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
31,431
[Feature Request]: Set ELECTRON_USE_REMOTE_CHECKSUMS from `.npmrc`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 Starting with Electron 15 consuming custom electron binaries from a custom mirror requires setting the `ELECTRON_USE_REMOTE_CHECKSUMS` environment variable, otherwise the checksum match fails. Specifying environment variables is cumbersome across all dev and CI hosts. ### Proposed Solution If the electron installer script also looked at the `.npmrc` it would be a one time configuration option for the project and wouldn't require additional step (of setting env variable) during dev host setup. @electron/get allows setting the mirror options this way. ### Alternatives Considered Other option could be an npm package config, which would also work. @electron/get also allows setting the mirror options this way. ### Additional Information _No response_
https://github.com/electron/electron/issues/31431
https://github.com/electron/electron/pull/40253
29d7be1565f6d5bcd4f8b5d95ccb77baece81717
f5262060957b7e32b33d64b3529a69417bdb5c26
2021-10-14T18:01:44Z
c++
2023-10-31T20:51:59Z
npm/install.js
#!/usr/bin/env node const { version } = require('./package'); const childProcess = require('child_process'); const fs = require('fs'); const os = require('os'); const path = require('path'); const extract = require('extract-zip'); const { downloadArtifact } = require('@electron/get'); if (process.env.ELECTRON_SKIP_BINARY_DOWNLOAD) { process.exit(0); } const platformPath = getPlatformPath(); if (isInstalled()) { process.exit(0); } const platform = process.env.npm_config_platform || process.platform; let arch = process.env.npm_config_arch || process.arch; if (platform === 'darwin' && process.platform === 'darwin' && arch === 'x64' && process.env.npm_config_arch === undefined) { // When downloading for macOS ON macOS and we think we need x64 we should // check if we're running under rosetta and download the arm64 version if appropriate try { const output = childProcess.execSync('sysctl -in sysctl.proc_translated'); if (output.toString().trim() === '1') { arch = 'arm64'; } } catch { // Ignore failure } } // downloads if not cached downloadArtifact({ version, artifactName: 'electron', force: process.env.force_no_cache === 'true', cacheRoot: process.env.electron_config_cache, checksums: process.env.electron_use_remote_checksums ? undefined : require('./checksums.json'), platform, arch }).then(extractFile).catch(err => { console.error(err.stack); process.exit(1); }); function isInstalled () { try { if (fs.readFileSync(path.join(__dirname, 'dist', 'version'), 'utf-8').replace(/^v/, '') !== version) { return false; } if (fs.readFileSync(path.join(__dirname, 'path.txt'), 'utf-8') !== platformPath) { return false; } } catch (ignored) { return false; } const electronPath = process.env.ELECTRON_OVERRIDE_DIST_PATH || path.join(__dirname, 'dist', platformPath); return fs.existsSync(electronPath); } // unzips and makes path.txt point at the correct executable function extractFile (zipPath) { const distPath = process.env.ELECTRON_OVERRIDE_DIST_PATH || path.join(__dirname, 'dist'); return extract(zipPath, { dir: path.join(__dirname, 'dist') }).then(() => { // If the zip contains an "electron.d.ts" file, // move that up const srcTypeDefPath = path.join(distPath, 'electron.d.ts'); const targetTypeDefPath = path.join(__dirname, 'electron.d.ts'); const hasTypeDefinitions = fs.existsSync(srcTypeDefPath); if (hasTypeDefinitions) { fs.renameSync(srcTypeDefPath, targetTypeDefPath); } // Write a "path.txt" file. return fs.promises.writeFile(path.join(__dirname, 'path.txt'), platformPath); }); } function getPlatformPath () { const platform = process.env.npm_config_platform || os.platform(); switch (platform) { case 'mas': case 'darwin': return 'Electron.app/Contents/MacOS/Electron'; case 'freebsd': case 'openbsd': case 'linux': return 'electron'; case 'win32': return 'electron.exe'; default: throw new Error('Electron builds are not available on platform: ' + platform); } }
closed
electron/electron
https://github.com/electron/electron
31,431
[Feature Request]: Set ELECTRON_USE_REMOTE_CHECKSUMS from `.npmrc`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 Starting with Electron 15 consuming custom electron binaries from a custom mirror requires setting the `ELECTRON_USE_REMOTE_CHECKSUMS` environment variable, otherwise the checksum match fails. Specifying environment variables is cumbersome across all dev and CI hosts. ### Proposed Solution If the electron installer script also looked at the `.npmrc` it would be a one time configuration option for the project and wouldn't require additional step (of setting env variable) during dev host setup. @electron/get allows setting the mirror options this way. ### Alternatives Considered Other option could be an npm package config, which would also work. @electron/get also allows setting the mirror options this way. ### Additional Information _No response_
https://github.com/electron/electron/issues/31431
https://github.com/electron/electron/pull/40253
29d7be1565f6d5bcd4f8b5d95ccb77baece81717
f5262060957b7e32b33d64b3529a69417bdb5c26
2021-10-14T18:01:44Z
c++
2023-10-31T20:51:59Z
docs/tutorial/installation.md
# Advanced Installation Instructions To install prebuilt Electron binaries, use [`npm`][npm]. The preferred method is to install Electron as a development dependency in your app: ```sh npm install electron --save-dev ``` See the [Electron versioning doc][versioning] for info on how to manage Electron versions in your apps. ## Running Electron ad-hoc If you're in a pinch and would prefer to not use `npm install` in your local project, you can also run Electron ad-hoc using the [`npx`][npx] command runner bundled with `npm`: ```sh npx electron . ``` The above command will run the current working directory with Electron. Note that any dependencies in your app will not be installed. ## Customization If you want to change the architecture that is downloaded (e.g., `ia32` on an `x64` machine), you can use the `--arch` flag with npm install or set the `npm_config_arch` environment variable: ```shell npm install --arch=ia32 electron ``` In addition to changing the architecture, you can also specify the platform (e.g., `win32`, `linux`, etc.) using the `--platform` flag: ```shell npm install --platform=win32 electron ``` ## Proxies If you need to use an HTTP proxy, you need to set the `ELECTRON_GET_USE_PROXY` variable to any value, plus additional environment variables depending on your host system's Node version: * [Node 10 and above][proxy-env-10] * [Before Node 10][proxy-env] ## Custom Mirrors and Caches During installation, the `electron` module will call out to [`@electron/get`][electron-get] to download prebuilt binaries of Electron for your platform. It will do so by contacting GitHub's release download page (`https://github.com/electron/electron/releases/tag/v$VERSION`, where `$VERSION` is the exact version of Electron). If you are unable to access GitHub or you need to provide a custom build, you can do so by either providing a mirror or an existing cache directory. #### Mirror You can use environment variables to override the base URL, the path at which to look for Electron binaries, and the binary filename. The URL used by `@electron/get` is composed as follows: ```javascript @ts-nocheck url = ELECTRON_MIRROR + ELECTRON_CUSTOM_DIR + '/' + ELECTRON_CUSTOM_FILENAME ``` For instance, to use the China CDN mirror: ```shell ELECTRON_MIRROR="https://npmmirror.com/mirrors/electron/" ``` By default, `ELECTRON_CUSTOM_DIR` is set to `v$VERSION`. To change the format, use the `{{ version }}` placeholder. For example, `version-{{ version }}` resolves to `version-5.0.0`, `{{ version }}` resolves to `5.0.0`, and `v{{ version }}` is equivalent to the default. As a more concrete example, to use the China non-CDN mirror: ```shell ELECTRON_MIRROR="https://npmmirror.com/mirrors/electron/" ELECTRON_CUSTOM_DIR="{{ version }}" ``` The above configuration will download from URLs such as `https://npmmirror.com/mirrors/electron/8.0.0/electron-v8.0.0-linux-x64.zip`. If your mirror serves artifacts with different checksums to the official Electron release you may have to set `electron_use_remote_checksums=1` to force Electron to use the remote `SHASUMS256.txt` file to verify the checksum instead of the embedded checksums. #### Cache Alternatively, you can override the local cache. `@electron/get` will cache downloaded binaries in a local directory to not stress your network. You can use that cache folder to provide custom builds of Electron or to avoid making contact with the network at all. * Linux: `$XDG_CACHE_HOME` or `~/.cache/electron/` * macOS: `~/Library/Caches/electron/` * Windows: `$LOCALAPPDATA/electron/Cache` or `~/AppData/Local/electron/Cache/` On environments that have been using older versions of Electron, you might find the cache also in `~/.electron`. You can also override the local cache location by providing a `electron_config_cache` environment variable. The cache contains the version's official zip file as well as a checksum, and is stored as `[checksum]/[filename]`. A typical cache might look like this: ```sh ├── a91b089b5dc5b1279966511344b805ec84869b6cd60af44f800b363bba25b915 │ └── electron-v15.3.1-darwin-x64.zip ``` ## Skip binary download Under the hood, Electron's JavaScript API binds to a binary that contains its implementations. Because this binary is crucial to the function of any Electron app, it is downloaded by default in the `postinstall` step every time you install `electron` from the npm registry. However, if you want to install your project's dependencies but don't need to use Electron functionality, you can set the `ELECTRON_SKIP_BINARY_DOWNLOAD` environment variable to prevent the binary from being downloaded. For instance, this feature can be useful in continuous integration environments when running unit tests that mock out the `electron` module. ```sh npm2yarn ELECTRON_SKIP_BINARY_DOWNLOAD=1 npm install ``` ## Troubleshooting When running `npm install electron`, some users occasionally encounter installation errors. In almost all cases, these errors are the result of network problems and not actual issues with the `electron` npm package. Errors like `ELIFECYCLE`, `EAI_AGAIN`, `ECONNRESET`, and `ETIMEDOUT` are all indications of such network problems. The best resolution is to try switching networks, or wait a bit and try installing again. You can also attempt to download Electron directly from [electron/electron/releases][releases] if installing via `npm` is failing. If installation fails with an `EACCESS` error you may need to [fix your npm permissions][npm-permissions]. If the above error persists, the [unsafe-perm][unsafe-perm] flag may need to be set to true: ```sh sudo npm install electron --unsafe-perm=true ``` On slower networks, it may be advisable to use the `--verbose` flag in order to show download progress: ```sh npm install --verbose electron ``` If you need to force a re-download of the asset and the SHASUM file set the `force_no_cache` environment variable to `true`. [npm]: https://docs.npmjs.com [versioning]: ./electron-versioning.md [npx]: https://docs.npmjs.com/cli/v7/commands/npx [releases]: https://github.com/electron/electron/releases [proxy-env-10]: https://github.com/gajus/global-agent/blob/v2.1.5/README.md#environment-variables [proxy-env]: https://github.com/np-maintain/global-tunnel/blob/v2.7.1/README.md#auto-config [electron-get]: https://github.com/electron/get [npm-permissions]: https://docs.npmjs.com/getting-started/fixing-npm-permissions [unsafe-perm]: https://docs.npmjs.com/misc/config#unsafe-perm
closed
electron/electron
https://github.com/electron/electron
31,431
[Feature Request]: Set ELECTRON_USE_REMOTE_CHECKSUMS from `.npmrc`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 Starting with Electron 15 consuming custom electron binaries from a custom mirror requires setting the `ELECTRON_USE_REMOTE_CHECKSUMS` environment variable, otherwise the checksum match fails. Specifying environment variables is cumbersome across all dev and CI hosts. ### Proposed Solution If the electron installer script also looked at the `.npmrc` it would be a one time configuration option for the project and wouldn't require additional step (of setting env variable) during dev host setup. @electron/get allows setting the mirror options this way. ### Alternatives Considered Other option could be an npm package config, which would also work. @electron/get also allows setting the mirror options this way. ### Additional Information _No response_
https://github.com/electron/electron/issues/31431
https://github.com/electron/electron/pull/40253
29d7be1565f6d5bcd4f8b5d95ccb77baece81717
f5262060957b7e32b33d64b3529a69417bdb5c26
2021-10-14T18:01:44Z
c++
2023-10-31T20:51:59Z
npm/install.js
#!/usr/bin/env node const { version } = require('./package'); const childProcess = require('child_process'); const fs = require('fs'); const os = require('os'); const path = require('path'); const extract = require('extract-zip'); const { downloadArtifact } = require('@electron/get'); if (process.env.ELECTRON_SKIP_BINARY_DOWNLOAD) { process.exit(0); } const platformPath = getPlatformPath(); if (isInstalled()) { process.exit(0); } const platform = process.env.npm_config_platform || process.platform; let arch = process.env.npm_config_arch || process.arch; if (platform === 'darwin' && process.platform === 'darwin' && arch === 'x64' && process.env.npm_config_arch === undefined) { // When downloading for macOS ON macOS and we think we need x64 we should // check if we're running under rosetta and download the arm64 version if appropriate try { const output = childProcess.execSync('sysctl -in sysctl.proc_translated'); if (output.toString().trim() === '1') { arch = 'arm64'; } } catch { // Ignore failure } } // downloads if not cached downloadArtifact({ version, artifactName: 'electron', force: process.env.force_no_cache === 'true', cacheRoot: process.env.electron_config_cache, checksums: process.env.electron_use_remote_checksums ? undefined : require('./checksums.json'), platform, arch }).then(extractFile).catch(err => { console.error(err.stack); process.exit(1); }); function isInstalled () { try { if (fs.readFileSync(path.join(__dirname, 'dist', 'version'), 'utf-8').replace(/^v/, '') !== version) { return false; } if (fs.readFileSync(path.join(__dirname, 'path.txt'), 'utf-8') !== platformPath) { return false; } } catch (ignored) { return false; } const electronPath = process.env.ELECTRON_OVERRIDE_DIST_PATH || path.join(__dirname, 'dist', platformPath); return fs.existsSync(electronPath); } // unzips and makes path.txt point at the correct executable function extractFile (zipPath) { const distPath = process.env.ELECTRON_OVERRIDE_DIST_PATH || path.join(__dirname, 'dist'); return extract(zipPath, { dir: path.join(__dirname, 'dist') }).then(() => { // If the zip contains an "electron.d.ts" file, // move that up const srcTypeDefPath = path.join(distPath, 'electron.d.ts'); const targetTypeDefPath = path.join(__dirname, 'electron.d.ts'); const hasTypeDefinitions = fs.existsSync(srcTypeDefPath); if (hasTypeDefinitions) { fs.renameSync(srcTypeDefPath, targetTypeDefPath); } // Write a "path.txt" file. return fs.promises.writeFile(path.join(__dirname, 'path.txt'), platformPath); }); } function getPlatformPath () { const platform = process.env.npm_config_platform || os.platform(); switch (platform) { case 'mas': case 'darwin': return 'Electron.app/Contents/MacOS/Electron'; case 'freebsd': case 'openbsd': case 'linux': return 'electron'; case 'win32': return 'electron.exe'; default: throw new Error('Electron builds are not available on platform: ' + platform); } }
closed
electron/electron
https://github.com/electron/electron
40,391
[Bug]: App crashes when unloading webview before it finished rendering since Electron 26.1.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 27.0.2 ### What operating system are you using? Windows ### Operating System Version Windows 10/11 ### What arch are you using? x64 ### Last Known Working Electron version 16.0.0 ### Expected Behavior The application should just move on and not crash. ### Actual Behavior The application closes without any error message shown or logged. ### Testcase Gist URL https://github.com/wartab/electron-bug ### Additional Information I previously reported this here, but another customer of ours had this issue happen on a fast PC and I could reproduce it on mine as well. https://github.com/electron/electron/issues/40288 I can't reproduce it in Electron Fiddle, but the following repository reproduces the issue. It attempts to load a webview with inline HTML in the src attribute. That HTML is > 3 MB large with inline images. Electron never manages to render this webview, but when unloading the webview, the app crashes. Simply removing the webview with removeChild() didn't crash the application, so my minimum reproduction is a bit closer to what we actually do. It is in an Angular application. The reproduction contains the app already built in `dist-angular`. To reproduce: `npm i` Optionally: `ng build --base-href .` `npm run-script build-electron`
https://github.com/electron/electron/issues/40391
https://github.com/electron/electron/pull/40400
f501dabc8064fa441e959d2203c706801aa21a22
5b18d90597a4a9fd837125786ac29af2151d6931
2023-10-31T17:01:30Z
c++
2023-11-03T14:36:25Z
shell/browser/web_view_guest_delegate.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/web_view_guest_delegate.h" #include <memory> #include "content/browser/web_contents/web_contents_impl.h" // nogncheck #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 "shell/browser/api/electron_api_web_contents.h" #include "third_party/blink/public/common/page/page_zoom.h" namespace electron { WebViewGuestDelegate::WebViewGuestDelegate(content::WebContents* embedder, api::WebContents* api_web_contents) : embedder_web_contents_(embedder), api_web_contents_(api_web_contents) {} WebViewGuestDelegate::~WebViewGuestDelegate() { ResetZoomController(); } void WebViewGuestDelegate::AttachToIframe( content::WebContents* embedder_web_contents, int embedder_frame_id) { embedder_web_contents_ = embedder_web_contents; int embedder_process_id = embedder_web_contents_->GetPrimaryMainFrame()->GetProcess()->GetID(); auto* embedder_frame = content::RenderFrameHost::FromID(embedder_process_id, embedder_frame_id); DCHECK_EQ(embedder_web_contents_, content::WebContents::FromRenderFrameHost(embedder_frame)); content::WebContents* guest_web_contents = api_web_contents_->web_contents(); // Force a refresh of the webPreferences so that OverrideWebkitPrefs runs on // the new web contents before the renderer process initializes. // guest_web_contents->NotifyPreferencesChanged(); // Attach this inner WebContents |guest_web_contents| to the outer // WebContents |embedder_web_contents|. The outer WebContents's // frame |embedder_frame| hosts the inner WebContents. embedder_web_contents_->AttachInnerWebContents( base::WrapUnique<content::WebContents>(guest_web_contents), embedder_frame, /*remote_frame=*/mojo::NullAssociatedRemote(), /*remote_frame_host_receiver=*/mojo::NullAssociatedReceiver(), /*is_full_page=*/false); ResetZoomController(); embedder_zoom_controller_ = WebContentsZoomController::FromWebContents(embedder_web_contents_); embedder_zoom_controller_->AddObserver(this); auto* zoom_controller = api_web_contents_->GetZoomController(); zoom_controller->SetEmbedderZoomController(embedder_zoom_controller_); api_web_contents_->Emit("did-attach"); } void WebViewGuestDelegate::WillDestroy() { ResetZoomController(); } content::WebContents* WebViewGuestDelegate::GetOwnerWebContents() { return embedder_web_contents_; } void WebViewGuestDelegate::OnZoomChanged( const WebContentsZoomController::ZoomChangedEventData& data) { if (data.web_contents == GetOwnerWebContents()) { if (data.temporary) { api_web_contents_->GetZoomController()->SetTemporaryZoomLevel( data.new_zoom_level); } else { api_web_contents_->GetZoomController()->SetZoomLevel(data.new_zoom_level); } // Change the default zoom factor to match the embedders' new zoom level. double zoom_factor = blink::PageZoomLevelToZoomFactor(data.new_zoom_level); api_web_contents_->GetZoomController()->SetDefaultZoomFactor(zoom_factor); } } void WebViewGuestDelegate::OnZoomControllerDestroyed( WebContentsZoomController* zoom_controller) { ResetZoomController(); } void WebViewGuestDelegate::ResetZoomController() { if (embedder_zoom_controller_) { embedder_zoom_controller_->RemoveObserver(this); embedder_zoom_controller_ = nullptr; } } std::unique_ptr<content::WebContents> WebViewGuestDelegate::CreateNewGuestWindow( const content::WebContents::CreateParams& create_params) { // Code below mirrors what content::WebContentsImpl::CreateNewWindow // does for non-guest sources content::WebContents::CreateParams guest_params(create_params); guest_params.context = embedder_web_contents_->GetNativeView(); std::unique_ptr<content::WebContents> guest_contents = content::WebContents::Create(guest_params); if (!create_params.opener_suppressed) { auto* guest_contents_impl = static_cast<content::WebContentsImpl*>(guest_contents.release()); auto* new_guest_view = guest_contents_impl->GetView(); content::RenderWidgetHostView* widget_view = new_guest_view->CreateViewForWidget( guest_contents_impl->GetRenderViewHost()->GetWidget()); if (!create_params.initially_hidden) widget_view->Show(); return base::WrapUnique( static_cast<content::WebContentsImpl*>(guest_contents_impl)); } return guest_contents; } base::WeakPtr<content::BrowserPluginGuestDelegate> WebViewGuestDelegate::GetGuestDelegateWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,391
[Bug]: App crashes when unloading webview before it finished rendering since Electron 26.1.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 27.0.2 ### What operating system are you using? Windows ### Operating System Version Windows 10/11 ### What arch are you using? x64 ### Last Known Working Electron version 16.0.0 ### Expected Behavior The application should just move on and not crash. ### Actual Behavior The application closes without any error message shown or logged. ### Testcase Gist URL https://github.com/wartab/electron-bug ### Additional Information I previously reported this here, but another customer of ours had this issue happen on a fast PC and I could reproduce it on mine as well. https://github.com/electron/electron/issues/40288 I can't reproduce it in Electron Fiddle, but the following repository reproduces the issue. It attempts to load a webview with inline HTML in the src attribute. That HTML is > 3 MB large with inline images. Electron never manages to render this webview, but when unloading the webview, the app crashes. Simply removing the webview with removeChild() didn't crash the application, so my minimum reproduction is a bit closer to what we actually do. It is in an Angular application. The reproduction contains the app already built in `dist-angular`. To reproduce: `npm i` Optionally: `ng build --base-href .` `npm run-script build-electron`
https://github.com/electron/electron/issues/40391
https://github.com/electron/electron/pull/40400
f501dabc8064fa441e959d2203c706801aa21a22
5b18d90597a4a9fd837125786ac29af2151d6931
2023-10-31T17:01:30Z
c++
2023-11-03T14:36:25Z
shell/browser/web_view_guest_delegate.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/web_view_guest_delegate.h" #include <memory> #include "content/browser/web_contents/web_contents_impl.h" // nogncheck #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 "shell/browser/api/electron_api_web_contents.h" #include "third_party/blink/public/common/page/page_zoom.h" namespace electron { WebViewGuestDelegate::WebViewGuestDelegate(content::WebContents* embedder, api::WebContents* api_web_contents) : embedder_web_contents_(embedder), api_web_contents_(api_web_contents) {} WebViewGuestDelegate::~WebViewGuestDelegate() { ResetZoomController(); } void WebViewGuestDelegate::AttachToIframe( content::WebContents* embedder_web_contents, int embedder_frame_id) { embedder_web_contents_ = embedder_web_contents; int embedder_process_id = embedder_web_contents_->GetPrimaryMainFrame()->GetProcess()->GetID(); auto* embedder_frame = content::RenderFrameHost::FromID(embedder_process_id, embedder_frame_id); DCHECK_EQ(embedder_web_contents_, content::WebContents::FromRenderFrameHost(embedder_frame)); content::WebContents* guest_web_contents = api_web_contents_->web_contents(); // Force a refresh of the webPreferences so that OverrideWebkitPrefs runs on // the new web contents before the renderer process initializes. // guest_web_contents->NotifyPreferencesChanged(); // Attach this inner WebContents |guest_web_contents| to the outer // WebContents |embedder_web_contents|. The outer WebContents's // frame |embedder_frame| hosts the inner WebContents. embedder_web_contents_->AttachInnerWebContents( base::WrapUnique<content::WebContents>(guest_web_contents), embedder_frame, /*remote_frame=*/mojo::NullAssociatedRemote(), /*remote_frame_host_receiver=*/mojo::NullAssociatedReceiver(), /*is_full_page=*/false); ResetZoomController(); embedder_zoom_controller_ = WebContentsZoomController::FromWebContents(embedder_web_contents_); embedder_zoom_controller_->AddObserver(this); auto* zoom_controller = api_web_contents_->GetZoomController(); zoom_controller->SetEmbedderZoomController(embedder_zoom_controller_); api_web_contents_->Emit("did-attach"); } void WebViewGuestDelegate::WillDestroy() { ResetZoomController(); } content::WebContents* WebViewGuestDelegate::GetOwnerWebContents() { return embedder_web_contents_; } void WebViewGuestDelegate::OnZoomChanged( const WebContentsZoomController::ZoomChangedEventData& data) { if (data.web_contents == GetOwnerWebContents()) { if (data.temporary) { api_web_contents_->GetZoomController()->SetTemporaryZoomLevel( data.new_zoom_level); } else { api_web_contents_->GetZoomController()->SetZoomLevel(data.new_zoom_level); } // Change the default zoom factor to match the embedders' new zoom level. double zoom_factor = blink::PageZoomLevelToZoomFactor(data.new_zoom_level); api_web_contents_->GetZoomController()->SetDefaultZoomFactor(zoom_factor); } } void WebViewGuestDelegate::OnZoomControllerDestroyed( WebContentsZoomController* zoom_controller) { ResetZoomController(); } void WebViewGuestDelegate::ResetZoomController() { if (embedder_zoom_controller_) { embedder_zoom_controller_->RemoveObserver(this); embedder_zoom_controller_ = nullptr; } } std::unique_ptr<content::WebContents> WebViewGuestDelegate::CreateNewGuestWindow( const content::WebContents::CreateParams& create_params) { // Code below mirrors what content::WebContentsImpl::CreateNewWindow // does for non-guest sources content::WebContents::CreateParams guest_params(create_params); guest_params.context = embedder_web_contents_->GetNativeView(); std::unique_ptr<content::WebContents> guest_contents = content::WebContents::Create(guest_params); if (!create_params.opener_suppressed) { auto* guest_contents_impl = static_cast<content::WebContentsImpl*>(guest_contents.release()); auto* new_guest_view = guest_contents_impl->GetView(); content::RenderWidgetHostView* widget_view = new_guest_view->CreateViewForWidget( guest_contents_impl->GetRenderViewHost()->GetWidget()); if (!create_params.initially_hidden) widget_view->Show(); return base::WrapUnique( static_cast<content::WebContentsImpl*>(guest_contents_impl)); } return guest_contents; } base::WeakPtr<content::BrowserPluginGuestDelegate> WebViewGuestDelegate::GetGuestDelegateWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,914
[Bug]: In Mac OS Sonoma (14.0) showInactive, is not inactive anymore
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 26.2.1 ### What operating system are you using? macOS ### Operating System Version Mac OS Sonoma 14 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When `window.showIncative()` the focus is still on the app below the window that you just make appear. The menu is still the menu from the app below and not the menu from your app. My window is in `type: panel` ### Actual Behavior When window `type: panel` and on `window.showIncative()` the electron js app becomes active, the app's menu shows. This wasn't the behavior on the previous Mac OS version. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/39914
https://github.com/electron/electron/pull/40307
7999ea39e2ee9702e64e4125e8e89c314e9f468f
b55d7f4a16293164693618b8a0822370f7f4d46c
2023-09-19T12:27:14Z
c++
2023-11-06T21:38:12Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/apple/scoped_cftyperef.h" #include "base/mac/mac_util.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } NSView* GetNativeNSView(NativeBrowserView* view) { if (auto* inspectable = view->GetInspectableWebContentsView()) { return inspectable->GetNativeView().GetNativeNSView(); } else { return nullptr; } } } // 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_); bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this]; [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_]; [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } set_wants_to_be_visible(true); // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // If the window wants to be visible and has a parent, then the parent may // order it back in (in the period between orderOut: and close). set_wants_to_be_visible(false); DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow() { if (parent() && !is_modal()) { parent()->RemoveChildWindow(this); NativeWindow::SetParentWindow(nullptr); } } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { if (!static_cast<NativeWindowMac*>(child)->wants_to_be_visible()) continue; auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } void NativeWindowMac::SetFullScreen(bool fullscreen) { // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; if (![window_ toggleFullScreenMode:nil]) fullscreen_transition_state_ = FullScreenTransitionState::kNone; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { // Apply the size constraints to NSWindow. if (window_constraints.HasMinimumSize()) [window_ setMinSize:window_constraints.GetMinimumSize().ToCGSize()]; if (window_constraints.HasMaximumSize()) [window_ setMaxSize:window_constraints.GetMaximumSize().ToCGSize()]; NativeWindow::SetSizeConstraints(window_constraints); } 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()); } }; // Apply the size constraints to NSWindow. NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:0]; } else { ReorderChildWindowAbove(window_, nullptr); } } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); bool was_fullscreenable = IsFullScreenable(); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreen collection behavior as well as the maximize traffic // light in SetCanResize if resizability is false on macOS unless // the window is both resizable and maximizable. We want consistent // cross-platform behavior, so if resizability is disabled we disable // the maximize button and ensure fullscreenability matches user setting. SetCanResize(resizable); SetFullScreenable(was_fullscreenable); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:resizable ? was_fullscreenable : false]; } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::apple::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (auto* native_view = GetNativeNSView(view)) { [[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 (auto* native_view = GetNativeNSView(view)) { [native_view 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 (auto* native_view = GetNativeNSView(view)) { [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[NSImageView alloc] init]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[ElectronProgressBar alloc] initWithFrame:frame]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); const int macos_version = base::mac::MacOSMajorVersion(); // Modal window corners are rounded on macOS >= 11 or higher if the user // hasn't passed noRoundedCorners. bool should_round_modal = !no_rounded_corner && (macos_version >= 11 ? true : !is_modal()); // Nonmodal window corners are rounded if they're frameless and the user // hasn't passed noRoundedCorners. bool should_round_nonmodal = !no_rounded_corner && !has_frame(); if (should_round_nonmodal || should_round_modal) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (macos_version >= 11) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NativeWindow::SetVibrancy(type); NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ window:this settings:std::move(items)]; [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::ShowAllTabs() { [window_ toggleTabOverview:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } absl::optional<std::string> NativeWindowMac::GetTabbingIdentifier() const { if ([window_ tabbingMode] == NSWindowTabbingModeDisallowed) return absl::nullopt; return base::SysNSStringToUTF8([window_ tabbingIdentifier]); } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_ = [[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]; [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:NO]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:YES]; } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { CALayer* background_layer = [[CALayer alloc] init]; [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(); // Set new parent window. if (new_parent) { new_parent->add_child_window(this); if (attach) new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } absl::optional<gfx::Rect> NativeWindowMac::GetWindowControlsOverlayRect() { if (!titlebar_overlay_) return absl::nullopt; // On macOS, when in fullscreen mode, window controls (the menu bar, title // bar, and toolbar) are attached to a separate NSView that slides down from // the top of the screen, independent of, and overlapping the WebContents. // Disable WCO when in fullscreen, because this space is inaccessible to // WebContents. https://crbug.com/915110. if (IsFullscreen()) return gfx::Rect(); if (buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); overlay.set_height([buttons_proxy_ useCustomHeight] ? titlebar_overlay_height() : NSHeight(buttons)); if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return absl::nullopt; } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,914
[Bug]: In Mac OS Sonoma (14.0) showInactive, is not inactive anymore
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 26.2.1 ### What operating system are you using? macOS ### Operating System Version Mac OS Sonoma 14 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When `window.showIncative()` the focus is still on the app below the window that you just make appear. The menu is still the menu from the app below and not the menu from your app. My window is in `type: panel` ### Actual Behavior When window `type: panel` and on `window.showIncative()` the electron js app becomes active, the app's menu shows. This wasn't the behavior on the previous Mac OS version. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/39914
https://github.com/electron/electron/pull/40307
7999ea39e2ee9702e64e4125e8e89c314e9f468f
b55d7f4a16293164693618b8a0822370f7f4d46c
2023-09-19T12:27:14Z
c++
2023-11-06T21:38:12Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as http from 'node:http'; import * as os from 'node:os'; import { AddressInfo } from 'node:net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; const fixtures = path.resolve(__dirname, 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { it('sets the correct class name on the prototype', () => { expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow'); }); describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. const wr = new WeakRef(w); await setTimeout(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = once(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = once(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await once(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); for (const win of windows) win.show(); for (const win of windows) win.focus(); for (const win of windows) win.destroy(); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w: BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server: http.Server; let url: string; let postData = null as any; before(async () => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); describe('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); url = (await listen(server)).url; }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(url + '/navigate'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(url + '/redirect'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(url + '/in-page'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = once(w, 'maximize'); const shown = once(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await setTimeout(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { afterEach(closeAllWindows); it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); it('should not crash when called on a modal child window', async () => { const shown = once(w, 'show'); w.show(); await shown; const child = new BrowserWindow({ modal: true, parent: w }); expect(() => { child.moveTop(); }).to.not.throw(); }); }); describe('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; for (const sourceId of fakeSourceIds) { 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]; for (const sourceId of fakeSourceIds) { 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']; for (const sourceId of fakeSourceIds) { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); } }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = once(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = once(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.showAllTabs()', () => { it('does not throw', () => { expect(() => { w.showAllTabs(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); describe('BrowserWindow.tabbingIdentifier', () => { it('is undefined if no tabbingIdentifier was set', () => { const w = new BrowserWindow({ show: false }); expect(w.tabbingIdentifier).to.be.undefined('tabbingIdentifier'); }); it('returns the window tabbingIdentifier', () => { const w = new BrowserWindow({ show: false, tabbingIdentifier: 'group1' }); expect(w.tabbingIdentifier).to.equal('group1'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves when the window is occluded', async () => { const w1 = new BrowserWindow({ show: false }); w1.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w1, 'ready-to-show'); w1.show(); const w2 = new BrowserWindow({ show: false }); w2.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w2, 'ready-to-show'); w2.show(); const visibleImage = await w1.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); }); it('resolves when the window is not visible', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.minimize(); const hiddenImage = await w.capturePage(); expect(hiddenImage.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w: BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w: BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = once(w, 'always-on-top-changed') as Promise<[any, boolean]>; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect(c._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w: BrowserWindow; let server: http.Server; let url: string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); url = (await listen(server)).url; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = once(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('titlebar'); w.setVibrancy('selection'); w.setVibrancy(null); w.setVibrancy('menu'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created') as [any, WebContents]; expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); bv1.webContents.destroy(); bv2.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await once(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await once(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await once(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await once(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await once(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replaceAll('\\', '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('node:events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window') as [BrowserWindow, Electron.DidCreateWindowDetails]; const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replaceAll('\\', '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await once(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await once(app, 'browser-window-created') as [any, BrowserWindow]; // Ask the popup window for details. const detailsAnswer = once(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); const errorPattern = /Failed to read a named property 'document' from 'Window': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./; expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(errorPattern); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(errorPattern); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences!.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => once(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); expect(test.nodeEvents).to.equal(true); expect(test.nodeTimers).to.equal(true); expect(test.nodeUrl).to.equal(true); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Failed to read a named property \'toString\' from \'Location\': Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences!.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await once(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); // TODO(codebytere): figure out how to make these pass in CI on Windows. ifdescribe(process.platform !== 'win32')('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); it('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); it('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = once(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = once(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('can handle child window close and reparent multiple times', async () => { const w = new BrowserWindow({ show: false }); let c: BrowserWindow | null; for (let i = 0; i < 5; i++) { c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; } await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('only shows the intended window when a child with siblings is shown', async () => { const w = new BrowserWindow({ show: false }); const childOne = new BrowserWindow({ show: false, parent: w }); const childTwo = new BrowserWindow({ show: false, parent: w }); const parentShown = once(w, 'show'); w.show(); await parentShown; expect(childOne.isVisible()).to.be.false('childOne is visible'); expect(childTwo.isVisible()).to.be.false('childTwo is visible'); const childOneShown = once(childOne, 'show'); childOne.show(); await childOneShown; expect(childOne.isVisible()).to.be.true('childOne is not visible'); expect(childTwo.isVisible()).to.be.false('childTwo is visible'); }); ifit(process.platform === 'darwin')('child matches parent visibility when parent visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); ifit(process.platform === 'darwin')('parent matches child visibility when child visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(c, 'minimize'); c.minimize(); await minimized; expect(c.isVisible()).to.be.false('child is visible'); const restored = once(c, 'restore'); c.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); it('closes a grandchild window when a middle child window is destroyed', async () => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); const closed = once(childWindow, 'closed'); window.close(); await closed; expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = once(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('can reparent when the first parent is destroyed', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); c.setParentWindow(w1); expect(w1.getChildWindows().length).to.equal(1); const closed = once(w1, 'closed'); w1.destroy(); await closed; c.setParentWindow(w2); await setTimeout(); const children = w2.getChildWindows(); expect(children[0]).to.equal(c); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform !== 'darwin')('when fullscreen state is changed', () => { it('correctly remembers state prior to fullscreen change', async () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); it('correctly remembers state prior to fullscreen change with autoHide', async () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); it('does not open non-fullscreenable child windows in fullscreen if parent is fullscreen', async () => { const w = new BrowserWindow(); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const child = new BrowserWindow({ parent: w, resizable: false, fullscreenable: false }); const shown = once(child, 'show'); await shown; expect(child.resizable).to.be.false('resizable'); expect(child.fullScreen).to.be.false('fullscreen'); expect(child.fullScreenable).to.be.false('fullscreenable'); }); it('is set correctly with different resizable values', async () => { const w1 = new BrowserWindow({ resizable: false, fullscreenable: false }); const w2 = new BrowserWindow({ resizable: true, fullscreenable: false }); const w3 = new BrowserWindow({ fullscreenable: false }); expect(w1.isFullScreenable()).to.be.false('isFullScreenable'); expect(w2.isFullScreenable()).to.be.false('isFullScreenable'); expect(w3.isFullScreenable()).to.be.false('isFullScreenable'); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); const isValidWindow = require('@electron-ci/is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences()!.contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = once(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = once(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); describe('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(1000); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(1000); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); await setTimeout(1000); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
39,914
[Bug]: In Mac OS Sonoma (14.0) showInactive, is not inactive anymore
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 26.2.1 ### What operating system are you using? macOS ### Operating System Version Mac OS Sonoma 14 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When `window.showIncative()` the focus is still on the app below the window that you just make appear. The menu is still the menu from the app below and not the menu from your app. My window is in `type: panel` ### Actual Behavior When window `type: panel` and on `window.showIncative()` the electron js app becomes active, the app's menu shows. This wasn't the behavior on the previous Mac OS version. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/39914
https://github.com/electron/electron/pull/40307
7999ea39e2ee9702e64e4125e8e89c314e9f468f
b55d7f4a16293164693618b8a0822370f7f4d46c
2023-09-19T12:27:14Z
c++
2023-11-06T21:38:12Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/apple/scoped_cftyperef.h" #include "base/mac/mac_util.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } NSView* GetNativeNSView(NativeBrowserView* view) { if (auto* inspectable = view->GetInspectableWebContentsView()) { return inspectable->GetNativeView().GetNativeNSView(); } else { return nullptr; } } } // 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_); bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this]; [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_]; [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } set_wants_to_be_visible(true); // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // If the window wants to be visible and has a parent, then the parent may // order it back in (in the period between orderOut: and close). set_wants_to_be_visible(false); DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow() { if (parent() && !is_modal()) { parent()->RemoveChildWindow(this); NativeWindow::SetParentWindow(nullptr); } } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { if (!static_cast<NativeWindowMac*>(child)->wants_to_be_visible()) continue; auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } void NativeWindowMac::SetFullScreen(bool fullscreen) { // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; if (![window_ toggleFullScreenMode:nil]) fullscreen_transition_state_ = FullScreenTransitionState::kNone; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { // Apply the size constraints to NSWindow. if (window_constraints.HasMinimumSize()) [window_ setMinSize:window_constraints.GetMinimumSize().ToCGSize()]; if (window_constraints.HasMaximumSize()) [window_ setMaxSize:window_constraints.GetMaximumSize().ToCGSize()]; NativeWindow::SetSizeConstraints(window_constraints); } 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()); } }; // Apply the size constraints to NSWindow. NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:0]; } else { ReorderChildWindowAbove(window_, nullptr); } } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); bool was_fullscreenable = IsFullScreenable(); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreen collection behavior as well as the maximize traffic // light in SetCanResize if resizability is false on macOS unless // the window is both resizable and maximizable. We want consistent // cross-platform behavior, so if resizability is disabled we disable // the maximize button and ensure fullscreenability matches user setting. SetCanResize(resizable); SetFullScreenable(was_fullscreenable); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:resizable ? was_fullscreenable : false]; } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::apple::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (auto* native_view = GetNativeNSView(view)) { [[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 (auto* native_view = GetNativeNSView(view)) { [native_view 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 (auto* native_view = GetNativeNSView(view)) { [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[NSImageView alloc] init]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[ElectronProgressBar alloc] initWithFrame:frame]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); const int macos_version = base::mac::MacOSMajorVersion(); // Modal window corners are rounded on macOS >= 11 or higher if the user // hasn't passed noRoundedCorners. bool should_round_modal = !no_rounded_corner && (macos_version >= 11 ? true : !is_modal()); // Nonmodal window corners are rounded if they're frameless and the user // hasn't passed noRoundedCorners. bool should_round_nonmodal = !no_rounded_corner && !has_frame(); if (should_round_nonmodal || should_round_modal) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (macos_version >= 11) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NativeWindow::SetVibrancy(type); NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ window:this settings:std::move(items)]; [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::ShowAllTabs() { [window_ toggleTabOverview:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } absl::optional<std::string> NativeWindowMac::GetTabbingIdentifier() const { if ([window_ tabbingMode] == NSWindowTabbingModeDisallowed) return absl::nullopt; return base::SysNSStringToUTF8([window_ tabbingIdentifier]); } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_ = [[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]; [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:NO]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:YES]; } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { CALayer* background_layer = [[CALayer alloc] init]; [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(); // Set new parent window. if (new_parent) { new_parent->add_child_window(this); if (attach) new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } absl::optional<gfx::Rect> NativeWindowMac::GetWindowControlsOverlayRect() { if (!titlebar_overlay_) return absl::nullopt; // On macOS, when in fullscreen mode, window controls (the menu bar, title // bar, and toolbar) are attached to a separate NSView that slides down from // the top of the screen, independent of, and overlapping the WebContents. // Disable WCO when in fullscreen, because this space is inaccessible to // WebContents. https://crbug.com/915110. if (IsFullscreen()) return gfx::Rect(); if (buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); overlay.set_height([buttons_proxy_ useCustomHeight] ? titlebar_overlay_height() : NSHeight(buttons)); if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return absl::nullopt; } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,914
[Bug]: In Mac OS Sonoma (14.0) showInactive, is not inactive anymore
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 26.2.1 ### What operating system are you using? macOS ### Operating System Version Mac OS Sonoma 14 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When `window.showIncative()` the focus is still on the app below the window that you just make appear. The menu is still the menu from the app below and not the menu from your app. My window is in `type: panel` ### Actual Behavior When window `type: panel` and on `window.showIncative()` the electron js app becomes active, the app's menu shows. This wasn't the behavior on the previous Mac OS version. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/39914
https://github.com/electron/electron/pull/40307
7999ea39e2ee9702e64e4125e8e89c314e9f468f
b55d7f4a16293164693618b8a0822370f7f4d46c
2023-09-19T12:27:14Z
c++
2023-11-06T21:38:12Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as http from 'node:http'; import * as os from 'node:os'; import { AddressInfo } from 'node:net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; const fixtures = path.resolve(__dirname, 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { it('sets the correct class name on the prototype', () => { expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow'); }); describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. const wr = new WeakRef(w); await setTimeout(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = once(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = once(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await once(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); for (const win of windows) win.show(); for (const win of windows) win.focus(); for (const win of windows) win.destroy(); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w: BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server: http.Server; let url: string; let postData = null as any; before(async () => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); describe('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); url = (await listen(server)).url; }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(url + '/navigate'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(url + '/redirect'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(url + '/in-page'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = once(w, 'maximize'); const shown = once(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await setTimeout(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { afterEach(closeAllWindows); it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); it('should not crash when called on a modal child window', async () => { const shown = once(w, 'show'); w.show(); await shown; const child = new BrowserWindow({ modal: true, parent: w }); expect(() => { child.moveTop(); }).to.not.throw(); }); }); describe('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; for (const sourceId of fakeSourceIds) { 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]; for (const sourceId of fakeSourceIds) { 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']; for (const sourceId of fakeSourceIds) { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); } }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = once(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = once(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.showAllTabs()', () => { it('does not throw', () => { expect(() => { w.showAllTabs(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); describe('BrowserWindow.tabbingIdentifier', () => { it('is undefined if no tabbingIdentifier was set', () => { const w = new BrowserWindow({ show: false }); expect(w.tabbingIdentifier).to.be.undefined('tabbingIdentifier'); }); it('returns the window tabbingIdentifier', () => { const w = new BrowserWindow({ show: false, tabbingIdentifier: 'group1' }); expect(w.tabbingIdentifier).to.equal('group1'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves when the window is occluded', async () => { const w1 = new BrowserWindow({ show: false }); w1.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w1, 'ready-to-show'); w1.show(); const w2 = new BrowserWindow({ show: false }); w2.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w2, 'ready-to-show'); w2.show(); const visibleImage = await w1.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); }); it('resolves when the window is not visible', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.minimize(); const hiddenImage = await w.capturePage(); expect(hiddenImage.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w: BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w: BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = once(w, 'always-on-top-changed') as Promise<[any, boolean]>; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect(c._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w: BrowserWindow; let server: http.Server; let url: string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); url = (await listen(server)).url; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = once(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('titlebar'); w.setVibrancy('selection'); w.setVibrancy(null); w.setVibrancy('menu'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created') as [any, WebContents]; expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); bv1.webContents.destroy(); bv2.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await once(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await once(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await once(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await once(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await once(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replaceAll('\\', '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('node:events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window') as [BrowserWindow, Electron.DidCreateWindowDetails]; const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replaceAll('\\', '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await once(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await once(app, 'browser-window-created') as [any, BrowserWindow]; // Ask the popup window for details. const detailsAnswer = once(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); const errorPattern = /Failed to read a named property 'document' from 'Window': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./; expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(errorPattern); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(errorPattern); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences!.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => once(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); expect(test.nodeEvents).to.equal(true); expect(test.nodeTimers).to.equal(true); expect(test.nodeUrl).to.equal(true); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Failed to read a named property \'toString\' from \'Location\': Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences!.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await once(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); // TODO(codebytere): figure out how to make these pass in CI on Windows. ifdescribe(process.platform !== 'win32')('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); it('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); it('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = once(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = once(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('can handle child window close and reparent multiple times', async () => { const w = new BrowserWindow({ show: false }); let c: BrowserWindow | null; for (let i = 0; i < 5; i++) { c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; } await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('only shows the intended window when a child with siblings is shown', async () => { const w = new BrowserWindow({ show: false }); const childOne = new BrowserWindow({ show: false, parent: w }); const childTwo = new BrowserWindow({ show: false, parent: w }); const parentShown = once(w, 'show'); w.show(); await parentShown; expect(childOne.isVisible()).to.be.false('childOne is visible'); expect(childTwo.isVisible()).to.be.false('childTwo is visible'); const childOneShown = once(childOne, 'show'); childOne.show(); await childOneShown; expect(childOne.isVisible()).to.be.true('childOne is not visible'); expect(childTwo.isVisible()).to.be.false('childTwo is visible'); }); ifit(process.platform === 'darwin')('child matches parent visibility when parent visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); ifit(process.platform === 'darwin')('parent matches child visibility when child visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(c, 'minimize'); c.minimize(); await minimized; expect(c.isVisible()).to.be.false('child is visible'); const restored = once(c, 'restore'); c.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); it('closes a grandchild window when a middle child window is destroyed', async () => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); const closed = once(childWindow, 'closed'); window.close(); await closed; expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = once(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('can reparent when the first parent is destroyed', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); c.setParentWindow(w1); expect(w1.getChildWindows().length).to.equal(1); const closed = once(w1, 'closed'); w1.destroy(); await closed; c.setParentWindow(w2); await setTimeout(); const children = w2.getChildWindows(); expect(children[0]).to.equal(c); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform !== 'darwin')('when fullscreen state is changed', () => { it('correctly remembers state prior to fullscreen change', async () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); it('correctly remembers state prior to fullscreen change with autoHide', async () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); it('does not open non-fullscreenable child windows in fullscreen if parent is fullscreen', async () => { const w = new BrowserWindow(); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const child = new BrowserWindow({ parent: w, resizable: false, fullscreenable: false }); const shown = once(child, 'show'); await shown; expect(child.resizable).to.be.false('resizable'); expect(child.fullScreen).to.be.false('fullscreen'); expect(child.fullScreenable).to.be.false('fullscreenable'); }); it('is set correctly with different resizable values', async () => { const w1 = new BrowserWindow({ resizable: false, fullscreenable: false }); const w2 = new BrowserWindow({ resizable: true, fullscreenable: false }); const w3 = new BrowserWindow({ fullscreenable: false }); expect(w1.isFullScreenable()).to.be.false('isFullScreenable'); expect(w2.isFullScreenable()).to.be.false('isFullScreenable'); expect(w3.isFullScreenable()).to.be.false('isFullScreenable'); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); const isValidWindow = require('@electron-ci/is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences()!.contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = once(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = once(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); describe('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(1000); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(1000); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); await setTimeout(1000); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
40,457
[Bug]: Wrong types for HidDeviceRemovedDetails and HidDeviceAddedDetails
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.3 ### What operating system are you using? macOS ### Operating System Version 14.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior ```typescript interface HidDeviceAddedDetails { device: HIDDevice; frame: WebFrameMain; } interface HidDeviceRemovedDetails { device: HIDDevice; frame: WebFrameMain; } ``` ### Actual Behavior ```typescript interface HidDeviceAddedDetails { device: HIDDevice[]; frame: WebFrameMain; } interface HidDeviceRemovedDetails { device: HIDDevice[]; frame: WebFrameMain; } ``` ### Testcase Gist URL _No response_ ### Additional Information Currently provided typings for electron assume that device will be an array of HIDDevice while the actual binary provides with only instance.
https://github.com/electron/electron/issues/40457
https://github.com/electron/electron/pull/40462
e8d9294d9d51ca0e2eaae22d4f57561e79a08833
1ba535296efe87ecf0362759d2fab29b2af8b755
2023-11-06T14:18:02Z
c++
2023-11-07T22:26:35Z
docs/api/session.md
# session > Manage browser sessions, cookies, cache, proxy settings, etc. Process: [Main](../glossary.md#main-process) The `session` module can be used to create new `Session` objects. You can also access the `session` of existing pages by using the `session` property of [`WebContents`](web-contents.md), or from the `session` module. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('https://github.com') const ses = win.webContents.session console.log(ses.getUserAgent()) ``` ## Methods The `session` module has the following methods: ### `session.fromPartition(partition[, options])` * `partition` string * `options` Object (optional) * `cache` boolean - Whether to enable cache. Returns `Session` - A session instance from `partition` string. When there is an existing `Session` with the same `partition`, it will be returned; otherwise a new `Session` instance will be created with `options`. 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. If the `partition` is empty then default session of the app will be returned. To create a `Session` with `options`, you have to ensure the `Session` with the `partition` has never been used before. There is no way to change the `options` of an existing `Session` object. ### `session.fromPath(path[, options])` * `path` string * `options` Object (optional) * `cache` boolean - Whether to enable cache. Returns `Session` - A session instance from the absolute path as specified by the `path` string. When there is an existing `Session` with the same absolute path, it will be returned; otherwise a new `Session` instance will be created with `options`. The call will throw an error if the path is not an absolute path. Additionally, an error will be thrown if an empty string is provided. To create a `Session` with `options`, you have to ensure the `Session` with the `path` has never been used before. There is no way to change the `options` of an existing `Session` object. ## Properties The `session` module has the following properties: ### `session.defaultSession` A `Session` object, the default session object of the app. ## Class: Session > Get and set properties of a session. Process: [Main](../glossary.md#main-process)<br /> _This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ You can create a `Session` object in the `session` module: ```javascript const { session } = require('electron') const ses = session.fromPartition('persist:name') console.log(ses.getUserAgent()) ``` ### Instance Events The following events are available on instances of `Session`: #### Event: 'will-download' Returns: * `event` Event * `item` [DownloadItem](download-item.md) * `webContents` [WebContents](web-contents.md) Emitted when Electron is about to download `item` in `webContents`. Calling `event.preventDefault()` will cancel the download and `item` will not be available from next tick of the process. ```javascript @ts-expect-error=[4] const { session } = require('electron') session.defaultSession.on('will-download', (event, item, webContents) => { event.preventDefault() require('got')(item.getURL()).then((response) => { require('node:fs').writeFileSync('/somewhere', response.body) }) }) ``` #### Event: 'extension-loaded' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is loaded. This occurs whenever an extension is added to the "enabled" set of extensions. This includes: * Extensions being loaded from `Session.loadExtension`. * Extensions being reloaded: * from a crash. * if the extension requested it ([`chrome.runtime.reload()`](https://developer.chrome.com/extensions/runtime#method-reload)). #### Event: 'extension-unloaded' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is unloaded. This occurs when `Session.removeExtension` is called. #### Event: 'extension-ready' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is loaded and all necessary browser state is initialized to support the start of the extension's background page. #### Event: 'preconnect' Returns: * `event` Event * `preconnectUrl` string - The URL being requested for preconnection by the renderer. * `allowCredentials` boolean - True if the renderer is requesting that the connection include credentials (see the [spec](https://w3c.github.io/resource-hints/#preconnect) for more details.) Emitted when a render process requests preconnection to a URL, generally due to a [resource hint](https://w3c.github.io/resource-hints/). #### Event: 'spellcheck-dictionary-initialized' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file has been successfully initialized. This occurs after the file has been downloaded. #### Event: 'spellcheck-dictionary-download-begin' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file starts downloading #### Event: 'spellcheck-dictionary-download-success' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file has been successfully downloaded #### Event: 'spellcheck-dictionary-download-failure' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file download fails. For details on the failure you should collect a netlog and inspect the download request. #### Event: 'select-hid-device' Returns: * `event` Event * `details` Object * `deviceList` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) * `callback` Function * `deviceId` string | null (optional) Emitted when a HID device needs to be selected when a call to `navigator.hid.requestDevice` is made. `callback` should be called with `deviceId` to be selected; passing no arguments to `callback` will cancel the request. Additionally, permissioning on `navigator.hid` can be further managed by using [`ses.setPermissionCheckHandler(handler)`](#sessetpermissioncheckhandlerhandler) and [`ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler). ```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'hid') { // Add logic here to determine if permission should be given to allow HID selection return true } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } return false }) win.webContents.session.on('select-hid-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === 9025 && device.productId === 67 }) callback(selectedDevice?.deviceId) }) }) ``` #### Event: 'hid-device-added' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) Emitted after `navigator.hid.requestDevice` has been called and `select-hid-device` has fired if a new device becomes available before the callback from `select-hid-device` is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated with the newly added device. #### Event: 'hid-device-removed' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) Emitted after `navigator.hid.requestDevice` has been called and `select-hid-device` has fired if a device has been removed before the callback from `select-hid-device` is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated to remove the specified device. #### Event: 'hid-device-revoked' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `origin` string (optional) - The origin that the device has been revoked from. Emitted after `HIDDevice.forget()` has been called. This event can be used to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used. #### Event: 'select-serial-port' Returns: * `event` Event * `portList` [SerialPort[]](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) * `callback` Function * `portId` string Emitted when a serial port needs to be selected when a call to `navigator.serial.requestPort` is made. `callback` should be called with `portId` to be selected, passing an empty string to `callback` will cancel the request. Additionally, permissioning on `navigator.serial` can be managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler) with the `serial` permission. ```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'serial') { // Add logic here to determine if permission should be given to allow serial selection return true } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'serial') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.serial.requestPort` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } return false }) win.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { event.preventDefault() const selectedPort = portList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) if (!selectedPort) { callback('') } else { callback(selectedPort.portId) } }) }) ``` #### Event: 'serial-port-added' Returns: * `event` Event * `port` [SerialPort](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) Emitted after `navigator.serial.requestPort` has been called and `select-serial-port` has fired if a new serial port becomes available before the callback from `select-serial-port` is called. This event is intended for use when using a UI to ask users to pick a port so that the UI can be updated with the newly added port. #### Event: 'serial-port-removed' Returns: * `event` Event * `port` [SerialPort](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) Emitted after `navigator.serial.requestPort` has been called and `select-serial-port` has fired if a serial port has been removed before the callback from `select-serial-port` is called. This event is intended for use when using a UI to ask users to pick a port so that the UI can be updated to remove the specified port. #### Event: 'serial-port-revoked' Returns: * `event` Event * `details` Object * `port` [SerialPort](structures/serial-port.md) * `frame` [WebFrameMain](web-frame-main.md) * `origin` string - The origin that the device has been revoked from. Emitted after `SerialPort.forget()` has been called. This event can be used to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used. ```js // Browser Process const { app, BrowserWindow } = require('electron') app.whenReady().then(() => { const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.session.on('serial-port-revoked', (event, details) => { console.log(`Access revoked for serial device from origin ${details.origin}`) }) }) ``` ```js // Renderer Process const portConnect = async () => { // Request a port. const port = await navigator.serial.requestPort() // Wait for the serial port to open. await port.open({ baudRate: 9600 }) // ...later, revoke access to the serial port. await port.forget() } ``` #### Event: 'select-usb-device' Returns: * `event` Event * `details` Object * `deviceList` [USBDevice[]](structures/usb-device.md) * `frame` [WebFrameMain](web-frame-main.md) * `callback` Function * `deviceId` string (optional) Emitted when a USB device needs to be selected when a call to `navigator.usb.requestDevice` is made. `callback` should be called with `deviceId` to be selected; passing no arguments to `callback` will cancel the request. Additionally, permissioning on `navigator.usb` can be further managed by using [`ses.setPermissionCheckHandler(handler)`](#sessetpermissioncheckhandlerhandler) and [`ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler). ```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} @ts-type={updateGrantedDevices:(devices:Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)=>void} const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'usb') { // Add logic here to determine if permission should be given to allow USB selection return true } return false }) // Optionally, retrieve previously persisted devices from a persistent store (fetchGrantedDevices needs to be implemented by developer to fetch persisted permissions) const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'usb') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.usb.requestDevice` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } return false }) win.webContents.session.on('select-usb-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === 9025 && device.productId === 67 }) if (selectedDevice) { // Optionally, add this to the persisted devices (updateGrantedDevices needs to be implemented by developer to persist permissions) grantedDevices.push(selectedDevice) updateGrantedDevices(grantedDevices) } callback(selectedDevice?.deviceId) }) }) ``` #### Event: 'usb-device-added' Returns: * `event` Event * `device` [USBDevice](structures/usb-device.md) * `webContents` [WebContents](web-contents.md) Emitted after `navigator.usb.requestDevice` has been called and `select-usb-device` has fired if a new device becomes available before the callback from `select-usb-device` is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated with the newly added device. #### Event: 'usb-device-removed' Returns: * `event` Event * `device` [USBDevice](structures/usb-device.md) * `webContents` [WebContents](web-contents.md) Emitted after `navigator.usb.requestDevice` has been called and `select-usb-device` has fired if a device has been removed before the callback from `select-usb-device` is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated to remove the specified device. #### Event: 'usb-device-revoked' Returns: * `event` Event * `details` Object * `device` [USBDevice](structures/usb-device.md) * `origin` string (optional) - The origin that the device has been revoked from. Emitted after `USBDevice.forget()` has been called. This event can be used to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used. ### Instance Methods The following methods are available on instances of `Session`: #### `ses.getCacheSize()` Returns `Promise<Integer>` - the session's current cache size, in bytes. #### `ses.clearCache()` Returns `Promise<void>` - resolves when the cache clear operation is complete. Clears the session’s HTTP cache. #### `ses.clearStorageData([options])` * `options` Object (optional) * `origin` string (optional) - Should follow `window.location.origin`’s representation `scheme://host:port`. * `storages` string[] (optional) - The types of storages to clear, can be `cookies`, `filesystem`, `indexdb`, `localstorage`, `shadercache`, `websql`, `serviceworkers`, `cachestorage`. If not specified, clear all storage types. * `quotas` string[] (optional) - The types of quotas to clear, can be `temporary`, `syncable`. If not specified, clear all quotas. Returns `Promise<void>` - resolves when the storage data has been cleared. #### `ses.flushStorageData()` Writes any unwritten DOMStorage data to disk. #### `ses.setProxy(config)` * `config` Object * `mode` string (optional) - The proxy mode. Should be one of `direct`, `auto_detect`, `pac_script`, `fixed_servers` or `system`. If it's unspecified, it will be automatically determined based on other specified options. * `direct` In direct mode all connections are created directly, without any proxy involved. * `auto_detect` In auto_detect mode the proxy configuration is determined by a PAC script that can be downloaded at http://wpad/wpad.dat. * `pac_script` In pac_script mode the proxy configuration is determined by a PAC script that is retrieved from the URL specified in the `pacScript`. This is the default mode if `pacScript` is specified. * `fixed_servers` In fixed_servers mode the proxy configuration is specified in `proxyRules`. This is the default mode if `proxyRules` is specified. * `system` In system mode the proxy configuration is taken from the operating system. Note that the system mode is different from setting no proxy configuration. In the latter case, Electron falls back to the system settings only if no command-line options influence the proxy configuration. * `pacScript` string (optional) - The URL associated with the PAC file. * `proxyRules` string (optional) - Rules indicating which proxies to use. * `proxyBypassRules` string (optional) - Rules indicating which URLs should bypass the proxy settings. Returns `Promise<void>` - Resolves when the proxy setting process is complete. Sets the proxy settings. When `mode` is unspecified, `pacScript` and `proxyRules` are provided together, the `proxyRules` option is ignored and `pacScript` configuration is applied. You may need `ses.closeAllConnections` to close currently in flight connections to prevent pooled sockets using previous proxy from being reused by future requests. The `proxyRules` has to follow the rules below: ```sh proxyRules = schemeProxies[";"<schemeProxies>] schemeProxies = [<urlScheme>"="]<proxyURIList> urlScheme = "http" | "https" | "ftp" | "socks" proxyURIList = <proxyURL>[","<proxyURIList>] proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>] ``` For example: * `http=foopy:80;ftp=foopy2` - Use HTTP proxy `foopy:80` for `http://` URLs, and HTTP proxy `foopy2:80` for `ftp://` URLs. * `foopy:80` - Use HTTP proxy `foopy:80` for all URLs. * `foopy:80,bar,direct://` - Use HTTP proxy `foopy:80` for all URLs, failing over to `bar` if `foopy:80` is unavailable, and after that using no proxy. * `socks4://foopy` - Use SOCKS v4 proxy `foopy:1080` for all URLs. * `http=foopy,socks5://bar.com` - Use HTTP proxy `foopy` for http URLs, and fail over to the SOCKS5 proxy `bar.com` if `foopy` is unavailable. * `http=foopy,direct://` - Use HTTP proxy `foopy` for http URLs, and use no proxy if `foopy` is unavailable. * `http=foopy;socks=foopy2` - Use HTTP proxy `foopy` for http URLs, and use `socks4://foopy2` for all other URLs. The `proxyBypassRules` is a comma separated list of rules described below: * `[ URL_SCHEME "://" ] HOSTNAME_PATTERN [ ":" <port> ]` Match all hostnames that match the pattern HOSTNAME_PATTERN. Examples: "foobar.com", "\*foobar.com", "\*.foobar.com", "\*foobar.com:99", "https://x.\*.y.com:99" * `"." HOSTNAME_SUFFIX_PATTERN [ ":" PORT ]` Match a particular domain suffix. Examples: ".google.com", ".com", "http://.google.com" * `[ SCHEME "://" ] IP_LITERAL [ ":" PORT ]` Match URLs which are IP address literals. Examples: "127.0.1", "\[0:0::1]", "\[::1]", "http://\[::1]:99" * `IP_LITERAL "/" PREFIX_LENGTH_IN_BITS` Match any URL that is to an IP literal that falls between the given range. IP range is specified using CIDR notation. Examples: "192.168.1.1/16", "fefe:13::abc/33". * `<local>` Match local addresses. The meaning of `<local>` is whether the host matches one of: "127.0.0.1", "::1", "localhost". #### `ses.resolveHost(host, [options])` * `host` string - Hostname to resolve. * `options` Object (optional) * `queryType` string (optional) - Requested DNS query type. If unspecified, resolver will pick A or AAAA (or both) based on IPv4/IPv6 settings: * `A` - Fetch only A records * `AAAA` - Fetch only AAAA records. * `source` string (optional) - The source to use for resolved addresses. Default allows the resolver to pick an appropriate source. Only affects use of big external sources (e.g. calling the system for resolution or using DNS). Even if a source is specified, results can still come from cache, resolving "localhost" or IP literals, etc. One of the following values: * `any` (default) - Resolver will pick an appropriate source. Results could come from DNS, MulticastDNS, HOSTS file, etc * `system` - Results will only be retrieved from the system or OS, e.g. via the `getaddrinfo()` system call * `dns` - Results will only come from DNS queries * `mdns` - Results will only come from Multicast DNS queries * `localOnly` - No external sources will be used. Results will only come from fast local sources that are available no matter the source setting, e.g. cache, hosts file, IP literal resolution, etc. * `cacheUsage` string (optional) - Indicates what DNS cache entries, if any, can be used to provide a response. One of the following values: * `allowed` (default) - Results may come from the host cache if non-stale * `staleAllowed` - Results may come from the host cache even if stale (by expiration or network changes) * `disallowed` - Results will not come from the host cache. * `secureDnsPolicy` string (optional) - Controls the resolver's Secure DNS behavior for this request. One of the following values: * `allow` (default) * `disable` Returns [`Promise<ResolvedHost>`](structures/resolved-host.md) - Resolves with the resolved IP addresses for the `host`. #### `ses.resolveProxy(url)` * `url` URL Returns `Promise<string>` - Resolves with the proxy information for `url`. #### `ses.forceReloadProxyConfig()` Returns `Promise<void>` - Resolves when the all internal states of proxy service is reset and the latest proxy configuration is reapplied if it's already available. The pac script will be fetched from `pacScript` again if the proxy mode is `pac_script`. #### `ses.setDownloadPath(path)` * `path` string - The download location. Sets download saving directory. By default, the download directory will be the `Downloads` under the respective app folder. #### `ses.enableNetworkEmulation(options)` * `options` Object * `offline` boolean (optional) - Whether to emulate network outage. Defaults to false. * `latency` Double (optional) - RTT in ms. Defaults to 0 which will disable latency throttling. * `downloadThroughput` Double (optional) - Download rate in Bps. Defaults to 0 which will disable download throttling. * `uploadThroughput` Double (optional) - Upload rate in Bps. Defaults to 0 which will disable upload throttling. Emulates network with the given configuration for the `session`. ```javascript const win = new BrowserWindow() // To emulate a GPRS connection with 50kbps throughput and 500 ms latency. win.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }) // To emulate a network outage. win.webContents.session.enableNetworkEmulation({ offline: true }) ``` #### `ses.preconnect(options)` * `options` Object * `url` string - URL for preconnect. Only the origin is relevant for opening the socket. * `numSockets` number (optional) - number of sockets to preconnect. Must be between 1 and 6. Defaults to 1. Preconnects the given number of sockets to an origin. #### `ses.closeAllConnections()` Returns `Promise<void>` - Resolves when all connections are closed. **Note:** It will terminate / fail all requests currently in flight. #### `ses.fetch(input[, init])` * `input` string | [GlobalRequest](https://nodejs.org/api/globals.html#request) * `init` [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options) & { bypassCustomProtocolHandlers?: boolean } (optional) Returns `Promise<GlobalResponse>` - see [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response). Sends a request, similarly to how `fetch()` works in the renderer, using Chrome's network stack. This differs from Node's `fetch()`, which uses Node.js's HTTP stack. Example: ```js async function example () { const response = await net.fetch('https://my.app') if (response.ok) { const body = await response.json() // ... use the result. } } ``` See also [`net.fetch()`](net.md#netfetchinput-init), a convenience method which issues requests from the [default session](#sessiondefaultsession). See the MDN documentation for [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) for more details. Limitations: * `net.fetch()` does not support the `data:` or `blob:` schemes. * The value of the `integrity` option is ignored. * The `.type` and `.url` values of the returned `Response` object are incorrect. By default, requests made with `net.fetch` can be made to [custom protocols](protocol.md) as well as `file:`, and will trigger [webRequest](web-request.md) handlers if present. When the non-standard `bypassCustomProtocolHandlers` option is set in RequestInit, custom protocol handlers will not be called for this request. This allows forwarding an intercepted request to the built-in handler. [webRequest](web-request.md) handlers will still be triggered when bypassing custom protocols. ```js protocol.handle('https', (req) => { if (req.url === 'https://my-app.com') { return new Response('<body>my app</body>') } else { return net.fetch(req, { bypassCustomProtocolHandlers: true }) } }) ``` #### `ses.disableNetworkEmulation()` Disables any network emulation already active for the `session`. Resets to the original network configuration. #### `ses.setCertificateVerifyProc(proc)` * `proc` Function | null * `request` Object * `hostname` string * `certificate` [Certificate](structures/certificate.md) * `validatedCertificate` [Certificate](structures/certificate.md) * `isIssuedByKnownRoot` boolean - `true` if Chromium recognises the root CA as a standard root. If it isn't then it's probably the case that this certificate was generated by a MITM proxy whose root has been installed locally (for example, by a corporate proxy). This should not be trusted if the `verificationResult` is not `OK`. * `verificationResult` string - `OK` if the certificate is trusted, otherwise an error like `CERT_REVOKED`. * `errorCode` Integer - Error code. * `callback` Function * `verificationResult` Integer - Value can be one of certificate error codes from [here](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). Apart from the certificate error codes, the following special codes can be used. * `0` - Indicates success and disables Certificate Transparency verification. * `-2` - Indicates failure. * `-3` - Uses the verification result from chromium. Sets the certificate verify proc for `session`, the `proc` will be called with `proc(request, callback)` whenever a server certificate verification is requested. Calling `callback(0)` accepts the certificate, calling `callback(-2)` rejects it. Calling `setCertificateVerifyProc(null)` will revert back to default certificate verify proc. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.webContents.session.setCertificateVerifyProc((request, callback) => { const { hostname } = request if (hostname === 'github.com') { callback(0) } else { callback(-2) } }) ``` > **NOTE:** The result of this procedure is cached by the network service. #### `ses.setPermissionRequestHandler(handler)` * `handler` Function | null * `webContents` [WebContents](web-contents.md) - WebContents requesting the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. * `permission` string - The type of requested permission. * `clipboard-read` - Request access to read from the clipboard. * `clipboard-sanitized-write` - Request access to write to the clipboard. * `display-capture` - Request access to capture the screen via the [Screen Capture API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API). * `fullscreen` - Request control of the app's fullscreen state via the [Fullscreen API](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API). * `geolocation` - Request access to the user's location via the [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) * `idle-detection` - Request access to the user's idle state via the [IdleDetector API](https://developer.mozilla.org/en-US/docs/Web/API/IdleDetector). * `media` - Request access to media devices such as camera, microphone and speakers. * `mediaKeySystem` - Request access to DRM protected content. * `midi` - Request MIDI access in the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). * `midiSysex` - Request the use of system exclusive messages in the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). * `notifications` - Request notification creation and the ability to display them in the user's system tray using the [Notifications API](https://developer.mozilla.org/en-US/docs/Web/API/notification) * `pointerLock` - Request to directly interpret mouse movements as an input method via the [Pointer Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API). These requests always appear to originate from the main frame. * `keyboardLock` - Request capture of keypresses for any or all of the keys on the physical keyboard via the [Keyboard Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/lock). These requests always appear to originate from the main frame. * `openExternal` - Request to open links in external applications. * `window-management` - Request access to enumerate screens using the [`getScreenDetails`](https://developer.chrome.com/en/articles/multi-screen-window-placement/) API. * `unknown` - An unrecognized permission request. * `callback` Function * `permissionGranted` boolean - Allow or deny the permission. * `details` Object - Some properties are only available on certain permission types. * `externalURL` string (optional) - The url of the `openExternal` request. * `securityOrigin` string (optional) - The security origin of the `media` request. * `mediaTypes` string[] (optional) - The types of media access being requested, elements can be `video` or `audio` * `requestingUrl` string - The last URL the requesting frame loaded * `isMainFrame` boolean - Whether the frame making the request is the main frame Sets the handler which can be used to respond to permission requests for the `session`. Calling `callback(true)` will allow the permission and `callback(false)` will reject it. To clear the handler, call `setPermissionRequestHandler(null)`. Please note that you must also implement `setPermissionCheckHandler` to get complete permission handling. Most web APIs do a permission check and then make a permission request if the check is denied. ```javascript const { session } = require('electron') session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => { if (webContents.getURL() === 'some-host' && permission === 'notifications') { return callback(false) // denied. } callback(true) }) ``` #### `ses.setPermissionCheckHandler(handler)` * `handler` Function\<boolean> | null * `webContents` ([WebContents](web-contents.md) | null) - WebContents checking the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. All cross origin sub frames making permission checks will pass a `null` webContents to this handler, while certain other permission checks such as `notifications` checks will always pass `null`. You should use `embeddingOrigin` and `requestingOrigin` to determine what origin the owning frame and the requesting frame are on respectively. * `permission` string - Type of permission check. * `clipboard-read` - Request access to read from the clipboard. * `clipboard-sanitized-write` - Request access to write to the clipboard. * `geolocation` - Access the user's geolocation data via the [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) * `fullscreen` - Control of the app's fullscreen state via the [Fullscreen API](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API). * `hid` - Access the HID protocol to manipulate HID devices via the [WebHID API](https://developer.mozilla.org/en-US/docs/Web/API/WebHID_API). * `idle-detection` - Access the user's idle state via the [IdleDetector API](https://developer.mozilla.org/en-US/docs/Web/API/IdleDetector). * `media` - Access to media devices such as camera, microphone and speakers. * `mediaKeySystem` - Access to DRM protected content. * `midi` - Enable MIDI access in the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). * `midiSysex` - Use system exclusive messages in the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). * `notifications` - Configure and display desktop notifications to the user with the [Notifications API](https://developer.mozilla.org/en-US/docs/Web/API/notification). * `openExternal` - Open links in external applications. * `pointerLock` - Directly interpret mouse movements as an input method via the [Pointer Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API). These requests always appear to originate from the main frame. * `serial` - Read from and write to serial devices with the [Web Serial API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Serial_API). * `usb` - Expose non-standard Universal Serial Bus (USB) compatible devices services to the web with the [WebUSB API](https://developer.mozilla.org/en-US/docs/Web/API/WebUSB_API). * `requestingOrigin` string - The origin URL of the permission check * `details` Object - Some properties are only available on certain permission types. * `embeddingOrigin` string (optional) - The origin of the frame embedding the frame that made the permission check. Only set for cross-origin sub frames making permission checks. * `securityOrigin` string (optional) - The security origin of the `media` check. * `mediaType` string (optional) - The type of media access being requested, can be `video`, `audio` or `unknown` * `requestingUrl` string (optional) - The last URL the requesting frame loaded. This is not provided for cross-origin sub frames making permission checks. * `isMainFrame` boolean - Whether the frame making the request is the main frame Sets the handler which can be used to respond to permission checks for the `session`. Returning `true` will allow the permission and `false` will reject it. Please note that you must also implement `setPermissionRequestHandler` to get complete permission handling. Most web APIs do a permission check and then make a permission request if the check is denied. To clear the handler, call `setPermissionCheckHandler(null)`. ```javascript const { session } = require('electron') const url = require('url') session.fromPartition('some-partition').setPermissionCheckHandler((webContents, permission, requestingOrigin) => { if (new URL(requestingOrigin).hostname === 'some-host' && permission === 'notifications') { return true // granted } return false // denied }) ``` #### `ses.setDisplayMediaRequestHandler(handler)` * `handler` Function | null * `request` Object * `frame` [WebFrameMain](web-frame-main.md) - Frame that is requesting access to media. * `securityOrigin` String - Origin of the page making the request. * `videoRequested` Boolean - true if the web content requested a video stream. * `audioRequested` Boolean - true if the web content requested an audio stream. * `userGesture` Boolean - Whether a user gesture was active when this request was triggered. * `callback` Function * `streams` Object * `video` Object | [WebFrameMain](web-frame-main.md) (optional) * `id` String - The id of the stream being granted. This will usually come from a [DesktopCapturerSource](structures/desktop-capturer-source.md) object. * `name` String - The name of the stream being granted. This will usually come from a [DesktopCapturerSource](structures/desktop-capturer-source.md) object. * `audio` String | [WebFrameMain](web-frame-main.md) (optional) - If a string is specified, can be `loopback` or `loopbackWithMute`. Specifying a loopback device will capture system audio, and is currently only supported on Windows. If a WebFrameMain is specified, will capture audio from that frame. * `enableLocalEcho` Boolean (optional) - If `audio` is a [WebFrameMain](web-frame-main.md) and this is set to `true`, then local playback of audio will not be muted (e.g. using `MediaRecorder` to record `WebFrameMain` with this flag set to `true` will allow audio to pass through to the speakers while recording). Default is `false`. This handler will be called when web content requests access to display media via the `navigator.mediaDevices.getDisplayMedia` API. Use the [desktopCapturer](desktop-capturer.md) API to choose which stream(s) to grant access to. ```javascript const { session, desktopCapturer } = require('electron') session.defaultSession.setDisplayMediaRequestHandler((request, callback) => { desktopCapturer.getSources({ types: ['screen'] }).then((sources) => { // Grant access to the first screen found. callback({ video: sources[0] }) }) }) ``` Passing a [WebFrameMain](web-frame-main.md) object as a video or audio stream will capture the video or audio stream from that frame. ```javascript const { session } = require('electron') session.defaultSession.setDisplayMediaRequestHandler((request, callback) => { // Allow the tab to capture itself. callback({ video: request.frame }) }) ``` Passing `null` instead of a function resets the handler to its default state. #### `ses.setDevicePermissionHandler(handler)` * `handler` Function\<boolean> | null * `details` Object * `deviceType` string - The type of device that permission is being requested on, can be `hid`, `serial`, or `usb`. * `origin` string - The origin URL of the device permission check. * `device` [HIDDevice](structures/hid-device.md) | [SerialPort](structures/serial-port.md) | [USBDevice](structures/usb-device.md) - the device that permission is being requested for. Sets the handler which can be used to respond to device permission checks for the `session`. Returning `true` will allow the device to be permitted and `false` will reject it. To clear the handler, call `setDevicePermissionHandler(null)`. This handler can be used to provide default permissioning to devices without first calling for permission to devices (eg via `navigator.hid.requestDevice`). If this handler is not defined, the default device permissions as granted through device selection (eg via `navigator.hid.requestDevice`) will be used. Additionally, the default behavior of Electron is to store granted device permission in memory. If longer term storage is needed, a developer can store granted device permissions (eg when handling the `select-hid-device` event) and then read from that storage with `setDevicePermissionHandler`. ```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'hid') { // Add logic here to determine if permission should be given to allow HID selection return true } else if (permission === 'serial') { // Add logic here to determine if permission should be given to allow serial port selection } else if (permission === 'usb') { // Add logic here to determine if permission should be given to allow USB device selection } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } else if (details.deviceType === 'serial') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } } return false }) win.webContents.session.on('select-hid-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === 9025 && device.productId === 67 }) callback(selectedDevice?.deviceId) }) }) ``` #### `ses.setUSBProtectedClassesHandler(handler)` * `handler` Function\<string[]> | null * `details` Object * `protectedClasses` string[] - The current list of protected USB classes. Possible class values include: * `audio` * `audio-video` * `hid` * `mass-storage` * `smart-card` * `video` * `wireless` Sets the handler which can be used to override which [USB classes are protected](https://wicg.github.io/webusb/#usbinterface-interface). The return value for the handler is a string array of USB classes which should be considered protected (eg not available in the renderer). Valid values for the array are: * `audio` * `audio-video` * `hid` * `mass-storage` * `smart-card` * `video` * `wireless` Returning an empty string array from the handler will allow all USB classes; returning the passed in array will maintain the default list of protected USB classes (this is also the default behavior if a handler is not defined). To clear the handler, call `setUSBProtectedClassesHandler(null)`. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setUSBProtectedClassesHandler((details) => { // Allow all classes: // return [] // Keep the current set of protected classes: // return details.protectedClasses // Selectively remove classes: return details.protectedClasses.filter((usbClass) => { // Exclude classes except for audio classes return usbClass.indexOf('audio') === -1 }) }) }) ``` #### `ses.setBluetoothPairingHandler(handler)` _Windows_ _Linux_ * `handler` Function | null * `details` Object * `deviceId` string * `pairingKind` string - The type of pairing prompt being requested. One of the following values: * `confirm` This prompt is requesting confirmation that the Bluetooth device should be paired. * `confirmPin` This prompt is requesting confirmation that the provided PIN matches the pin displayed on the device. * `providePin` This prompt is requesting that a pin be provided for the device. * `frame` [WebFrameMain](web-frame-main.md) * `pin` string (optional) - The pin value to verify if `pairingKind` is `confirmPin`. * `callback` Function * `response` Object * `confirmed` boolean - `false` should be passed in if the dialog is canceled. If the `pairingKind` is `confirm` or `confirmPin`, this value should indicate if the pairing is confirmed. If the `pairingKind` is `providePin` the value should be `true` when a value is provided. * `pin` string | null (optional) - When the `pairingKind` is `providePin` this value should be the required pin for the Bluetooth device. Sets a handler to respond to Bluetooth pairing requests. This handler allows developers to handle devices that require additional validation before pairing. When a handler is not defined, any pairing on Linux or Windows that requires additional validation will be automatically cancelled. macOS does not require a handler because macOS handles the pairing automatically. To clear the handler, call `setBluetoothPairingHandler(null)`. ```javascript const { app, BrowserWindow, session } = require('electron') const path = require('node:path') function createWindow () { let bluetoothPinCallback = null const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js') } }) mainWindow.webContents.session.setBluetoothPairingHandler((details, callback) => { bluetoothPinCallback = callback // Send a IPC message to the renderer to prompt the user to confirm the pairing. // Note that this will require logic in the renderer to handle this message and // display a prompt to the user. mainWindow.webContents.send('bluetooth-pairing-request', details) }) // Listen for an IPC message from the renderer to get the response for the Bluetooth pairing. mainWindow.webContents.ipc.on('bluetooth-pairing-response', (event, response) => { bluetoothPinCallback(response) }) } app.whenReady().then(() => { createWindow() }) ``` #### `ses.clearHostResolverCache()` Returns `Promise<void>` - Resolves when the operation is complete. Clears the host resolver cache. #### `ses.allowNTLMCredentialsForDomains(domains)` * `domains` string - A comma-separated list of servers for which integrated authentication is enabled. Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate authentication. ```javascript const { session } = require('electron') // consider any url ending with `example.com`, `foobar.com`, `baz` // for integrated authentication. session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz') // consider all urls for integrated authentication. session.defaultSession.allowNTLMCredentialsForDomains('*') ``` #### `ses.setUserAgent(userAgent[, acceptLanguages])` * `userAgent` string * `acceptLanguages` string (optional) Overrides the `userAgent` and `acceptLanguages` for this session. The `acceptLanguages` must a comma separated ordered list of language codes, for example `"en-US,fr,de,ko,zh-CN,ja"`. This doesn't affect existing `WebContents`, and each `WebContents` can use `webContents.setUserAgent` to override the session-wide user agent. #### `ses.isPersistent()` Returns `boolean` - Whether or not this session is a persistent one. The default `webContents` session of a `BrowserWindow` is persistent. When creating a session from a partition, session prefixed with `persist:` will be persistent, while others will be temporary. #### `ses.getUserAgent()` Returns `string` - The user agent for this session. #### `ses.setSSLConfig(config)` * `config` Object * `minVersion` string (optional) - Can be `tls1`, `tls1.1`, `tls1.2` or `tls1.3`. The minimum SSL version to allow when connecting to remote servers. Defaults to `tls1`. * `maxVersion` string (optional) - Can be `tls1.2` or `tls1.3`. The maximum SSL version to allow when connecting to remote servers. Defaults to `tls1.3`. * `disabledCipherSuites` Integer[] (optional) - List of cipher suites which should be explicitly prevented from being used in addition to those disabled by the net built-in policy. Supported literal forms: 0xAABB, where AA is `cipher_suite[0]` and BB is `cipher_suite[1]`, as defined in RFC 2246, Section 7.4.1.2. Unrecognized but parsable cipher suites in this form will not return an error. Ex: To disable TLS_RSA_WITH_RC4_128_MD5, specify 0x0004, while to disable TLS_ECDH_ECDSA_WITH_RC4_128_SHA, specify 0xC002. Note that TLSv1.3 ciphers cannot be disabled using this mechanism. Sets the SSL configuration for the session. All subsequent network requests will use the new configuration. Existing network connections (such as WebSocket connections) will not be terminated, but old sockets in the pool will not be reused for new connections. #### `ses.getBlobData(identifier)` * `identifier` string - Valid UUID. Returns `Promise<Buffer>` - resolves with blob data. #### `ses.downloadURL(url[, options])` * `url` string * `options` Object (optional) * `headers` Record<string, string> (optional) - HTTP request headers. Initiates a download of the resource at `url`. The API will generate a [DownloadItem](download-item.md) that can be accessed with the [will-download](#event-will-download) event. **Note:** This does not perform any security checks that relate to a page's origin, unlike [`webContents.downloadURL`](web-contents.md#contentsdownloadurlurl-options). #### `ses.createInterruptedDownload(options)` * `options` Object * `path` string - Absolute path of the download. * `urlChain` string[] - Complete URL chain for the download. * `mimeType` string (optional) * `offset` Integer - Start range for the download. * `length` Integer - Total length of the download. * `lastModified` string (optional) - Last-Modified header value. * `eTag` string (optional) - ETag header value. * `startTime` Double (optional) - Time when download was started in number of seconds since UNIX epoch. Allows resuming `cancelled` or `interrupted` downloads from previous `Session`. The API will generate a [DownloadItem](download-item.md) that can be accessed with the [will-download](#event-will-download) event. The [DownloadItem](download-item.md) will not have any `WebContents` associated with it and the initial state will be `interrupted`. The download will start only when the `resume` API is called on the [DownloadItem](download-item.md). #### `ses.clearAuthCache()` Returns `Promise<void>` - resolves when the session’s HTTP authentication cache has been cleared. #### `ses.setPreloads(preloads)` * `preloads` string[] - An array of absolute path to preload scripts Adds scripts that will be executed on ALL web contents that are associated with this session just before normal `preload` scripts run. #### `ses.getPreloads()` Returns `string[]` an array of paths to preload scripts that have been registered. #### `ses.setCodeCachePath(path)` * `path` String - Absolute path to store the v8 generated JS code cache from the renderer. Sets the directory to store the generated JS [code cache](https://v8.dev/blog/code-caching-for-devs) for this session. The directory is not required to be created by the user before this call, the runtime will create if it does not exist otherwise will use the existing directory. If directory cannot be created, then code cache will not be used and all operations related to code cache will fail silently inside the runtime. By default, the directory will be `Code Cache` under the respective user data folder. #### `ses.clearCodeCaches(options)` * `options` Object * `urls` String[] (optional) - An array of url corresponding to the resource whose generated code cache needs to be removed. If the list is empty then all entries in the cache directory will be removed. Returns `Promise<void>` - resolves when the code cache clear operation is complete. #### `ses.setSpellCheckerEnabled(enable)` * `enable` boolean Sets whether to enable the builtin spell checker. #### `ses.isSpellCheckerEnabled()` Returns `boolean` - Whether the builtin spell checker is enabled. #### `ses.setSpellCheckerLanguages(languages)` * `languages` string[] - An array of language codes to enable the spellchecker for. The built in spellchecker does not automatically detect what language a user is typing in. In order for the spell checker to correctly check their words you must call this API with an array of language codes. You can get the list of supported language codes with the `ses.availableSpellCheckerLanguages` property. **Note:** On macOS the OS spellchecker is used and will detect your language automatically. This API is a no-op on macOS. #### `ses.getSpellCheckerLanguages()` Returns `string[]` - An array of language codes the spellchecker is enabled for. If this list is empty the spellchecker will fallback to using `en-US`. By default on launch if this setting is an empty list Electron will try to populate this setting with the current OS locale. This setting is persisted across restarts. **Note:** On macOS the OS spellchecker is used and has its own list of languages. On macOS, this API will return whichever languages have been configured by the OS. #### `ses.setSpellCheckerDictionaryDownloadURL(url)` * `url` string - A base URL for Electron to download hunspell dictionaries from. By default Electron will download hunspell dictionaries from the Chromium CDN. If you want to override this behavior you can use this API to point the dictionary downloader at your own hosted version of the hunspell dictionaries. We publish a `hunspell_dictionaries.zip` file with each release which contains the files you need to host here. The file server must be **case insensitive**. If you cannot do this, you must upload each file twice: once with the case it has in the ZIP file and once with the filename as all lowercase. If the files present in `hunspell_dictionaries.zip` are available at `https://example.com/dictionaries/language-code.bdic` then you should call this api with `ses.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/')`. Please note the trailing slash. The URL to the dictionaries is formed as `${url}${filename}`. **Note:** On macOS the OS spellchecker is used and therefore we do not download any dictionary files. This API is a no-op on macOS. #### `ses.listWordsInSpellCheckerDictionary()` Returns `Promise<string[]>` - An array of all words in app's custom dictionary. Resolves when the full dictionary is loaded from disk. #### `ses.addWordToSpellCheckerDictionary(word)` * `word` string - The word you want to add to the dictionary Returns `boolean` - Whether the word was successfully written to the custom dictionary. This API will not work on non-persistent (in-memory) sessions. **Note:** On macOS and Windows 10 this word will be written to the OS custom dictionary as well #### `ses.removeWordFromSpellCheckerDictionary(word)` * `word` string - The word you want to remove from the dictionary Returns `boolean` - Whether the word was successfully removed from the custom dictionary. This API will not work on non-persistent (in-memory) sessions. **Note:** On macOS and Windows 10 this word will be removed from the OS custom dictionary as well #### `ses.loadExtension(path[, options])` * `path` string - Path to a directory containing an unpacked Chrome extension * `options` Object (optional) * `allowFileAccess` boolean - Whether to allow the extension to read local files over `file://` protocol and inject content scripts into `file://` pages. This is required e.g. for loading devtools extensions on `file://` URLs. Defaults to false. Returns `Promise<Extension>` - resolves when the extension is loaded. This method will raise an exception if the extension could not be loaded. If there are warnings when installing the extension (e.g. if the extension requests an API that Electron does not support) then they will be logged to the console. Note that Electron does not support the full range of Chrome extensions APIs. See [Supported Extensions APIs](extensions.md#supported-extensions-apis) for more details on what is supported. Note that in previous versions of Electron, extensions that were loaded would be remembered for future runs of the application. This is no longer the case: `loadExtension` must be called on every boot of your app if you want the extension to be loaded. ```js const { app, session } = require('electron') const path = require('node:path') app.whenReady().then(async () => { await session.defaultSession.loadExtension( path.join(__dirname, 'react-devtools'), // allowFileAccess is required to load the devtools extension on file:// URLs. { allowFileAccess: true } ) // Note that in order to use the React DevTools extension, you'll need to // download and unzip a copy of the extension. }) ``` This API does not support loading packed (.crx) extensions. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. **Note:** Loading extensions into in-memory (non-persistent) sessions is not supported and will throw an error. #### `ses.removeExtension(extensionId)` * `extensionId` string - ID of extension to remove Unloads an extension. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getExtension(extensionId)` * `extensionId` string - ID of extension to query Returns `Extension | null` - The loaded extension with the given ID. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getAllExtensions()` Returns `Extension[]` - A list of all loaded extensions. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getStoragePath()` Returns `string | null` - The absolute file system path where data for this session is persisted on disk. For in memory sessions this returns `null`. ### Instance Properties The following properties are available on instances of `Session`: #### `ses.availableSpellCheckerLanguages` _Readonly_ A `string[]` array which consists of all the known available spell checker languages. Providing a language code to the `setSpellCheckerLanguages` API that isn't in this array will result in an error. #### `ses.spellCheckerEnabled` A `boolean` indicating whether builtin spell checker is enabled. #### `ses.storagePath` _Readonly_ A `string | null` indicating the absolute file system path where data for this session is persisted on disk. For in memory sessions this returns `null`. #### `ses.cookies` _Readonly_ A [`Cookies`](cookies.md) object for this session. #### `ses.serviceWorkers` _Readonly_ A [`ServiceWorkers`](service-workers.md) object for this session. #### `ses.webRequest` _Readonly_ A [`WebRequest`](web-request.md) object for this session. #### `ses.protocol` _Readonly_ A [`Protocol`](protocol.md) object for this session. ```javascript const { app, session } = require('electron') const path = require('node:path') app.whenReady().then(() => { const protocol = session.fromPartition('some-partition').protocol if (!protocol.registerFileProtocol('atom', (request, callback) => { const url = request.url.substr(7) callback({ path: path.normalize(path.join(__dirname, url)) }) })) { console.error('Failed to register protocol') } }) ``` #### `ses.netLog` _Readonly_ A [`NetLog`](net-log.md) object for this session. ```javascript const { app, session } = require('electron') app.whenReady().then(async () => { const netLog = session.fromPartition('some-partition').netLog netLog.startLogging('/path/to/net-log') // After some network events const path = await netLog.stopLogging() console.log('Net-logs written to', path) }) ```
closed
electron/electron
https://github.com/electron/electron
40,457
[Bug]: Wrong types for HidDeviceRemovedDetails and HidDeviceAddedDetails
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.3 ### What operating system are you using? macOS ### Operating System Version 14.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior ```typescript interface HidDeviceAddedDetails { device: HIDDevice; frame: WebFrameMain; } interface HidDeviceRemovedDetails { device: HIDDevice; frame: WebFrameMain; } ``` ### Actual Behavior ```typescript interface HidDeviceAddedDetails { device: HIDDevice[]; frame: WebFrameMain; } interface HidDeviceRemovedDetails { device: HIDDevice[]; frame: WebFrameMain; } ``` ### Testcase Gist URL _No response_ ### Additional Information Currently provided typings for electron assume that device will be an array of HIDDevice while the actual binary provides with only instance.
https://github.com/electron/electron/issues/40457
https://github.com/electron/electron/pull/40462
e8d9294d9d51ca0e2eaae22d4f57561e79a08833
1ba535296efe87ecf0362759d2fab29b2af8b755
2023-11-06T14:18:02Z
c++
2023-11-07T22:26:35Z
docs/api/session.md
# session > Manage browser sessions, cookies, cache, proxy settings, etc. Process: [Main](../glossary.md#main-process) The `session` module can be used to create new `Session` objects. You can also access the `session` of existing pages by using the `session` property of [`WebContents`](web-contents.md), or from the `session` module. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('https://github.com') const ses = win.webContents.session console.log(ses.getUserAgent()) ``` ## Methods The `session` module has the following methods: ### `session.fromPartition(partition[, options])` * `partition` string * `options` Object (optional) * `cache` boolean - Whether to enable cache. Returns `Session` - A session instance from `partition` string. When there is an existing `Session` with the same `partition`, it will be returned; otherwise a new `Session` instance will be created with `options`. 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. If the `partition` is empty then default session of the app will be returned. To create a `Session` with `options`, you have to ensure the `Session` with the `partition` has never been used before. There is no way to change the `options` of an existing `Session` object. ### `session.fromPath(path[, options])` * `path` string * `options` Object (optional) * `cache` boolean - Whether to enable cache. Returns `Session` - A session instance from the absolute path as specified by the `path` string. When there is an existing `Session` with the same absolute path, it will be returned; otherwise a new `Session` instance will be created with `options`. The call will throw an error if the path is not an absolute path. Additionally, an error will be thrown if an empty string is provided. To create a `Session` with `options`, you have to ensure the `Session` with the `path` has never been used before. There is no way to change the `options` of an existing `Session` object. ## Properties The `session` module has the following properties: ### `session.defaultSession` A `Session` object, the default session object of the app. ## Class: Session > Get and set properties of a session. Process: [Main](../glossary.md#main-process)<br /> _This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ You can create a `Session` object in the `session` module: ```javascript const { session } = require('electron') const ses = session.fromPartition('persist:name') console.log(ses.getUserAgent()) ``` ### Instance Events The following events are available on instances of `Session`: #### Event: 'will-download' Returns: * `event` Event * `item` [DownloadItem](download-item.md) * `webContents` [WebContents](web-contents.md) Emitted when Electron is about to download `item` in `webContents`. Calling `event.preventDefault()` will cancel the download and `item` will not be available from next tick of the process. ```javascript @ts-expect-error=[4] const { session } = require('electron') session.defaultSession.on('will-download', (event, item, webContents) => { event.preventDefault() require('got')(item.getURL()).then((response) => { require('node:fs').writeFileSync('/somewhere', response.body) }) }) ``` #### Event: 'extension-loaded' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is loaded. This occurs whenever an extension is added to the "enabled" set of extensions. This includes: * Extensions being loaded from `Session.loadExtension`. * Extensions being reloaded: * from a crash. * if the extension requested it ([`chrome.runtime.reload()`](https://developer.chrome.com/extensions/runtime#method-reload)). #### Event: 'extension-unloaded' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is unloaded. This occurs when `Session.removeExtension` is called. #### Event: 'extension-ready' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is loaded and all necessary browser state is initialized to support the start of the extension's background page. #### Event: 'preconnect' Returns: * `event` Event * `preconnectUrl` string - The URL being requested for preconnection by the renderer. * `allowCredentials` boolean - True if the renderer is requesting that the connection include credentials (see the [spec](https://w3c.github.io/resource-hints/#preconnect) for more details.) Emitted when a render process requests preconnection to a URL, generally due to a [resource hint](https://w3c.github.io/resource-hints/). #### Event: 'spellcheck-dictionary-initialized' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file has been successfully initialized. This occurs after the file has been downloaded. #### Event: 'spellcheck-dictionary-download-begin' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file starts downloading #### Event: 'spellcheck-dictionary-download-success' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file has been successfully downloaded #### Event: 'spellcheck-dictionary-download-failure' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file download fails. For details on the failure you should collect a netlog and inspect the download request. #### Event: 'select-hid-device' Returns: * `event` Event * `details` Object * `deviceList` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) * `callback` Function * `deviceId` string | null (optional) Emitted when a HID device needs to be selected when a call to `navigator.hid.requestDevice` is made. `callback` should be called with `deviceId` to be selected; passing no arguments to `callback` will cancel the request. Additionally, permissioning on `navigator.hid` can be further managed by using [`ses.setPermissionCheckHandler(handler)`](#sessetpermissioncheckhandlerhandler) and [`ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler). ```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'hid') { // Add logic here to determine if permission should be given to allow HID selection return true } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } return false }) win.webContents.session.on('select-hid-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === 9025 && device.productId === 67 }) callback(selectedDevice?.deviceId) }) }) ``` #### Event: 'hid-device-added' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) Emitted after `navigator.hid.requestDevice` has been called and `select-hid-device` has fired if a new device becomes available before the callback from `select-hid-device` is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated with the newly added device. #### Event: 'hid-device-removed' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) Emitted after `navigator.hid.requestDevice` has been called and `select-hid-device` has fired if a device has been removed before the callback from `select-hid-device` is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated to remove the specified device. #### Event: 'hid-device-revoked' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `origin` string (optional) - The origin that the device has been revoked from. Emitted after `HIDDevice.forget()` has been called. This event can be used to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used. #### Event: 'select-serial-port' Returns: * `event` Event * `portList` [SerialPort[]](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) * `callback` Function * `portId` string Emitted when a serial port needs to be selected when a call to `navigator.serial.requestPort` is made. `callback` should be called with `portId` to be selected, passing an empty string to `callback` will cancel the request. Additionally, permissioning on `navigator.serial` can be managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler) with the `serial` permission. ```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'serial') { // Add logic here to determine if permission should be given to allow serial selection return true } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'serial') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.serial.requestPort` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } return false }) win.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { event.preventDefault() const selectedPort = portList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) if (!selectedPort) { callback('') } else { callback(selectedPort.portId) } }) }) ``` #### Event: 'serial-port-added' Returns: * `event` Event * `port` [SerialPort](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) Emitted after `navigator.serial.requestPort` has been called and `select-serial-port` has fired if a new serial port becomes available before the callback from `select-serial-port` is called. This event is intended for use when using a UI to ask users to pick a port so that the UI can be updated with the newly added port. #### Event: 'serial-port-removed' Returns: * `event` Event * `port` [SerialPort](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) Emitted after `navigator.serial.requestPort` has been called and `select-serial-port` has fired if a serial port has been removed before the callback from `select-serial-port` is called. This event is intended for use when using a UI to ask users to pick a port so that the UI can be updated to remove the specified port. #### Event: 'serial-port-revoked' Returns: * `event` Event * `details` Object * `port` [SerialPort](structures/serial-port.md) * `frame` [WebFrameMain](web-frame-main.md) * `origin` string - The origin that the device has been revoked from. Emitted after `SerialPort.forget()` has been called. This event can be used to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used. ```js // Browser Process const { app, BrowserWindow } = require('electron') app.whenReady().then(() => { const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.session.on('serial-port-revoked', (event, details) => { console.log(`Access revoked for serial device from origin ${details.origin}`) }) }) ``` ```js // Renderer Process const portConnect = async () => { // Request a port. const port = await navigator.serial.requestPort() // Wait for the serial port to open. await port.open({ baudRate: 9600 }) // ...later, revoke access to the serial port. await port.forget() } ``` #### Event: 'select-usb-device' Returns: * `event` Event * `details` Object * `deviceList` [USBDevice[]](structures/usb-device.md) * `frame` [WebFrameMain](web-frame-main.md) * `callback` Function * `deviceId` string (optional) Emitted when a USB device needs to be selected when a call to `navigator.usb.requestDevice` is made. `callback` should be called with `deviceId` to be selected; passing no arguments to `callback` will cancel the request. Additionally, permissioning on `navigator.usb` can be further managed by using [`ses.setPermissionCheckHandler(handler)`](#sessetpermissioncheckhandlerhandler) and [`ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler). ```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} @ts-type={updateGrantedDevices:(devices:Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)=>void} const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'usb') { // Add logic here to determine if permission should be given to allow USB selection return true } return false }) // Optionally, retrieve previously persisted devices from a persistent store (fetchGrantedDevices needs to be implemented by developer to fetch persisted permissions) const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'usb') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.usb.requestDevice` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } return false }) win.webContents.session.on('select-usb-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === 9025 && device.productId === 67 }) if (selectedDevice) { // Optionally, add this to the persisted devices (updateGrantedDevices needs to be implemented by developer to persist permissions) grantedDevices.push(selectedDevice) updateGrantedDevices(grantedDevices) } callback(selectedDevice?.deviceId) }) }) ``` #### Event: 'usb-device-added' Returns: * `event` Event * `device` [USBDevice](structures/usb-device.md) * `webContents` [WebContents](web-contents.md) Emitted after `navigator.usb.requestDevice` has been called and `select-usb-device` has fired if a new device becomes available before the callback from `select-usb-device` is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated with the newly added device. #### Event: 'usb-device-removed' Returns: * `event` Event * `device` [USBDevice](structures/usb-device.md) * `webContents` [WebContents](web-contents.md) Emitted after `navigator.usb.requestDevice` has been called and `select-usb-device` has fired if a device has been removed before the callback from `select-usb-device` is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated to remove the specified device. #### Event: 'usb-device-revoked' Returns: * `event` Event * `details` Object * `device` [USBDevice](structures/usb-device.md) * `origin` string (optional) - The origin that the device has been revoked from. Emitted after `USBDevice.forget()` has been called. This event can be used to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used. ### Instance Methods The following methods are available on instances of `Session`: #### `ses.getCacheSize()` Returns `Promise<Integer>` - the session's current cache size, in bytes. #### `ses.clearCache()` Returns `Promise<void>` - resolves when the cache clear operation is complete. Clears the session’s HTTP cache. #### `ses.clearStorageData([options])` * `options` Object (optional) * `origin` string (optional) - Should follow `window.location.origin`’s representation `scheme://host:port`. * `storages` string[] (optional) - The types of storages to clear, can be `cookies`, `filesystem`, `indexdb`, `localstorage`, `shadercache`, `websql`, `serviceworkers`, `cachestorage`. If not specified, clear all storage types. * `quotas` string[] (optional) - The types of quotas to clear, can be `temporary`, `syncable`. If not specified, clear all quotas. Returns `Promise<void>` - resolves when the storage data has been cleared. #### `ses.flushStorageData()` Writes any unwritten DOMStorage data to disk. #### `ses.setProxy(config)` * `config` Object * `mode` string (optional) - The proxy mode. Should be one of `direct`, `auto_detect`, `pac_script`, `fixed_servers` or `system`. If it's unspecified, it will be automatically determined based on other specified options. * `direct` In direct mode all connections are created directly, without any proxy involved. * `auto_detect` In auto_detect mode the proxy configuration is determined by a PAC script that can be downloaded at http://wpad/wpad.dat. * `pac_script` In pac_script mode the proxy configuration is determined by a PAC script that is retrieved from the URL specified in the `pacScript`. This is the default mode if `pacScript` is specified. * `fixed_servers` In fixed_servers mode the proxy configuration is specified in `proxyRules`. This is the default mode if `proxyRules` is specified. * `system` In system mode the proxy configuration is taken from the operating system. Note that the system mode is different from setting no proxy configuration. In the latter case, Electron falls back to the system settings only if no command-line options influence the proxy configuration. * `pacScript` string (optional) - The URL associated with the PAC file. * `proxyRules` string (optional) - Rules indicating which proxies to use. * `proxyBypassRules` string (optional) - Rules indicating which URLs should bypass the proxy settings. Returns `Promise<void>` - Resolves when the proxy setting process is complete. Sets the proxy settings. When `mode` is unspecified, `pacScript` and `proxyRules` are provided together, the `proxyRules` option is ignored and `pacScript` configuration is applied. You may need `ses.closeAllConnections` to close currently in flight connections to prevent pooled sockets using previous proxy from being reused by future requests. The `proxyRules` has to follow the rules below: ```sh proxyRules = schemeProxies[";"<schemeProxies>] schemeProxies = [<urlScheme>"="]<proxyURIList> urlScheme = "http" | "https" | "ftp" | "socks" proxyURIList = <proxyURL>[","<proxyURIList>] proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>] ``` For example: * `http=foopy:80;ftp=foopy2` - Use HTTP proxy `foopy:80` for `http://` URLs, and HTTP proxy `foopy2:80` for `ftp://` URLs. * `foopy:80` - Use HTTP proxy `foopy:80` for all URLs. * `foopy:80,bar,direct://` - Use HTTP proxy `foopy:80` for all URLs, failing over to `bar` if `foopy:80` is unavailable, and after that using no proxy. * `socks4://foopy` - Use SOCKS v4 proxy `foopy:1080` for all URLs. * `http=foopy,socks5://bar.com` - Use HTTP proxy `foopy` for http URLs, and fail over to the SOCKS5 proxy `bar.com` if `foopy` is unavailable. * `http=foopy,direct://` - Use HTTP proxy `foopy` for http URLs, and use no proxy if `foopy` is unavailable. * `http=foopy;socks=foopy2` - Use HTTP proxy `foopy` for http URLs, and use `socks4://foopy2` for all other URLs. The `proxyBypassRules` is a comma separated list of rules described below: * `[ URL_SCHEME "://" ] HOSTNAME_PATTERN [ ":" <port> ]` Match all hostnames that match the pattern HOSTNAME_PATTERN. Examples: "foobar.com", "\*foobar.com", "\*.foobar.com", "\*foobar.com:99", "https://x.\*.y.com:99" * `"." HOSTNAME_SUFFIX_PATTERN [ ":" PORT ]` Match a particular domain suffix. Examples: ".google.com", ".com", "http://.google.com" * `[ SCHEME "://" ] IP_LITERAL [ ":" PORT ]` Match URLs which are IP address literals. Examples: "127.0.1", "\[0:0::1]", "\[::1]", "http://\[::1]:99" * `IP_LITERAL "/" PREFIX_LENGTH_IN_BITS` Match any URL that is to an IP literal that falls between the given range. IP range is specified using CIDR notation. Examples: "192.168.1.1/16", "fefe:13::abc/33". * `<local>` Match local addresses. The meaning of `<local>` is whether the host matches one of: "127.0.0.1", "::1", "localhost". #### `ses.resolveHost(host, [options])` * `host` string - Hostname to resolve. * `options` Object (optional) * `queryType` string (optional) - Requested DNS query type. If unspecified, resolver will pick A or AAAA (or both) based on IPv4/IPv6 settings: * `A` - Fetch only A records * `AAAA` - Fetch only AAAA records. * `source` string (optional) - The source to use for resolved addresses. Default allows the resolver to pick an appropriate source. Only affects use of big external sources (e.g. calling the system for resolution or using DNS). Even if a source is specified, results can still come from cache, resolving "localhost" or IP literals, etc. One of the following values: * `any` (default) - Resolver will pick an appropriate source. Results could come from DNS, MulticastDNS, HOSTS file, etc * `system` - Results will only be retrieved from the system or OS, e.g. via the `getaddrinfo()` system call * `dns` - Results will only come from DNS queries * `mdns` - Results will only come from Multicast DNS queries * `localOnly` - No external sources will be used. Results will only come from fast local sources that are available no matter the source setting, e.g. cache, hosts file, IP literal resolution, etc. * `cacheUsage` string (optional) - Indicates what DNS cache entries, if any, can be used to provide a response. One of the following values: * `allowed` (default) - Results may come from the host cache if non-stale * `staleAllowed` - Results may come from the host cache even if stale (by expiration or network changes) * `disallowed` - Results will not come from the host cache. * `secureDnsPolicy` string (optional) - Controls the resolver's Secure DNS behavior for this request. One of the following values: * `allow` (default) * `disable` Returns [`Promise<ResolvedHost>`](structures/resolved-host.md) - Resolves with the resolved IP addresses for the `host`. #### `ses.resolveProxy(url)` * `url` URL Returns `Promise<string>` - Resolves with the proxy information for `url`. #### `ses.forceReloadProxyConfig()` Returns `Promise<void>` - Resolves when the all internal states of proxy service is reset and the latest proxy configuration is reapplied if it's already available. The pac script will be fetched from `pacScript` again if the proxy mode is `pac_script`. #### `ses.setDownloadPath(path)` * `path` string - The download location. Sets download saving directory. By default, the download directory will be the `Downloads` under the respective app folder. #### `ses.enableNetworkEmulation(options)` * `options` Object * `offline` boolean (optional) - Whether to emulate network outage. Defaults to false. * `latency` Double (optional) - RTT in ms. Defaults to 0 which will disable latency throttling. * `downloadThroughput` Double (optional) - Download rate in Bps. Defaults to 0 which will disable download throttling. * `uploadThroughput` Double (optional) - Upload rate in Bps. Defaults to 0 which will disable upload throttling. Emulates network with the given configuration for the `session`. ```javascript const win = new BrowserWindow() // To emulate a GPRS connection with 50kbps throughput and 500 ms latency. win.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }) // To emulate a network outage. win.webContents.session.enableNetworkEmulation({ offline: true }) ``` #### `ses.preconnect(options)` * `options` Object * `url` string - URL for preconnect. Only the origin is relevant for opening the socket. * `numSockets` number (optional) - number of sockets to preconnect. Must be between 1 and 6. Defaults to 1. Preconnects the given number of sockets to an origin. #### `ses.closeAllConnections()` Returns `Promise<void>` - Resolves when all connections are closed. **Note:** It will terminate / fail all requests currently in flight. #### `ses.fetch(input[, init])` * `input` string | [GlobalRequest](https://nodejs.org/api/globals.html#request) * `init` [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options) & { bypassCustomProtocolHandlers?: boolean } (optional) Returns `Promise<GlobalResponse>` - see [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response). Sends a request, similarly to how `fetch()` works in the renderer, using Chrome's network stack. This differs from Node's `fetch()`, which uses Node.js's HTTP stack. Example: ```js async function example () { const response = await net.fetch('https://my.app') if (response.ok) { const body = await response.json() // ... use the result. } } ``` See also [`net.fetch()`](net.md#netfetchinput-init), a convenience method which issues requests from the [default session](#sessiondefaultsession). See the MDN documentation for [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) for more details. Limitations: * `net.fetch()` does not support the `data:` or `blob:` schemes. * The value of the `integrity` option is ignored. * The `.type` and `.url` values of the returned `Response` object are incorrect. By default, requests made with `net.fetch` can be made to [custom protocols](protocol.md) as well as `file:`, and will trigger [webRequest](web-request.md) handlers if present. When the non-standard `bypassCustomProtocolHandlers` option is set in RequestInit, custom protocol handlers will not be called for this request. This allows forwarding an intercepted request to the built-in handler. [webRequest](web-request.md) handlers will still be triggered when bypassing custom protocols. ```js protocol.handle('https', (req) => { if (req.url === 'https://my-app.com') { return new Response('<body>my app</body>') } else { return net.fetch(req, { bypassCustomProtocolHandlers: true }) } }) ``` #### `ses.disableNetworkEmulation()` Disables any network emulation already active for the `session`. Resets to the original network configuration. #### `ses.setCertificateVerifyProc(proc)` * `proc` Function | null * `request` Object * `hostname` string * `certificate` [Certificate](structures/certificate.md) * `validatedCertificate` [Certificate](structures/certificate.md) * `isIssuedByKnownRoot` boolean - `true` if Chromium recognises the root CA as a standard root. If it isn't then it's probably the case that this certificate was generated by a MITM proxy whose root has been installed locally (for example, by a corporate proxy). This should not be trusted if the `verificationResult` is not `OK`. * `verificationResult` string - `OK` if the certificate is trusted, otherwise an error like `CERT_REVOKED`. * `errorCode` Integer - Error code. * `callback` Function * `verificationResult` Integer - Value can be one of certificate error codes from [here](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). Apart from the certificate error codes, the following special codes can be used. * `0` - Indicates success and disables Certificate Transparency verification. * `-2` - Indicates failure. * `-3` - Uses the verification result from chromium. Sets the certificate verify proc for `session`, the `proc` will be called with `proc(request, callback)` whenever a server certificate verification is requested. Calling `callback(0)` accepts the certificate, calling `callback(-2)` rejects it. Calling `setCertificateVerifyProc(null)` will revert back to default certificate verify proc. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.webContents.session.setCertificateVerifyProc((request, callback) => { const { hostname } = request if (hostname === 'github.com') { callback(0) } else { callback(-2) } }) ``` > **NOTE:** The result of this procedure is cached by the network service. #### `ses.setPermissionRequestHandler(handler)` * `handler` Function | null * `webContents` [WebContents](web-contents.md) - WebContents requesting the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. * `permission` string - The type of requested permission. * `clipboard-read` - Request access to read from the clipboard. * `clipboard-sanitized-write` - Request access to write to the clipboard. * `display-capture` - Request access to capture the screen via the [Screen Capture API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API). * `fullscreen` - Request control of the app's fullscreen state via the [Fullscreen API](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API). * `geolocation` - Request access to the user's location via the [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) * `idle-detection` - Request access to the user's idle state via the [IdleDetector API](https://developer.mozilla.org/en-US/docs/Web/API/IdleDetector). * `media` - Request access to media devices such as camera, microphone and speakers. * `mediaKeySystem` - Request access to DRM protected content. * `midi` - Request MIDI access in the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). * `midiSysex` - Request the use of system exclusive messages in the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). * `notifications` - Request notification creation and the ability to display them in the user's system tray using the [Notifications API](https://developer.mozilla.org/en-US/docs/Web/API/notification) * `pointerLock` - Request to directly interpret mouse movements as an input method via the [Pointer Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API). These requests always appear to originate from the main frame. * `keyboardLock` - Request capture of keypresses for any or all of the keys on the physical keyboard via the [Keyboard Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/lock). These requests always appear to originate from the main frame. * `openExternal` - Request to open links in external applications. * `window-management` - Request access to enumerate screens using the [`getScreenDetails`](https://developer.chrome.com/en/articles/multi-screen-window-placement/) API. * `unknown` - An unrecognized permission request. * `callback` Function * `permissionGranted` boolean - Allow or deny the permission. * `details` Object - Some properties are only available on certain permission types. * `externalURL` string (optional) - The url of the `openExternal` request. * `securityOrigin` string (optional) - The security origin of the `media` request. * `mediaTypes` string[] (optional) - The types of media access being requested, elements can be `video` or `audio` * `requestingUrl` string - The last URL the requesting frame loaded * `isMainFrame` boolean - Whether the frame making the request is the main frame Sets the handler which can be used to respond to permission requests for the `session`. Calling `callback(true)` will allow the permission and `callback(false)` will reject it. To clear the handler, call `setPermissionRequestHandler(null)`. Please note that you must also implement `setPermissionCheckHandler` to get complete permission handling. Most web APIs do a permission check and then make a permission request if the check is denied. ```javascript const { session } = require('electron') session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => { if (webContents.getURL() === 'some-host' && permission === 'notifications') { return callback(false) // denied. } callback(true) }) ``` #### `ses.setPermissionCheckHandler(handler)` * `handler` Function\<boolean> | null * `webContents` ([WebContents](web-contents.md) | null) - WebContents checking the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. All cross origin sub frames making permission checks will pass a `null` webContents to this handler, while certain other permission checks such as `notifications` checks will always pass `null`. You should use `embeddingOrigin` and `requestingOrigin` to determine what origin the owning frame and the requesting frame are on respectively. * `permission` string - Type of permission check. * `clipboard-read` - Request access to read from the clipboard. * `clipboard-sanitized-write` - Request access to write to the clipboard. * `geolocation` - Access the user's geolocation data via the [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) * `fullscreen` - Control of the app's fullscreen state via the [Fullscreen API](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API). * `hid` - Access the HID protocol to manipulate HID devices via the [WebHID API](https://developer.mozilla.org/en-US/docs/Web/API/WebHID_API). * `idle-detection` - Access the user's idle state via the [IdleDetector API](https://developer.mozilla.org/en-US/docs/Web/API/IdleDetector). * `media` - Access to media devices such as camera, microphone and speakers. * `mediaKeySystem` - Access to DRM protected content. * `midi` - Enable MIDI access in the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). * `midiSysex` - Use system exclusive messages in the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). * `notifications` - Configure and display desktop notifications to the user with the [Notifications API](https://developer.mozilla.org/en-US/docs/Web/API/notification). * `openExternal` - Open links in external applications. * `pointerLock` - Directly interpret mouse movements as an input method via the [Pointer Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API). These requests always appear to originate from the main frame. * `serial` - Read from and write to serial devices with the [Web Serial API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Serial_API). * `usb` - Expose non-standard Universal Serial Bus (USB) compatible devices services to the web with the [WebUSB API](https://developer.mozilla.org/en-US/docs/Web/API/WebUSB_API). * `requestingOrigin` string - The origin URL of the permission check * `details` Object - Some properties are only available on certain permission types. * `embeddingOrigin` string (optional) - The origin of the frame embedding the frame that made the permission check. Only set for cross-origin sub frames making permission checks. * `securityOrigin` string (optional) - The security origin of the `media` check. * `mediaType` string (optional) - The type of media access being requested, can be `video`, `audio` or `unknown` * `requestingUrl` string (optional) - The last URL the requesting frame loaded. This is not provided for cross-origin sub frames making permission checks. * `isMainFrame` boolean - Whether the frame making the request is the main frame Sets the handler which can be used to respond to permission checks for the `session`. Returning `true` will allow the permission and `false` will reject it. Please note that you must also implement `setPermissionRequestHandler` to get complete permission handling. Most web APIs do a permission check and then make a permission request if the check is denied. To clear the handler, call `setPermissionCheckHandler(null)`. ```javascript const { session } = require('electron') const url = require('url') session.fromPartition('some-partition').setPermissionCheckHandler((webContents, permission, requestingOrigin) => { if (new URL(requestingOrigin).hostname === 'some-host' && permission === 'notifications') { return true // granted } return false // denied }) ``` #### `ses.setDisplayMediaRequestHandler(handler)` * `handler` Function | null * `request` Object * `frame` [WebFrameMain](web-frame-main.md) - Frame that is requesting access to media. * `securityOrigin` String - Origin of the page making the request. * `videoRequested` Boolean - true if the web content requested a video stream. * `audioRequested` Boolean - true if the web content requested an audio stream. * `userGesture` Boolean - Whether a user gesture was active when this request was triggered. * `callback` Function * `streams` Object * `video` Object | [WebFrameMain](web-frame-main.md) (optional) * `id` String - The id of the stream being granted. This will usually come from a [DesktopCapturerSource](structures/desktop-capturer-source.md) object. * `name` String - The name of the stream being granted. This will usually come from a [DesktopCapturerSource](structures/desktop-capturer-source.md) object. * `audio` String | [WebFrameMain](web-frame-main.md) (optional) - If a string is specified, can be `loopback` or `loopbackWithMute`. Specifying a loopback device will capture system audio, and is currently only supported on Windows. If a WebFrameMain is specified, will capture audio from that frame. * `enableLocalEcho` Boolean (optional) - If `audio` is a [WebFrameMain](web-frame-main.md) and this is set to `true`, then local playback of audio will not be muted (e.g. using `MediaRecorder` to record `WebFrameMain` with this flag set to `true` will allow audio to pass through to the speakers while recording). Default is `false`. This handler will be called when web content requests access to display media via the `navigator.mediaDevices.getDisplayMedia` API. Use the [desktopCapturer](desktop-capturer.md) API to choose which stream(s) to grant access to. ```javascript const { session, desktopCapturer } = require('electron') session.defaultSession.setDisplayMediaRequestHandler((request, callback) => { desktopCapturer.getSources({ types: ['screen'] }).then((sources) => { // Grant access to the first screen found. callback({ video: sources[0] }) }) }) ``` Passing a [WebFrameMain](web-frame-main.md) object as a video or audio stream will capture the video or audio stream from that frame. ```javascript const { session } = require('electron') session.defaultSession.setDisplayMediaRequestHandler((request, callback) => { // Allow the tab to capture itself. callback({ video: request.frame }) }) ``` Passing `null` instead of a function resets the handler to its default state. #### `ses.setDevicePermissionHandler(handler)` * `handler` Function\<boolean> | null * `details` Object * `deviceType` string - The type of device that permission is being requested on, can be `hid`, `serial`, or `usb`. * `origin` string - The origin URL of the device permission check. * `device` [HIDDevice](structures/hid-device.md) | [SerialPort](structures/serial-port.md) | [USBDevice](structures/usb-device.md) - the device that permission is being requested for. Sets the handler which can be used to respond to device permission checks for the `session`. Returning `true` will allow the device to be permitted and `false` will reject it. To clear the handler, call `setDevicePermissionHandler(null)`. This handler can be used to provide default permissioning to devices without first calling for permission to devices (eg via `navigator.hid.requestDevice`). If this handler is not defined, the default device permissions as granted through device selection (eg via `navigator.hid.requestDevice`) will be used. Additionally, the default behavior of Electron is to store granted device permission in memory. If longer term storage is needed, a developer can store granted device permissions (eg when handling the `select-hid-device` event) and then read from that storage with `setDevicePermissionHandler`. ```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'hid') { // Add logic here to determine if permission should be given to allow HID selection return true } else if (permission === 'serial') { // Add logic here to determine if permission should be given to allow serial port selection } else if (permission === 'usb') { // Add logic here to determine if permission should be given to allow USB device selection } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } else if (details.deviceType === 'serial') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } } return false }) win.webContents.session.on('select-hid-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === 9025 && device.productId === 67 }) callback(selectedDevice?.deviceId) }) }) ``` #### `ses.setUSBProtectedClassesHandler(handler)` * `handler` Function\<string[]> | null * `details` Object * `protectedClasses` string[] - The current list of protected USB classes. Possible class values include: * `audio` * `audio-video` * `hid` * `mass-storage` * `smart-card` * `video` * `wireless` Sets the handler which can be used to override which [USB classes are protected](https://wicg.github.io/webusb/#usbinterface-interface). The return value for the handler is a string array of USB classes which should be considered protected (eg not available in the renderer). Valid values for the array are: * `audio` * `audio-video` * `hid` * `mass-storage` * `smart-card` * `video` * `wireless` Returning an empty string array from the handler will allow all USB classes; returning the passed in array will maintain the default list of protected USB classes (this is also the default behavior if a handler is not defined). To clear the handler, call `setUSBProtectedClassesHandler(null)`. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setUSBProtectedClassesHandler((details) => { // Allow all classes: // return [] // Keep the current set of protected classes: // return details.protectedClasses // Selectively remove classes: return details.protectedClasses.filter((usbClass) => { // Exclude classes except for audio classes return usbClass.indexOf('audio') === -1 }) }) }) ``` #### `ses.setBluetoothPairingHandler(handler)` _Windows_ _Linux_ * `handler` Function | null * `details` Object * `deviceId` string * `pairingKind` string - The type of pairing prompt being requested. One of the following values: * `confirm` This prompt is requesting confirmation that the Bluetooth device should be paired. * `confirmPin` This prompt is requesting confirmation that the provided PIN matches the pin displayed on the device. * `providePin` This prompt is requesting that a pin be provided for the device. * `frame` [WebFrameMain](web-frame-main.md) * `pin` string (optional) - The pin value to verify if `pairingKind` is `confirmPin`. * `callback` Function * `response` Object * `confirmed` boolean - `false` should be passed in if the dialog is canceled. If the `pairingKind` is `confirm` or `confirmPin`, this value should indicate if the pairing is confirmed. If the `pairingKind` is `providePin` the value should be `true` when a value is provided. * `pin` string | null (optional) - When the `pairingKind` is `providePin` this value should be the required pin for the Bluetooth device. Sets a handler to respond to Bluetooth pairing requests. This handler allows developers to handle devices that require additional validation before pairing. When a handler is not defined, any pairing on Linux or Windows that requires additional validation will be automatically cancelled. macOS does not require a handler because macOS handles the pairing automatically. To clear the handler, call `setBluetoothPairingHandler(null)`. ```javascript const { app, BrowserWindow, session } = require('electron') const path = require('node:path') function createWindow () { let bluetoothPinCallback = null const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js') } }) mainWindow.webContents.session.setBluetoothPairingHandler((details, callback) => { bluetoothPinCallback = callback // Send a IPC message to the renderer to prompt the user to confirm the pairing. // Note that this will require logic in the renderer to handle this message and // display a prompt to the user. mainWindow.webContents.send('bluetooth-pairing-request', details) }) // Listen for an IPC message from the renderer to get the response for the Bluetooth pairing. mainWindow.webContents.ipc.on('bluetooth-pairing-response', (event, response) => { bluetoothPinCallback(response) }) } app.whenReady().then(() => { createWindow() }) ``` #### `ses.clearHostResolverCache()` Returns `Promise<void>` - Resolves when the operation is complete. Clears the host resolver cache. #### `ses.allowNTLMCredentialsForDomains(domains)` * `domains` string - A comma-separated list of servers for which integrated authentication is enabled. Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate authentication. ```javascript const { session } = require('electron') // consider any url ending with `example.com`, `foobar.com`, `baz` // for integrated authentication. session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz') // consider all urls for integrated authentication. session.defaultSession.allowNTLMCredentialsForDomains('*') ``` #### `ses.setUserAgent(userAgent[, acceptLanguages])` * `userAgent` string * `acceptLanguages` string (optional) Overrides the `userAgent` and `acceptLanguages` for this session. The `acceptLanguages` must a comma separated ordered list of language codes, for example `"en-US,fr,de,ko,zh-CN,ja"`. This doesn't affect existing `WebContents`, and each `WebContents` can use `webContents.setUserAgent` to override the session-wide user agent. #### `ses.isPersistent()` Returns `boolean` - Whether or not this session is a persistent one. The default `webContents` session of a `BrowserWindow` is persistent. When creating a session from a partition, session prefixed with `persist:` will be persistent, while others will be temporary. #### `ses.getUserAgent()` Returns `string` - The user agent for this session. #### `ses.setSSLConfig(config)` * `config` Object * `minVersion` string (optional) - Can be `tls1`, `tls1.1`, `tls1.2` or `tls1.3`. The minimum SSL version to allow when connecting to remote servers. Defaults to `tls1`. * `maxVersion` string (optional) - Can be `tls1.2` or `tls1.3`. The maximum SSL version to allow when connecting to remote servers. Defaults to `tls1.3`. * `disabledCipherSuites` Integer[] (optional) - List of cipher suites which should be explicitly prevented from being used in addition to those disabled by the net built-in policy. Supported literal forms: 0xAABB, where AA is `cipher_suite[0]` and BB is `cipher_suite[1]`, as defined in RFC 2246, Section 7.4.1.2. Unrecognized but parsable cipher suites in this form will not return an error. Ex: To disable TLS_RSA_WITH_RC4_128_MD5, specify 0x0004, while to disable TLS_ECDH_ECDSA_WITH_RC4_128_SHA, specify 0xC002. Note that TLSv1.3 ciphers cannot be disabled using this mechanism. Sets the SSL configuration for the session. All subsequent network requests will use the new configuration. Existing network connections (such as WebSocket connections) will not be terminated, but old sockets in the pool will not be reused for new connections. #### `ses.getBlobData(identifier)` * `identifier` string - Valid UUID. Returns `Promise<Buffer>` - resolves with blob data. #### `ses.downloadURL(url[, options])` * `url` string * `options` Object (optional) * `headers` Record<string, string> (optional) - HTTP request headers. Initiates a download of the resource at `url`. The API will generate a [DownloadItem](download-item.md) that can be accessed with the [will-download](#event-will-download) event. **Note:** This does not perform any security checks that relate to a page's origin, unlike [`webContents.downloadURL`](web-contents.md#contentsdownloadurlurl-options). #### `ses.createInterruptedDownload(options)` * `options` Object * `path` string - Absolute path of the download. * `urlChain` string[] - Complete URL chain for the download. * `mimeType` string (optional) * `offset` Integer - Start range for the download. * `length` Integer - Total length of the download. * `lastModified` string (optional) - Last-Modified header value. * `eTag` string (optional) - ETag header value. * `startTime` Double (optional) - Time when download was started in number of seconds since UNIX epoch. Allows resuming `cancelled` or `interrupted` downloads from previous `Session`. The API will generate a [DownloadItem](download-item.md) that can be accessed with the [will-download](#event-will-download) event. The [DownloadItem](download-item.md) will not have any `WebContents` associated with it and the initial state will be `interrupted`. The download will start only when the `resume` API is called on the [DownloadItem](download-item.md). #### `ses.clearAuthCache()` Returns `Promise<void>` - resolves when the session’s HTTP authentication cache has been cleared. #### `ses.setPreloads(preloads)` * `preloads` string[] - An array of absolute path to preload scripts Adds scripts that will be executed on ALL web contents that are associated with this session just before normal `preload` scripts run. #### `ses.getPreloads()` Returns `string[]` an array of paths to preload scripts that have been registered. #### `ses.setCodeCachePath(path)` * `path` String - Absolute path to store the v8 generated JS code cache from the renderer. Sets the directory to store the generated JS [code cache](https://v8.dev/blog/code-caching-for-devs) for this session. The directory is not required to be created by the user before this call, the runtime will create if it does not exist otherwise will use the existing directory. If directory cannot be created, then code cache will not be used and all operations related to code cache will fail silently inside the runtime. By default, the directory will be `Code Cache` under the respective user data folder. #### `ses.clearCodeCaches(options)` * `options` Object * `urls` String[] (optional) - An array of url corresponding to the resource whose generated code cache needs to be removed. If the list is empty then all entries in the cache directory will be removed. Returns `Promise<void>` - resolves when the code cache clear operation is complete. #### `ses.setSpellCheckerEnabled(enable)` * `enable` boolean Sets whether to enable the builtin spell checker. #### `ses.isSpellCheckerEnabled()` Returns `boolean` - Whether the builtin spell checker is enabled. #### `ses.setSpellCheckerLanguages(languages)` * `languages` string[] - An array of language codes to enable the spellchecker for. The built in spellchecker does not automatically detect what language a user is typing in. In order for the spell checker to correctly check their words you must call this API with an array of language codes. You can get the list of supported language codes with the `ses.availableSpellCheckerLanguages` property. **Note:** On macOS the OS spellchecker is used and will detect your language automatically. This API is a no-op on macOS. #### `ses.getSpellCheckerLanguages()` Returns `string[]` - An array of language codes the spellchecker is enabled for. If this list is empty the spellchecker will fallback to using `en-US`. By default on launch if this setting is an empty list Electron will try to populate this setting with the current OS locale. This setting is persisted across restarts. **Note:** On macOS the OS spellchecker is used and has its own list of languages. On macOS, this API will return whichever languages have been configured by the OS. #### `ses.setSpellCheckerDictionaryDownloadURL(url)` * `url` string - A base URL for Electron to download hunspell dictionaries from. By default Electron will download hunspell dictionaries from the Chromium CDN. If you want to override this behavior you can use this API to point the dictionary downloader at your own hosted version of the hunspell dictionaries. We publish a `hunspell_dictionaries.zip` file with each release which contains the files you need to host here. The file server must be **case insensitive**. If you cannot do this, you must upload each file twice: once with the case it has in the ZIP file and once with the filename as all lowercase. If the files present in `hunspell_dictionaries.zip` are available at `https://example.com/dictionaries/language-code.bdic` then you should call this api with `ses.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/')`. Please note the trailing slash. The URL to the dictionaries is formed as `${url}${filename}`. **Note:** On macOS the OS spellchecker is used and therefore we do not download any dictionary files. This API is a no-op on macOS. #### `ses.listWordsInSpellCheckerDictionary()` Returns `Promise<string[]>` - An array of all words in app's custom dictionary. Resolves when the full dictionary is loaded from disk. #### `ses.addWordToSpellCheckerDictionary(word)` * `word` string - The word you want to add to the dictionary Returns `boolean` - Whether the word was successfully written to the custom dictionary. This API will not work on non-persistent (in-memory) sessions. **Note:** On macOS and Windows 10 this word will be written to the OS custom dictionary as well #### `ses.removeWordFromSpellCheckerDictionary(word)` * `word` string - The word you want to remove from the dictionary Returns `boolean` - Whether the word was successfully removed from the custom dictionary. This API will not work on non-persistent (in-memory) sessions. **Note:** On macOS and Windows 10 this word will be removed from the OS custom dictionary as well #### `ses.loadExtension(path[, options])` * `path` string - Path to a directory containing an unpacked Chrome extension * `options` Object (optional) * `allowFileAccess` boolean - Whether to allow the extension to read local files over `file://` protocol and inject content scripts into `file://` pages. This is required e.g. for loading devtools extensions on `file://` URLs. Defaults to false. Returns `Promise<Extension>` - resolves when the extension is loaded. This method will raise an exception if the extension could not be loaded. If there are warnings when installing the extension (e.g. if the extension requests an API that Electron does not support) then they will be logged to the console. Note that Electron does not support the full range of Chrome extensions APIs. See [Supported Extensions APIs](extensions.md#supported-extensions-apis) for more details on what is supported. Note that in previous versions of Electron, extensions that were loaded would be remembered for future runs of the application. This is no longer the case: `loadExtension` must be called on every boot of your app if you want the extension to be loaded. ```js const { app, session } = require('electron') const path = require('node:path') app.whenReady().then(async () => { await session.defaultSession.loadExtension( path.join(__dirname, 'react-devtools'), // allowFileAccess is required to load the devtools extension on file:// URLs. { allowFileAccess: true } ) // Note that in order to use the React DevTools extension, you'll need to // download and unzip a copy of the extension. }) ``` This API does not support loading packed (.crx) extensions. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. **Note:** Loading extensions into in-memory (non-persistent) sessions is not supported and will throw an error. #### `ses.removeExtension(extensionId)` * `extensionId` string - ID of extension to remove Unloads an extension. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getExtension(extensionId)` * `extensionId` string - ID of extension to query Returns `Extension | null` - The loaded extension with the given ID. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getAllExtensions()` Returns `Extension[]` - A list of all loaded extensions. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getStoragePath()` Returns `string | null` - The absolute file system path where data for this session is persisted on disk. For in memory sessions this returns `null`. ### Instance Properties The following properties are available on instances of `Session`: #### `ses.availableSpellCheckerLanguages` _Readonly_ A `string[]` array which consists of all the known available spell checker languages. Providing a language code to the `setSpellCheckerLanguages` API that isn't in this array will result in an error. #### `ses.spellCheckerEnabled` A `boolean` indicating whether builtin spell checker is enabled. #### `ses.storagePath` _Readonly_ A `string | null` indicating the absolute file system path where data for this session is persisted on disk. For in memory sessions this returns `null`. #### `ses.cookies` _Readonly_ A [`Cookies`](cookies.md) object for this session. #### `ses.serviceWorkers` _Readonly_ A [`ServiceWorkers`](service-workers.md) object for this session. #### `ses.webRequest` _Readonly_ A [`WebRequest`](web-request.md) object for this session. #### `ses.protocol` _Readonly_ A [`Protocol`](protocol.md) object for this session. ```javascript const { app, session } = require('electron') const path = require('node:path') app.whenReady().then(() => { const protocol = session.fromPartition('some-partition').protocol if (!protocol.registerFileProtocol('atom', (request, callback) => { const url = request.url.substr(7) callback({ path: path.normalize(path.join(__dirname, url)) }) })) { console.error('Failed to register protocol') } }) ``` #### `ses.netLog` _Readonly_ A [`NetLog`](net-log.md) object for this session. ```javascript const { app, session } = require('electron') app.whenReady().then(async () => { const netLog = session.fromPartition('some-partition').netLog netLog.startLogging('/path/to/net-log') // After some network events const path = await netLog.stopLogging() console.log('Net-logs written to', path) }) ```
closed
electron/electron
https://github.com/electron/electron
40,439
Convert legacy IPC calls in extensions code to use mojo
https://chromium-review.googlesource.com/c/chromium/src/+/4995136 turned on the build flag to use the new mojo IPC pipe for messaging in extensions. In #40418 we turned this off because we have not converted our extensions code to use mojo. It appears that in chromium the follow CLs were landed to use mojo in extensions: - 4947890: [extensions] Convert Extension Messaging APIs over to mojo | https://chromium-review.googlesource.com/c/chromium/src/+/4947890 - 4950041: [extensions] Port Event Acks to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4950041 - 4902564: [extensions] Move WakeEventPage to mojom::RendererHost | https://chromium-review.googlesource.com/c/chromium/src/+/4902564 - 4956841: [extensions] Port GetMessageBundle over to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4956841 Once these changes have landed, the following flag override in build/args/all.gn should be removed: `enable_extensions_legacy_ipc = true`
https://github.com/electron/electron/issues/40439
https://github.com/electron/electron/pull/40511
088affd4a4311e03b8ed400cdf5d82f1db2125a4
371bca69b69351dc47d4b4dcfdf9a626f43b3b51
2023-11-02T18:50:40Z
c++
2023-11-15T14:30:47Z
build/args/all.gn
is_electron_build = true root_extra_deps = [ "//electron" ] # Registry of NMVs --> https://github.com/nodejs/node/blob/main/doc/abi_version_registry.json node_module_version = 119 v8_promise_internal_field_count = 1 v8_embedder_string = "-electron.0" # TODO: this breaks mksnapshot v8_enable_snapshot_native_code_counters = false # we use this api v8_enable_javascript_promise_hooks = true enable_cdm_host_verification = false proprietary_codecs = true ffmpeg_branding = "Chrome" enable_printing = true # Removes DLLs from the build, which are only meant to be used for Chromium development. # See https://github.com/electron/electron/pull/17985 angle_enable_vulkan_validation_layers = false dawn_enable_vulkan_validation_layers = false # These are disabled because they cause the zip manifest to differ between # testing and release builds. # See https://chromium-review.googlesource.com/c/chromium/src/+/2774898. enable_pseudolocales = false # Make application name configurable at runtime for cookie crypto allow_runtime_configurable_key_storage = true # CET shadow stack is incompatible with v8, until v8 is CET compliant # enabling this flag causes main process crashes where CET is enabled # Ref: https://source.chromium.org/chromium/chromium/src/+/45fba672185aae233e75d6ddc81ea1e0b30db050:v8/BUILD.gn;l=357 enable_cet_shadow_stack = false # For similar reasons, disable CFI, which is not well supported in V8. # Chromium doesn't have any problems with this because they do not run # V8 in the browser process. # Ref: https://source.chromium.org/chromium/chromium/src/+/45fba672185aae233e75d6ddc81ea1e0b30db050:v8/BUILD.gn;l=281 is_cfi = false # TODO: fix this once sysroots have been updated. use_qt = false # https://chromium-review.googlesource.com/c/chromium/src/+/4365718 # TODO(codebytere): fix perfetto incompatibility with Node.js. use_perfetto_client_library = false # Disables the builtins PGO for V8 v8_builtins_profiling_log_file = "" # https://chromium.googlesource.com/chromium/src/+/main/docs/dangling_ptr.md # TODO(vertedinde): hunt down dangling pointers on Linux enable_dangling_raw_ptr_checks = false # This flag speeds up the performance of fork/execve on linux systems. # Ref: https://chromium-review.googlesource.com/c/v8/v8/+/4602858 v8_enable_private_mapping_fork_optimization = true # https://chromium-review.googlesource.com/c/chromium/src/+/4995136 # TODO(jkleinsc): convert legacy IPC calls in extensions to use mojo # https://github.com/electron/electron/issues/40439 enable_extensions_legacy_ipc = true
closed
electron/electron
https://github.com/electron/electron
40,439
Convert legacy IPC calls in extensions code to use mojo
https://chromium-review.googlesource.com/c/chromium/src/+/4995136 turned on the build flag to use the new mojo IPC pipe for messaging in extensions. In #40418 we turned this off because we have not converted our extensions code to use mojo. It appears that in chromium the follow CLs were landed to use mojo in extensions: - 4947890: [extensions] Convert Extension Messaging APIs over to mojo | https://chromium-review.googlesource.com/c/chromium/src/+/4947890 - 4950041: [extensions] Port Event Acks to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4950041 - 4902564: [extensions] Move WakeEventPage to mojom::RendererHost | https://chromium-review.googlesource.com/c/chromium/src/+/4902564 - 4956841: [extensions] Port GetMessageBundle over to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4956841 Once these changes have landed, the following flag override in build/args/all.gn should be removed: `enable_extensions_legacy_ipc = true`
https://github.com/electron/electron/issues/40439
https://github.com/electron/electron/pull/40511
088affd4a4311e03b8ed400cdf5d82f1db2125a4
371bca69b69351dc47d4b4dcfdf9a626f43b3b51
2023-11-02T18:50:40Z
c++
2023-11-15T14:30:47Z
filenames.gni
filenames = { default_app_ts_sources = [ "default_app/default_app.ts", "default_app/main.ts", "default_app/preload.ts", ] default_app_static_sources = [ "default_app/icon.png", "default_app/index.html", "default_app/package.json", "default_app/styles.css", ] default_app_octicon_sources = [ "node_modules/@primer/octicons/build/build.css", "node_modules/@primer/octicons/build/svg/book-24.svg", "node_modules/@primer/octicons/build/svg/code-square-24.svg", "node_modules/@primer/octicons/build/svg/gift-24.svg", "node_modules/@primer/octicons/build/svg/mark-github-16.svg", "node_modules/@primer/octicons/build/svg/star-fill-24.svg", ] lib_sources_linux = [ "shell/browser/browser_linux.cc", "shell/browser/electron_browser_main_parts_linux.cc", "shell/browser/lib/power_observer_linux.cc", "shell/browser/lib/power_observer_linux.h", "shell/browser/linux/unity_service.cc", "shell/browser/linux/unity_service.h", "shell/browser/notifications/linux/libnotify_notification.cc", "shell/browser/notifications/linux/libnotify_notification.h", "shell/browser/notifications/linux/notification_presenter_linux.cc", "shell/browser/notifications/linux/notification_presenter_linux.h", "shell/browser/relauncher_linux.cc", "shell/browser/ui/electron_desktop_window_tree_host_linux.cc", "shell/browser/ui/file_dialog_gtk.cc", "shell/browser/ui/gtk/menu_gtk.cc", "shell/browser/ui/gtk/menu_gtk.h", "shell/browser/ui/gtk/menu_util.cc", "shell/browser/ui/gtk/menu_util.h", "shell/browser/ui/message_box_gtk.cc", "shell/browser/ui/status_icon_gtk.cc", "shell/browser/ui/status_icon_gtk.h", "shell/browser/ui/tray_icon_linux.cc", "shell/browser/ui/tray_icon_linux.h", "shell/browser/ui/views/client_frame_view_linux.cc", "shell/browser/ui/views/client_frame_view_linux.h", "shell/common/application_info_linux.cc", "shell/common/language_util_linux.cc", "shell/common/node_bindings_linux.cc", "shell/common/node_bindings_linux.h", "shell/common/platform_util_linux.cc", ] lib_sources_linux_x11 = [ "shell/browser/ui/views/global_menu_bar_registrar_x11.cc", "shell/browser/ui/views/global_menu_bar_registrar_x11.h", "shell/browser/ui/views/global_menu_bar_x11.cc", "shell/browser/ui/views/global_menu_bar_x11.h", "shell/browser/ui/x/event_disabler.cc", "shell/browser/ui/x/event_disabler.h", "shell/browser/ui/x/x_window_utils.cc", "shell/browser/ui/x/x_window_utils.h", ] lib_sources_posix = [ "shell/browser/electron_browser_main_parts_posix.cc" ] lib_sources_win = [ "shell/browser/api/electron_api_power_monitor_win.cc", "shell/browser/api/electron_api_system_preferences_win.cc", "shell/browser/browser_win.cc", "shell/browser/native_window_views_win.cc", "shell/browser/notifications/win/notification_presenter_win.cc", "shell/browser/notifications/win/notification_presenter_win.h", "shell/browser/notifications/win/windows_toast_notification.cc", "shell/browser/notifications/win/windows_toast_notification.h", "shell/browser/relauncher_win.cc", "shell/browser/ui/certificate_trust_win.cc", "shell/browser/ui/file_dialog_win.cc", "shell/browser/ui/message_box_win.cc", "shell/browser/ui/tray_icon_win.cc", "shell/browser/ui/views/electron_views_delegate_win.cc", "shell/browser/ui/views/win_icon_painter.cc", "shell/browser/ui/views/win_icon_painter.h", "shell/browser/ui/views/win_frame_view.cc", "shell/browser/ui/views/win_frame_view.h", "shell/browser/ui/views/win_caption_button.cc", "shell/browser/ui/views/win_caption_button.h", "shell/browser/ui/views/win_caption_button_container.cc", "shell/browser/ui/views/win_caption_button_container.h", "shell/browser/ui/win/dialog_thread.cc", "shell/browser/ui/win/dialog_thread.h", "shell/browser/ui/win/electron_desktop_native_widget_aura.cc", "shell/browser/ui/win/electron_desktop_native_widget_aura.h", "shell/browser/ui/win/electron_desktop_window_tree_host_win.cc", "shell/browser/ui/win/electron_desktop_window_tree_host_win.h", "shell/browser/ui/win/jump_list.cc", "shell/browser/ui/win/jump_list.h", "shell/browser/ui/win/notify_icon_host.cc", "shell/browser/ui/win/notify_icon_host.h", "shell/browser/ui/win/notify_icon.cc", "shell/browser/ui/win/notify_icon.h", "shell/browser/ui/win/taskbar_host.cc", "shell/browser/ui/win/taskbar_host.h", "shell/browser/win/dark_mode.cc", "shell/browser/win/dark_mode.h", "shell/browser/win/scoped_hstring.cc", "shell/browser/win/scoped_hstring.h", "shell/common/api/electron_api_native_image_win.cc", "shell/common/application_info_win.cc", "shell/common/language_util_win.cc", "shell/common/node_bindings_win.cc", "shell/common/node_bindings_win.h", "shell/common/platform_util_win.cc", ] lib_sources_mac = [ "shell/app/electron_main_delegate_mac.h", "shell/app/electron_main_delegate_mac.mm", "shell/browser/api/electron_api_app_mac.mm", "shell/browser/api/electron_api_menu_mac.h", "shell/browser/api/electron_api_menu_mac.mm", "shell/browser/api/electron_api_native_theme_mac.mm", "shell/browser/api/electron_api_power_monitor_mac.mm", "shell/browser/api/electron_api_push_notifications_mac.mm", "shell/browser/api/electron_api_system_preferences_mac.mm", "shell/browser/api/electron_api_web_contents_mac.mm", "shell/browser/auto_updater_mac.mm", "shell/browser/browser_mac.mm", "shell/browser/electron_browser_main_parts_mac.mm", "shell/browser/mac/dict_util.h", "shell/browser/mac/dict_util.mm", "shell/browser/mac/electron_application.h", "shell/browser/mac/electron_application.mm", "shell/browser/mac/electron_application_delegate.h", "shell/browser/mac/electron_application_delegate.mm", "shell/browser/mac/in_app_purchase_observer.h", "shell/browser/mac/in_app_purchase_observer.mm", "shell/browser/mac/in_app_purchase_product.h", "shell/browser/mac/in_app_purchase_product.mm", "shell/browser/mac/in_app_purchase.h", "shell/browser/mac/in_app_purchase.mm", "shell/browser/native_browser_view_mac.h", "shell/browser/native_browser_view_mac.mm", "shell/browser/native_window_mac.h", "shell/browser/native_window_mac.mm", "shell/browser/notifications/mac/cocoa_notification.h", "shell/browser/notifications/mac/cocoa_notification.mm", "shell/browser/notifications/mac/notification_center_delegate.h", "shell/browser/notifications/mac/notification_center_delegate.mm", "shell/browser/notifications/mac/notification_presenter_mac.h", "shell/browser/notifications/mac/notification_presenter_mac.mm", "shell/browser/osr/osr_host_display_client_mac.mm", "shell/browser/osr/osr_web_contents_view_mac.mm", "shell/browser/relauncher_mac.cc", "shell/browser/ui/certificate_trust_mac.mm", "shell/browser/ui/cocoa/delayed_native_view_host.h", "shell/browser/ui/cocoa/delayed_native_view_host.mm", "shell/browser/ui/cocoa/electron_bundle_mover.h", "shell/browser/ui/cocoa/electron_bundle_mover.mm", "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.h", "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm", "shell/browser/ui/cocoa/electron_menu_controller.h", "shell/browser/ui/cocoa/electron_menu_controller.mm", "shell/browser/ui/cocoa/electron_native_widget_mac.h", "shell/browser/ui/cocoa/electron_native_widget_mac.mm", "shell/browser/ui/cocoa/electron_ns_panel.h", "shell/browser/ui/cocoa/electron_ns_panel.mm", "shell/browser/ui/cocoa/electron_ns_window.h", "shell/browser/ui/cocoa/electron_ns_window.mm", "shell/browser/ui/cocoa/electron_ns_window_delegate.h", "shell/browser/ui/cocoa/electron_ns_window_delegate.mm", "shell/browser/ui/cocoa/electron_preview_item.h", "shell/browser/ui/cocoa/electron_preview_item.mm", "shell/browser/ui/cocoa/electron_touch_bar.h", "shell/browser/ui/cocoa/electron_touch_bar.mm", "shell/browser/ui/cocoa/event_dispatching_window.h", "shell/browser/ui/cocoa/event_dispatching_window.mm", "shell/browser/ui/cocoa/NSString+ANSI.h", "shell/browser/ui/cocoa/NSString+ANSI.mm", "shell/browser/ui/cocoa/root_view_mac.h", "shell/browser/ui/cocoa/root_view_mac.mm", "shell/browser/ui/cocoa/views_delegate_mac.h", "shell/browser/ui/cocoa/views_delegate_mac.mm", "shell/browser/ui/cocoa/window_buttons_proxy.h", "shell/browser/ui/cocoa/window_buttons_proxy.mm", "shell/browser/ui/drag_util_mac.mm", "shell/browser/ui/file_dialog_mac.mm", "shell/browser/ui/inspectable_web_contents_view_mac.h", "shell/browser/ui/inspectable_web_contents_view_mac.mm", "shell/browser/ui/message_box_mac.mm", "shell/browser/ui/tray_icon_cocoa.h", "shell/browser/ui/tray_icon_cocoa.mm", "shell/common/api/electron_api_clipboard_mac.mm", "shell/common/api/electron_api_native_image_mac.mm", "shell/common/asar/archive_mac.mm", "shell/common/application_info_mac.mm", "shell/common/language_util_mac.mm", "shell/common/mac/main_application_bundle.h", "shell/common/mac/main_application_bundle.mm", "shell/common/node_bindings_mac.cc", "shell/common/node_bindings_mac.h", "shell/common/platform_util_mac.mm", ] lib_sources_views = [ "shell/browser/api/electron_api_menu_views.cc", "shell/browser/api/electron_api_menu_views.h", "shell/browser/native_browser_view_views.cc", "shell/browser/native_browser_view_views.h", "shell/browser/native_window_views.cc", "shell/browser/native_window_views.h", "shell/browser/ui/drag_util_views.cc", "shell/browser/ui/views/autofill_popup_view.cc", "shell/browser/ui/views/autofill_popup_view.h", "shell/browser/ui/views/electron_views_delegate.cc", "shell/browser/ui/views/electron_views_delegate.h", "shell/browser/ui/views/frameless_view.cc", "shell/browser/ui/views/frameless_view.h", "shell/browser/ui/views/inspectable_web_contents_view_views.cc", "shell/browser/ui/views/inspectable_web_contents_view_views.h", "shell/browser/ui/views/menu_bar.cc", "shell/browser/ui/views/menu_bar.h", "shell/browser/ui/views/menu_delegate.cc", "shell/browser/ui/views/menu_delegate.h", "shell/browser/ui/views/menu_model_adapter.cc", "shell/browser/ui/views/menu_model_adapter.h", "shell/browser/ui/views/native_frame_view.cc", "shell/browser/ui/views/native_frame_view.h", "shell/browser/ui/views/root_view.cc", "shell/browser/ui/views/root_view.h", "shell/browser/ui/views/submenu_button.cc", "shell/browser/ui/views/submenu_button.h", ] lib_sources = [ "shell/app/command_line_args.cc", "shell/app/command_line_args.h", "shell/app/electron_content_client.cc", "shell/app/electron_content_client.h", "shell/app/electron_crash_reporter_client.cc", "shell/app/electron_crash_reporter_client.h", "shell/app/electron_main_delegate.cc", "shell/app/electron_main_delegate.h", "shell/app/node_main.cc", "shell/app/node_main.h", "shell/app/uv_task_runner.cc", "shell/app/uv_task_runner.h", "shell/browser/api/electron_api_app.cc", "shell/browser/api/electron_api_app.h", "shell/browser/api/electron_api_auto_updater.cc", "shell/browser/api/electron_api_auto_updater.h", "shell/browser/api/electron_api_base_window.cc", "shell/browser/api/electron_api_base_window.h", "shell/browser/api/electron_api_browser_view.cc", "shell/browser/api/electron_api_browser_view.h", "shell/browser/api/electron_api_browser_window.cc", "shell/browser/api/electron_api_browser_window.h", "shell/browser/api/electron_api_content_tracing.cc", "shell/browser/api/electron_api_cookies.cc", "shell/browser/api/electron_api_cookies.h", "shell/browser/api/electron_api_crash_reporter.cc", "shell/browser/api/electron_api_crash_reporter.h", "shell/browser/api/electron_api_data_pipe_holder.cc", "shell/browser/api/electron_api_data_pipe_holder.h", "shell/browser/api/electron_api_debugger.cc", "shell/browser/api/electron_api_debugger.h", "shell/browser/api/electron_api_desktop_capturer.cc", "shell/browser/api/electron_api_desktop_capturer.h", "shell/browser/api/electron_api_dialog.cc", "shell/browser/api/electron_api_download_item.cc", "shell/browser/api/electron_api_download_item.h", "shell/browser/api/electron_api_event_emitter.cc", "shell/browser/api/electron_api_event_emitter.h", "shell/browser/api/electron_api_global_shortcut.cc", "shell/browser/api/electron_api_global_shortcut.h", "shell/browser/api/electron_api_in_app_purchase.cc", "shell/browser/api/electron_api_in_app_purchase.h", "shell/browser/api/electron_api_menu.cc", "shell/browser/api/electron_api_menu.h", "shell/browser/api/electron_api_native_theme.cc", "shell/browser/api/electron_api_native_theme.h", "shell/browser/api/electron_api_net.cc", "shell/browser/api/electron_api_net_log.cc", "shell/browser/api/electron_api_net_log.h", "shell/browser/api/electron_api_notification.cc", "shell/browser/api/electron_api_notification.h", "shell/browser/api/electron_api_power_monitor.cc", "shell/browser/api/electron_api_power_monitor.h", "shell/browser/api/electron_api_power_save_blocker.cc", "shell/browser/api/electron_api_power_save_blocker.h", "shell/browser/api/electron_api_printing.cc", "shell/browser/api/electron_api_protocol.cc", "shell/browser/api/electron_api_protocol.h", "shell/browser/api/electron_api_push_notifications.cc", "shell/browser/api/electron_api_push_notifications.h", "shell/browser/api/electron_api_safe_storage.cc", "shell/browser/api/electron_api_safe_storage.h", "shell/browser/api/electron_api_screen.cc", "shell/browser/api/electron_api_screen.h", "shell/browser/api/electron_api_service_worker_context.cc", "shell/browser/api/electron_api_service_worker_context.h", "shell/browser/api/electron_api_session.cc", "shell/browser/api/electron_api_session.h", "shell/browser/api/electron_api_system_preferences.cc", "shell/browser/api/electron_api_system_preferences.h", "shell/browser/api/electron_api_tray.cc", "shell/browser/api/electron_api_tray.h", "shell/browser/api/electron_api_url_loader.cc", "shell/browser/api/electron_api_url_loader.h", "shell/browser/api/electron_api_utility_process.cc", "shell/browser/api/electron_api_utility_process.h", "shell/browser/api/electron_api_view.cc", "shell/browser/api/electron_api_view.h", "shell/browser/api/electron_api_web_contents.cc", "shell/browser/api/electron_api_web_contents.h", "shell/browser/api/electron_api_web_contents_impl.cc", "shell/browser/api/electron_api_web_contents_view.cc", "shell/browser/api/electron_api_web_contents_view.h", "shell/browser/api/electron_api_web_frame_main.cc", "shell/browser/api/electron_api_web_frame_main.h", "shell/browser/api/electron_api_web_request.cc", "shell/browser/api/electron_api_web_request.h", "shell/browser/api/electron_api_web_view_manager.cc", "shell/browser/api/frame_subscriber.cc", "shell/browser/api/frame_subscriber.h", "shell/browser/api/gpu_info_enumerator.cc", "shell/browser/api/gpu_info_enumerator.h", "shell/browser/api/gpuinfo_manager.cc", "shell/browser/api/gpuinfo_manager.h", "shell/browser/api/message_port.cc", "shell/browser/api/message_port.h", "shell/browser/api/process_metric.cc", "shell/browser/api/process_metric.h", "shell/browser/api/save_page_handler.cc", "shell/browser/api/save_page_handler.h", "shell/browser/api/ui_event.cc", "shell/browser/api/ui_event.h", "shell/browser/auto_updater.cc", "shell/browser/auto_updater.h", "shell/browser/background_throttling_source.h", "shell/browser/badging/badge_manager.cc", "shell/browser/badging/badge_manager.h", "shell/browser/badging/badge_manager_factory.cc", "shell/browser/badging/badge_manager_factory.h", "shell/browser/bluetooth/electron_bluetooth_delegate.cc", "shell/browser/bluetooth/electron_bluetooth_delegate.h", "shell/browser/browser.cc", "shell/browser/browser.h", "shell/browser/browser_observer.h", "shell/browser/browser_process_impl.cc", "shell/browser/browser_process_impl.h", "shell/browser/child_web_contents_tracker.cc", "shell/browser/child_web_contents_tracker.h", "shell/browser/cookie_change_notifier.cc", "shell/browser/cookie_change_notifier.h", "shell/browser/draggable_region_provider.h", "shell/browser/electron_api_ipc_handler_impl.cc", "shell/browser/electron_api_ipc_handler_impl.h", "shell/browser/electron_autofill_driver.cc", "shell/browser/electron_autofill_driver.h", "shell/browser/electron_autofill_driver_factory.cc", "shell/browser/electron_autofill_driver_factory.h", "shell/browser/electron_browser_client.cc", "shell/browser/electron_browser_client.h", "shell/browser/electron_browser_context.cc", "shell/browser/electron_browser_context.h", "shell/browser/electron_browser_main_parts.cc", "shell/browser/electron_browser_main_parts.h", "shell/browser/electron_download_manager_delegate.cc", "shell/browser/electron_download_manager_delegate.h", "shell/browser/electron_gpu_client.cc", "shell/browser/electron_gpu_client.h", "shell/browser/electron_javascript_dialog_manager.cc", "shell/browser/electron_javascript_dialog_manager.h", "shell/browser/electron_navigation_throttle.cc", "shell/browser/electron_navigation_throttle.h", "shell/browser/electron_permission_manager.cc", "shell/browser/electron_permission_manager.h", "shell/browser/electron_speech_recognition_manager_delegate.cc", "shell/browser/electron_speech_recognition_manager_delegate.h", "shell/browser/electron_web_contents_utility_handler_impl.cc", "shell/browser/electron_web_contents_utility_handler_impl.h", "shell/browser/electron_web_ui_controller_factory.cc", "shell/browser/electron_web_ui_controller_factory.h", "shell/browser/event_emitter_mixin.h", "shell/browser/extended_web_contents_observer.h", "shell/browser/feature_list.cc", "shell/browser/feature_list.h", "shell/browser/file_select_helper.cc", "shell/browser/file_select_helper.h", "shell/browser/file_select_helper_mac.mm", "shell/browser/font_defaults.cc", "shell/browser/font_defaults.h", "shell/browser/hid/electron_hid_delegate.cc", "shell/browser/hid/electron_hid_delegate.h", "shell/browser/hid/hid_chooser_context.cc", "shell/browser/hid/hid_chooser_context.h", "shell/browser/hid/hid_chooser_context_factory.cc", "shell/browser/hid/hid_chooser_context_factory.h", "shell/browser/hid/hid_chooser_controller.cc", "shell/browser/hid/hid_chooser_controller.h", "shell/browser/javascript_environment.cc", "shell/browser/javascript_environment.h", "shell/browser/lib/bluetooth_chooser.cc", "shell/browser/lib/bluetooth_chooser.h", "shell/browser/login_handler.cc", "shell/browser/login_handler.h", "shell/browser/media/media_capture_devices_dispatcher.cc", "shell/browser/media/media_capture_devices_dispatcher.h", "shell/browser/media/media_device_id_salt.cc", "shell/browser/media/media_device_id_salt.h", "shell/browser/microtasks_runner.cc", "shell/browser/microtasks_runner.h", "shell/browser/native_browser_view.cc", "shell/browser/native_browser_view.h", "shell/browser/native_window.cc", "shell/browser/native_window.h", "shell/browser/native_window_features.cc", "shell/browser/native_window_features.h", "shell/browser/native_window_observer.h", "shell/browser/net/asar/asar_file_validator.cc", "shell/browser/net/asar/asar_file_validator.h", "shell/browser/net/asar/asar_url_loader.cc", "shell/browser/net/asar/asar_url_loader.h", "shell/browser/net/asar/asar_url_loader_factory.cc", "shell/browser/net/asar/asar_url_loader_factory.h", "shell/browser/net/cert_verifier_client.cc", "shell/browser/net/cert_verifier_client.h", "shell/browser/net/electron_url_loader_factory.cc", "shell/browser/net/electron_url_loader_factory.h", "shell/browser/net/network_context_service.cc", "shell/browser/net/network_context_service.h", "shell/browser/net/network_context_service_factory.cc", "shell/browser/net/network_context_service_factory.h", "shell/browser/net/node_stream_loader.cc", "shell/browser/net/node_stream_loader.h", "shell/browser/net/proxying_url_loader_factory.cc", "shell/browser/net/proxying_url_loader_factory.h", "shell/browser/net/proxying_websocket.cc", "shell/browser/net/proxying_websocket.h", "shell/browser/net/resolve_host_function.cc", "shell/browser/net/resolve_host_function.h", "shell/browser/net/resolve_proxy_helper.cc", "shell/browser/net/resolve_proxy_helper.h", "shell/browser/net/system_network_context_manager.cc", "shell/browser/net/system_network_context_manager.h", "shell/browser/net/url_pipe_loader.cc", "shell/browser/net/url_pipe_loader.h", "shell/browser/net/web_request_api_interface.h", "shell/browser/network_hints_handler_impl.cc", "shell/browser/network_hints_handler_impl.h", "shell/browser/notifications/notification.cc", "shell/browser/notifications/notification.h", "shell/browser/notifications/notification_delegate.h", "shell/browser/notifications/notification_presenter.cc", "shell/browser/notifications/notification_presenter.h", "shell/browser/notifications/platform_notification_service.cc", "shell/browser/notifications/platform_notification_service.h", "shell/browser/osr/osr_host_display_client.cc", "shell/browser/osr/osr_host_display_client.h", "shell/browser/osr/osr_render_widget_host_view.cc", "shell/browser/osr/osr_render_widget_host_view.h", "shell/browser/osr/osr_video_consumer.cc", "shell/browser/osr/osr_video_consumer.h", "shell/browser/osr/osr_view_proxy.cc", "shell/browser/osr/osr_view_proxy.h", "shell/browser/osr/osr_web_contents_view.cc", "shell/browser/osr/osr_web_contents_view.h", "shell/browser/plugins/plugin_utils.cc", "shell/browser/plugins/plugin_utils.h", "shell/browser/protocol_registry.cc", "shell/browser/protocol_registry.h", "shell/browser/relauncher.cc", "shell/browser/relauncher.h", "shell/browser/serial/electron_serial_delegate.cc", "shell/browser/serial/electron_serial_delegate.h", "shell/browser/serial/serial_chooser_context.cc", "shell/browser/serial/serial_chooser_context.h", "shell/browser/serial/serial_chooser_context_factory.cc", "shell/browser/serial/serial_chooser_context_factory.h", "shell/browser/serial/serial_chooser_controller.cc", "shell/browser/serial/serial_chooser_controller.h", "shell/browser/session_preferences.cc", "shell/browser/session_preferences.h", "shell/browser/special_storage_policy.cc", "shell/browser/special_storage_policy.h", "shell/browser/ui/accelerator_util.cc", "shell/browser/ui/accelerator_util.h", "shell/browser/ui/autofill_popup.cc", "shell/browser/ui/autofill_popup.h", "shell/browser/ui/certificate_trust.h", "shell/browser/ui/devtools_manager_delegate.cc", "shell/browser/ui/devtools_manager_delegate.h", "shell/browser/ui/devtools_ui.cc", "shell/browser/ui/devtools_ui.h", "shell/browser/ui/drag_util.cc", "shell/browser/ui/drag_util.h", "shell/browser/ui/electron_menu_model.cc", "shell/browser/ui/electron_menu_model.h", "shell/browser/ui/file_dialog.h", "shell/browser/ui/inspectable_web_contents.cc", "shell/browser/ui/inspectable_web_contents.h", "shell/browser/ui/inspectable_web_contents_delegate.h", "shell/browser/ui/inspectable_web_contents_view.cc", "shell/browser/ui/inspectable_web_contents_view.h", "shell/browser/ui/inspectable_web_contents_view_delegate.cc", "shell/browser/ui/inspectable_web_contents_view_delegate.h", "shell/browser/ui/message_box.h", "shell/browser/ui/tray_icon.cc", "shell/browser/ui/tray_icon.h", "shell/browser/ui/tray_icon_observer.h", "shell/browser/ui/webui/accessibility_ui.cc", "shell/browser/ui/webui/accessibility_ui.h", "shell/browser/usb/electron_usb_delegate.cc", "shell/browser/usb/electron_usb_delegate.h", "shell/browser/usb/usb_chooser_context.cc", "shell/browser/usb/usb_chooser_context.h", "shell/browser/usb/usb_chooser_context_factory.cc", "shell/browser/usb/usb_chooser_context_factory.h", "shell/browser/usb/usb_chooser_controller.cc", "shell/browser/usb/usb_chooser_controller.h", "shell/browser/web_contents_permission_helper.cc", "shell/browser/web_contents_permission_helper.h", "shell/browser/web_contents_preferences.cc", "shell/browser/web_contents_preferences.h", "shell/browser/web_contents_zoom_controller.cc", "shell/browser/web_contents_zoom_controller.h", "shell/browser/web_contents_zoom_observer.h", "shell/browser/web_view_guest_delegate.cc", "shell/browser/web_view_guest_delegate.h", "shell/browser/web_view_manager.cc", "shell/browser/web_view_manager.h", "shell/browser/webauthn/electron_authenticator_request_delegate.cc", "shell/browser/webauthn/electron_authenticator_request_delegate.h", "shell/browser/window_list.cc", "shell/browser/window_list.h", "shell/browser/window_list_observer.h", "shell/browser/zoom_level_delegate.cc", "shell/browser/zoom_level_delegate.h", "shell/common/api/crashpad_support.cc", "shell/common/api/electron_api_asar.cc", "shell/common/api/electron_api_clipboard.cc", "shell/common/api/electron_api_clipboard.h", "shell/common/api/electron_api_command_line.cc", "shell/common/api/electron_api_environment.cc", "shell/common/api/electron_api_key_weak_map.h", "shell/common/api/electron_api_native_image.cc", "shell/common/api/electron_api_native_image.h", "shell/common/api/electron_api_shell.cc", "shell/common/api/electron_api_testing.cc", "shell/common/api/electron_api_v8_util.cc", "shell/common/api/electron_bindings.cc", "shell/common/api/electron_bindings.h", "shell/common/api/features.cc", "shell/common/api/object_life_monitor.cc", "shell/common/api/object_life_monitor.h", "shell/common/application_info.cc", "shell/common/application_info.h", "shell/common/asar/archive.cc", "shell/common/asar/archive.h", "shell/common/asar/asar_util.cc", "shell/common/asar/asar_util.h", "shell/common/asar/scoped_temporary_file.cc", "shell/common/asar/scoped_temporary_file.h", "shell/common/color_util.cc", "shell/common/color_util.h", "shell/common/crash_keys.cc", "shell/common/crash_keys.h", "shell/common/electron_command_line.cc", "shell/common/electron_command_line.h", "shell/common/electron_constants.cc", "shell/common/electron_constants.h", "shell/common/electron_paths.h", "shell/common/gin_converters/accelerator_converter.cc", "shell/common/gin_converters/accelerator_converter.h", "shell/common/gin_converters/base_converter.h", "shell/common/gin_converters/blink_converter.cc", "shell/common/gin_converters/blink_converter.h", "shell/common/gin_converters/callback_converter.h", "shell/common/gin_converters/content_converter.cc", "shell/common/gin_converters/content_converter.h", "shell/common/gin_converters/file_dialog_converter.cc", "shell/common/gin_converters/file_dialog_converter.h", "shell/common/gin_converters/file_path_converter.h", "shell/common/gin_converters/frame_converter.cc", "shell/common/gin_converters/frame_converter.h", "shell/common/gin_converters/gfx_converter.cc", "shell/common/gin_converters/gfx_converter.h", "shell/common/gin_converters/guid_converter.h", "shell/common/gin_converters/gurl_converter.h", "shell/common/gin_converters/hid_device_info_converter.h", "shell/common/gin_converters/image_converter.cc", "shell/common/gin_converters/image_converter.h", "shell/common/gin_converters/media_converter.cc", "shell/common/gin_converters/media_converter.h", "shell/common/gin_converters/message_box_converter.cc", "shell/common/gin_converters/message_box_converter.h", "shell/common/gin_converters/native_window_converter.h", "shell/common/gin_converters/net_converter.cc", "shell/common/gin_converters/net_converter.h", "shell/common/gin_converters/optional_converter.h", "shell/common/gin_converters/serial_port_info_converter.h", "shell/common/gin_converters/std_converter.h", "shell/common/gin_converters/time_converter.cc", "shell/common/gin_converters/time_converter.h", "shell/common/gin_converters/usb_device_info_converter.h", "shell/common/gin_converters/value_converter.cc", "shell/common/gin_converters/value_converter.h", "shell/common/gin_helper/arguments.cc", "shell/common/gin_helper/arguments.h", "shell/common/gin_helper/callback.cc", "shell/common/gin_helper/callback.h", "shell/common/gin_helper/cleaned_up_at_exit.cc", "shell/common/gin_helper/cleaned_up_at_exit.h", "shell/common/gin_helper/constructible.h", "shell/common/gin_helper/constructor.h", "shell/common/gin_helper/destroyable.cc", "shell/common/gin_helper/destroyable.h", "shell/common/gin_helper/dictionary.h", "shell/common/gin_helper/error_thrower.cc", "shell/common/gin_helper/error_thrower.h", "shell/common/gin_helper/event.cc", "shell/common/gin_helper/event.h", "shell/common/gin_helper/event_emitter.h", "shell/common/gin_helper/event_emitter_caller.cc", "shell/common/gin_helper/event_emitter_caller.h", "shell/common/gin_helper/event_emitter_template.cc", "shell/common/gin_helper/event_emitter_template.h", "shell/common/gin_helper/function_template.cc", "shell/common/gin_helper/function_template.h", "shell/common/gin_helper/function_template_extensions.h", "shell/common/gin_helper/locker.cc", "shell/common/gin_helper/locker.h", "shell/common/gin_helper/microtasks_scope.cc", "shell/common/gin_helper/microtasks_scope.h", "shell/common/gin_helper/object_template_builder.cc", "shell/common/gin_helper/object_template_builder.h", "shell/common/gin_helper/persistent_dictionary.cc", "shell/common/gin_helper/persistent_dictionary.h", "shell/common/gin_helper/pinnable.h", "shell/common/gin_helper/promise.cc", "shell/common/gin_helper/promise.h", "shell/common/gin_helper/trackable_object.cc", "shell/common/gin_helper/trackable_object.h", "shell/common/gin_helper/wrappable.cc", "shell/common/gin_helper/wrappable.h", "shell/common/gin_helper/wrappable_base.h", "shell/common/heap_snapshot.cc", "shell/common/heap_snapshot.h", "shell/common/key_weak_map.h", "shell/common/keyboard_util.cc", "shell/common/keyboard_util.h", "shell/common/language_util.h", "shell/common/logging.cc", "shell/common/logging.h", "shell/common/node_bindings.cc", "shell/common/node_bindings.h", "shell/common/node_includes.h", "shell/common/node_util.cc", "shell/common/node_util.h", "shell/common/options_switches.cc", "shell/common/options_switches.h", "shell/common/platform_util.cc", "shell/common/platform_util.h", "shell/common/platform_util_internal.h", "shell/common/process_util.cc", "shell/common/process_util.h", "shell/common/skia_util.cc", "shell/common/skia_util.h", "shell/common/thread_restrictions.h", "shell/common/v8_value_serializer.cc", "shell/common/v8_value_serializer.h", "shell/common/world_ids.h", "shell/renderer/api/context_bridge/object_cache.cc", "shell/renderer/api/context_bridge/object_cache.h", "shell/renderer/api/electron_api_context_bridge.cc", "shell/renderer/api/electron_api_context_bridge.h", "shell/renderer/api/electron_api_crash_reporter_renderer.cc", "shell/renderer/api/electron_api_ipc_renderer.cc", "shell/renderer/api/electron_api_spell_check_client.cc", "shell/renderer/api/electron_api_spell_check_client.h", "shell/renderer/api/electron_api_web_frame.cc", "shell/renderer/browser_exposed_renderer_interfaces.cc", "shell/renderer/browser_exposed_renderer_interfaces.h", "shell/renderer/content_settings_observer.cc", "shell/renderer/content_settings_observer.h", "shell/renderer/electron_api_service_impl.cc", "shell/renderer/electron_api_service_impl.h", "shell/renderer/electron_autofill_agent.cc", "shell/renderer/electron_autofill_agent.h", "shell/renderer/electron_render_frame_observer.cc", "shell/renderer/electron_render_frame_observer.h", "shell/renderer/electron_renderer_client.cc", "shell/renderer/electron_renderer_client.h", "shell/renderer/electron_sandboxed_renderer_client.cc", "shell/renderer/electron_sandboxed_renderer_client.h", "shell/renderer/renderer_client_base.cc", "shell/renderer/renderer_client_base.h", "shell/renderer/web_worker_observer.cc", "shell/renderer/web_worker_observer.h", "shell/services/node/node_service.cc", "shell/services/node/node_service.h", "shell/services/node/parent_port.cc", "shell/services/node/parent_port.h", "shell/utility/electron_content_utility_client.cc", "shell/utility/electron_content_utility_client.h", ] lib_sources_extensions = [ "shell/browser/extensions/api/extension_action/extension_action_api.cc", "shell/browser/extensions/api/extension_action/extension_action_api.h", "shell/browser/extensions/api/management/electron_management_api_delegate.cc", "shell/browser/extensions/api/management/electron_management_api_delegate.h", "shell/browser/extensions/api/resources_private/resources_private_api.cc", "shell/browser/extensions/api/resources_private/resources_private_api.h", "shell/browser/extensions/api/runtime/electron_runtime_api_delegate.cc", "shell/browser/extensions/api/runtime/electron_runtime_api_delegate.h", "shell/browser/extensions/api/scripting/scripting_api.cc", "shell/browser/extensions/api/scripting/scripting_api.h", "shell/browser/extensions/api/streams_private/streams_private_api.cc", "shell/browser/extensions/api/streams_private/streams_private_api.h", "shell/browser/extensions/api/tabs/tabs_api.cc", "shell/browser/extensions/api/tabs/tabs_api.h", "shell/browser/extensions/electron_browser_context_keyed_service_factories.cc", "shell/browser/extensions/electron_browser_context_keyed_service_factories.h", "shell/browser/extensions/electron_component_extension_resource_manager.cc", "shell/browser/extensions/electron_component_extension_resource_manager.h", "shell/browser/extensions/electron_display_info_provider.cc", "shell/browser/extensions/electron_display_info_provider.h", "shell/browser/extensions/electron_extension_host_delegate.cc", "shell/browser/extensions/electron_extension_host_delegate.h", "shell/browser/extensions/electron_extension_loader.cc", "shell/browser/extensions/electron_extension_loader.h", "shell/browser/extensions/electron_extension_message_filter.cc", "shell/browser/extensions/electron_extension_message_filter.h", "shell/browser/extensions/electron_extension_system_factory.cc", "shell/browser/extensions/electron_extension_system_factory.h", "shell/browser/extensions/electron_extension_system.cc", "shell/browser/extensions/electron_extension_system.h", "shell/browser/extensions/electron_extension_web_contents_observer.cc", "shell/browser/extensions/electron_extension_web_contents_observer.h", "shell/browser/extensions/electron_extensions_api_client.cc", "shell/browser/extensions/electron_extensions_api_client.h", "shell/browser/extensions/electron_extensions_browser_api_provider.cc", "shell/browser/extensions/electron_extensions_browser_api_provider.h", "shell/browser/extensions/electron_extensions_browser_client.cc", "shell/browser/extensions/electron_extensions_browser_client.h", "shell/browser/extensions/electron_kiosk_delegate.cc", "shell/browser/extensions/electron_kiosk_delegate.h", "shell/browser/extensions/electron_messaging_delegate.cc", "shell/browser/extensions/electron_messaging_delegate.h", "shell/browser/extensions/electron_navigation_ui_data.cc", "shell/browser/extensions/electron_navigation_ui_data.h", "shell/browser/extensions/electron_process_manager_delegate.cc", "shell/browser/extensions/electron_process_manager_delegate.h", "shell/common/extensions/electron_extensions_api_provider.cc", "shell/common/extensions/electron_extensions_api_provider.h", "shell/common/extensions/electron_extensions_client.cc", "shell/common/extensions/electron_extensions_client.h", "shell/common/gin_converters/extension_converter.cc", "shell/common/gin_converters/extension_converter.h", "shell/renderer/extensions/electron_extensions_dispatcher_delegate.cc", "shell/renderer/extensions/electron_extensions_dispatcher_delegate.h", "shell/renderer/extensions/electron_extensions_renderer_client.cc", "shell/renderer/extensions/electron_extensions_renderer_client.h", ] framework_sources = [ "shell/app/electron_library_main.h", "shell/app/electron_library_main.mm", ] login_helper_sources = [ "shell/app/electron_login_helper.mm" ] }
closed
electron/electron
https://github.com/electron/electron
40,439
Convert legacy IPC calls in extensions code to use mojo
https://chromium-review.googlesource.com/c/chromium/src/+/4995136 turned on the build flag to use the new mojo IPC pipe for messaging in extensions. In #40418 we turned this off because we have not converted our extensions code to use mojo. It appears that in chromium the follow CLs were landed to use mojo in extensions: - 4947890: [extensions] Convert Extension Messaging APIs over to mojo | https://chromium-review.googlesource.com/c/chromium/src/+/4947890 - 4950041: [extensions] Port Event Acks to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4950041 - 4902564: [extensions] Move WakeEventPage to mojom::RendererHost | https://chromium-review.googlesource.com/c/chromium/src/+/4902564 - 4956841: [extensions] Port GetMessageBundle over to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4956841 Once these changes have landed, the following flag override in build/args/all.gn should be removed: `enable_extensions_legacy_ipc = true`
https://github.com/electron/electron/issues/40439
https://github.com/electron/electron/pull/40511
088affd4a4311e03b8ed400cdf5d82f1db2125a4
371bca69b69351dc47d4b4dcfdf9a626f43b3b51
2023-11-02T18:50:40Z
c++
2023-11-15T14:30:47Z
shell/browser/electron_browser_client.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_client.h" #if BUILDFLAG(IS_WIN) #include <shlobj.h> #endif #include <memory> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/debug/crash_logging.h" #include "base/environment.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/lazy_instance.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/stl_util.h" #include "base/strings/escape.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version.h" #include "components/embedder_support/user_agent_utils.h" #include "components/net_log/chrome_net_log.h" #include "components/network_hints/common/network_hints.mojom.h" #include "content/browser/keyboard_lock/keyboard_lock_service_impl.h" // nogncheck #include "content/browser/site_instance_impl.h" // nogncheck #include "content/public/browser/browser_main_runner.h" #include "content/public/browser/browser_ppapi_host.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/client_certificate_delegate.h" #include "content/public/browser/login_delegate.h" #include "content/public/browser/overlay_window.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/service_worker_version_base_info.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/tts_controller.h" #include "content/public/browser/tts_platform.h" #include "content/public/browser/url_loader_request_interceptor.h" #include "content/public/browser/weak_document_ptr.h" #include "content/public/common/content_descriptors.h" #include "content/public/common/content_paths.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "crypto/crypto_buildflags.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "electron/shell/common/api/api.mojom.h" #include "extensions/browser/extension_navigation_ui_data.h" #include "mojo/public/cpp/bindings/binder_map.h" #include "net/ssl/ssl_cert_request_info.h" #include "net/ssl/ssl_private_key.h" #include "ppapi/buildflags/buildflags.h" #include "ppapi/host/ppapi_host.h" #include "printing/buildflags/buildflags.h" #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "services/device/public/cpp/geolocation/location_provider.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/is_potentially_trustworthy.h" #include "services/network/public/cpp/network_switches.h" #include "services/network/public/cpp/resource_request_body.h" #include "services/network/public/cpp/self_deleting_url_loader_factory.h" #include "shell/app/electron_crash_reporter_client.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/api/electron_api_crash_reporter.h" #include "shell/browser/api/electron_api_protocol.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/api/electron_api_web_request.h" #include "shell/browser/badging/badge_manager.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_api_ipc_handler_impl.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/electron_speech_recognition_manager_delegate.h" #include "shell/browser/electron_web_contents_utility_handler_impl.h" #include "shell/browser/font_defaults.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/native_window.h" #include "shell/browser/net/network_context_service.h" #include "shell/browser/net/network_context_service_factory.h" #include "shell/browser/net/proxying_url_loader_factory.h" #include "shell/browser/net/proxying_websocket.h" #include "shell/browser/net/system_network_context_manager.h" #include "shell/browser/network_hints_handler_impl.h" #include "shell/browser/notifications/notification_presenter.h" #include "shell/browser/notifications/platform_notification_service.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/serial/electron_serial_delegate.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/webauthn/electron_authenticator_request_delegate.h" #include "shell/browser/window_list.h" #include "shell/common/api/api.mojom.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/logging.h" #include "shell/common/options_switches.h" #include "shell/common/platform_util.h" #include "shell/common/thread_restrictions.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" #include "third_party/blink/public/common/loader/url_loader_throttle.h" #include "third_party/blink/public/common/renderer_preferences/renderer_preferences.h" #include "third_party/blink/public/common/tokens/tokens.h" #include "third_party/blink/public/common/web_preferences/web_preferences.h" #include "third_party/blink/public/mojom/badging/badging.mojom.h" #include "ui/base/resource/resource_bundle.h" #include "ui/native_theme/native_theme.h" #include "v8/include/v8.h" #if BUILDFLAG(USE_NSS_CERTS) #include "net/ssl/client_cert_store_nss.h" #elif BUILDFLAG(IS_WIN) #include "net/ssl/client_cert_store_win.h" #elif BUILDFLAG(IS_MAC) #include "net/ssl/client_cert_store_mac.h" #elif defined(USE_OPENSSL) #include "net/ssl/client_cert_store.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spell_check_host_chrome_impl.h" // nogncheck #include "components/spellcheck/common/spellcheck.mojom.h" // nogncheck #endif #if BUILDFLAG(OVERRIDE_LOCATION_PROVIDER) #include "shell/browser/fake_location_provider.h" #endif // BUILDFLAG(OVERRIDE_LOCATION_PROVIDER) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "base/functional/bind.h" #include "chrome/common/webui_url_constants.h" #include "components/guest_view/common/guest_view.mojom.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/file_url_loader.h" #include "content/public/browser/web_ui_url_loader_factory.h" #include "extensions/browser/api/messaging/messaging_api_message_filter.h" #include "extensions/browser/api/mime_handler_private/mime_handler_private.h" #include "extensions/browser/api/web_request/web_request_api.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_message_filter.h" #include "extensions/browser/extension_navigation_throttle.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_protocols.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/guest_view/extensions_guest_view.h" #include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h" #include "extensions/browser/process_manager.h" #include "extensions/browser/process_map.h" #include "extensions/browser/renderer_startup_helper.h" #include "extensions/browser/service_worker/service_worker_host.h" #include "extensions/browser/url_loader_factory_manager.h" #include "extensions/common/api/mime_handler.mojom.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/mojom/event_router.mojom.h" #include "extensions/common/mojom/guest_view.mojom.h" #include "extensions/common/mojom/renderer_host.mojom.h" #include "extensions/common/switches.h" #include "shell/browser/extensions/electron_extension_message_filter.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "chrome/browser/plugins/plugin_response_interceptor_url_loader_throttle.h" // nogncheck #include "shell/browser/plugins/plugin_utils.h" #endif #if BUILDFLAG(IS_MAC) #include "content/browser/mac_helpers.h" #include "content/public/browser/child_process_host.h" #endif #if BUILDFLAG(IS_LINUX) #include "components/crash/core/app/crash_switches.h" // nogncheck #include "components/crash/core/app/crashpad.h" // nogncheck #endif #if BUILDFLAG(IS_WIN) #include "chrome/browser/ui/views/overlay/video_overlay_window_views.h" #include "shell/browser/browser.h" #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/base/win/shell.h" #include "ui/views/widget/widget.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "shell/browser/printing/print_view_manager_electron.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "chrome/browser/pdf/chrome_pdf_stream_delegate.h" #include "chrome/browser/plugins/pdf_iframe_navigation_throttle.h" // nogncheck #include "components/pdf/browser/pdf_document_helper.h" // nogncheck #include "components/pdf/browser/pdf_navigation_throttle.h" #include "components/pdf/browser/pdf_url_loader_request_interceptor.h" #include "components/pdf/common/internal_plugin_helpers.h" #include "shell/browser/electron_pdf_document_helper_client.h" #endif using content::BrowserThread; namespace electron { namespace { ElectronBrowserClient* g_browser_client = nullptr; base::LazyInstance<std::string>::DestructorAtExit g_io_thread_application_locale = LAZY_INSTANCE_INITIALIZER; base::NoDestructor<std::string> g_application_locale; void SetApplicationLocaleOnIOThread(const std::string& locale) { DCHECK_CURRENTLY_ON(BrowserThread::IO); g_io_thread_application_locale.Get() = locale; } void BindNetworkHintsHandler( content::RenderFrameHost* frame_host, mojo::PendingReceiver<network_hints::mojom::NetworkHintsHandler> receiver) { NetworkHintsHandlerImpl::Create(frame_host, std::move(receiver)); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // Used by the GetPrivilegeRequiredByUrl() and GetProcessPrivilege() functions // below. Extension, and isolated apps require different privileges to be // granted to their RenderProcessHosts. This classification allows us to make // sure URLs are served by hosts with the right set of privileges. enum class RenderProcessHostPrivilege { kNormal, kHosted, kIsolated, kExtension, }; // Copied from chrome/browser/extensions/extension_util.cc. bool AllowFileAccess(const std::string& extension_id, content::BrowserContext* context) { return base::CommandLine::ForCurrentProcess()->HasSwitch( extensions::switches::kDisableExtensionsFileAccessCheck) || extensions::ExtensionPrefs::Get(context)->AllowFileAccess( extension_id); } RenderProcessHostPrivilege GetPrivilegeRequiredByUrl( const GURL& url, extensions::ExtensionRegistry* registry) { // Default to a normal renderer cause it is lower privileged. This should only // occur if the URL on a site instance is either malformed, or uninitialized. // If it is malformed, then there is no need for better privileges anyways. // If it is uninitialized, but eventually settles on being an a scheme other // than normal webrenderer, the navigation logic will correct us out of band // anyways. if (!url.is_valid()) return RenderProcessHostPrivilege::kNormal; if (!url.SchemeIs(extensions::kExtensionScheme)) return RenderProcessHostPrivilege::kNormal; return RenderProcessHostPrivilege::kExtension; } RenderProcessHostPrivilege GetProcessPrivilege( content::RenderProcessHost* process_host, extensions::ProcessMap* process_map, extensions::ExtensionRegistry* registry) { std::set<std::string> extension_ids = process_map->GetExtensionsInProcess(process_host->GetID()); if (extension_ids.empty()) return RenderProcessHostPrivilege::kNormal; return RenderProcessHostPrivilege::kExtension; } const extensions::Extension* GetEnabledExtensionFromEffectiveURL( content::BrowserContext* context, const GURL& effective_url) { if (!effective_url.SchemeIs(extensions::kExtensionScheme)) return nullptr; extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(context); if (!registry) return nullptr; return registry->enabled_extensions().GetByID(effective_url.host()); } #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(IS_LINUX) int GetCrashSignalFD(const base::CommandLine& command_line) { int fd; return crash_reporter::GetHandlerSocket(&fd, nullptr) ? fd : -1; } #endif // BUILDFLAG(IS_LINUX) void MaybeAppendSecureOriginsAllowlistSwitch(base::CommandLine* cmdline) { // |allowlist| combines pref/policy + cmdline switch in the browser process. // For renderer and utility (e.g. NetworkService) processes the switch is the // only available source, so below the combined (pref/policy + cmdline) // allowlist of secure origins is injected into |cmdline| for these other // processes. std::vector<std::string> allowlist = network::SecureOriginAllowlist::GetInstance().GetCurrentAllowlist(); if (!allowlist.empty()) { cmdline->AppendSwitchASCII( network::switches::kUnsafelyTreatInsecureOriginAsSecure, base::JoinString(allowlist, ",")); } } } // namespace // static ElectronBrowserClient* ElectronBrowserClient::Get() { return g_browser_client; } // static void ElectronBrowserClient::SetApplicationLocale(const std::string& locale) { if (!BrowserThread::IsThreadInitialized(BrowserThread::IO) || !content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&SetApplicationLocaleOnIOThread, locale))) { g_io_thread_application_locale.Get() = locale; } *g_application_locale = locale; } ElectronBrowserClient::ElectronBrowserClient() { DCHECK(!g_browser_client); g_browser_client = this; } ElectronBrowserClient::~ElectronBrowserClient() { DCHECK(g_browser_client); g_browser_client = nullptr; } content::WebContents* ElectronBrowserClient::GetWebContentsFromProcessID( int process_id) { // If the process is a pending process, we should use the web contents // for the frame host passed into RegisterPendingProcess. const auto iter = pending_processes_.find(process_id); if (iter != std::end(pending_processes_)) return iter->second; // Certain render process will be created with no associated render view, // for example: ServiceWorker. return WebContentsPreferences::GetWebContentsFromProcessID(process_id); } content::SiteInstance* ElectronBrowserClient::GetSiteInstanceFromAffinity( content::BrowserContext* browser_context, const GURL& url, content::RenderFrameHost* rfh) const { return nullptr; } bool ElectronBrowserClient::IsRendererSubFrame(int process_id) const { return base::Contains(renderer_is_subframe_, process_id); } void ElectronBrowserClient::RenderProcessWillLaunch( content::RenderProcessHost* host) { // When a render process is crashed, it might be reused. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) int process_id = host->GetID(); auto* browser_context = host->GetBrowserContext(); host->AddFilter( new extensions::ExtensionMessageFilter(process_id, browser_context)); host->AddFilter( new ElectronExtensionMessageFilter(process_id, browser_context)); host->AddFilter( new extensions::MessagingAPIMessageFilter(process_id, browser_context)); #endif // Remove in case the host is reused after a crash, otherwise noop. host->RemoveObserver(this); // ensure the ProcessPreferences is removed later host->AddObserver(this); } content::SpeechRecognitionManagerDelegate* ElectronBrowserClient::CreateSpeechRecognitionManagerDelegate() { return new ElectronSpeechRecognitionManagerDelegate; } content::TtsPlatform* ElectronBrowserClient::GetTtsPlatform() { return nullptr; } void ElectronBrowserClient::OverrideWebkitPrefs( content::WebContents* web_contents, blink::web_pref::WebPreferences* prefs) { prefs->javascript_enabled = true; prefs->web_security_enabled = true; prefs->plugins_enabled = true; prefs->dom_paste_enabled = true; prefs->allow_scripts_to_close_windows = true; prefs->javascript_can_access_clipboard = true; prefs->local_storage_enabled = true; prefs->databases_enabled = true; prefs->allow_universal_access_from_file_urls = electron::fuses::IsGrantFileProtocolExtraPrivilegesEnabled(); prefs->allow_file_access_from_file_urls = electron::fuses::IsGrantFileProtocolExtraPrivilegesEnabled(); prefs->webgl1_enabled = true; prefs->webgl2_enabled = true; prefs->allow_running_insecure_content = false; prefs->default_minimum_page_scale_factor = 1.f; prefs->default_maximum_page_scale_factor = 1.f; blink::RendererPreferences* renderer_prefs = web_contents->GetMutableRendererPrefs(); renderer_prefs->can_accept_load_drops = false; ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForNativeUi(); prefs->preferred_color_scheme = native_theme->ShouldUseDarkColors() ? blink::mojom::PreferredColorScheme::kDark : blink::mojom::PreferredColorScheme::kLight; SetFontDefaults(prefs); // Custom preferences of guest page. auto* web_preferences = WebContentsPreferences::From(web_contents); if (web_preferences) { web_preferences->OverrideWebkitPrefs(prefs, renderer_prefs); } } void ElectronBrowserClient::RegisterPendingSiteInstance( content::RenderFrameHost* rfh, content::SiteInstance* pending_site_instance) { // Remember the original web contents for the pending renderer process. auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); auto* pending_process = pending_site_instance->GetProcess(); pending_processes_[pending_process->GetID()] = web_contents; if (rfh->GetParent()) renderer_is_subframe_.insert(pending_process->GetID()); else renderer_is_subframe_.erase(pending_process->GetID()); } void ElectronBrowserClient::AppendExtraCommandLineSwitches( base::CommandLine* command_line, int process_id) { // Make sure we're about to launch a known executable { ScopedAllowBlockingForElectron allow_blocking; base::FilePath child_path; base::FilePath program = base::MakeAbsoluteFilePath(command_line->GetProgram()); #if BUILDFLAG(IS_MAC) auto renderer_child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_RENDERER); auto gpu_child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_GPU); auto plugin_child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_PLUGIN); if (program != renderer_child_path && program != gpu_child_path && program != plugin_child_path) { child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_NORMAL); CHECK_EQ(program, child_path) << "Aborted from launching unexpected helper executable"; } #else if (!base::PathService::Get(content::CHILD_PROCESS_EXE, &child_path)) { CHECK(false) << "Unable to get child process binary name."; } SCOPED_CRASH_KEY_STRING256("ChildProcess", "child_process_exe", child_path.AsUTF8Unsafe()); SCOPED_CRASH_KEY_STRING256("ChildProcess", "program", program.AsUTF8Unsafe()); CHECK_EQ(program, child_path); #endif } std::string process_type = command_line->GetSwitchValueASCII(::switches::kProcessType); #if BUILDFLAG(IS_LINUX) pid_t pid; if (crash_reporter::GetHandlerSocket(nullptr, &pid)) { command_line->AppendSwitchASCII( crash_reporter::switches::kCrashpadHandlerPid, base::NumberToString(pid)); } // Zygote Process gets booted before any JS runs, accessing GetClientId // will end up touching DIR_USER_DATA path provider and this will // configure default value because app.name from browser_init has // not run yet. if (process_type != ::switches::kZygoteProcess) { std::string switch_value = api::crash_reporter::GetClientId() + ",no_channel"; command_line->AppendSwitchASCII(::switches::kEnableCrashReporter, switch_value); } #endif // The zygote process is booted before JS runs, so DIR_USER_DATA isn't usable // at that time. It doesn't need --user-data-dir to be correct anyway, since // the zygote itself doesn't access anything in that directory. if (process_type != ::switches::kZygoteProcess) { base::FilePath user_data_dir; if (base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) command_line->AppendSwitchPath(::switches::kUserDataDir, user_data_dir); } if (process_type == ::switches::kUtilityProcess || process_type == ::switches::kRendererProcess) { // Copy following switches to child process. static const char* const kCommonSwitchNames[] = { switches::kStandardSchemes, switches::kEnableSandbox, switches::kSecureSchemes, switches::kBypassCSPSchemes, switches::kCORSSchemes, switches::kFetchSchemes, switches::kServiceWorkerSchemes, switches::kStreamingSchemes}; command_line->CopySwitchesFrom(*base::CommandLine::ForCurrentProcess(), kCommonSwitchNames); if (process_type == ::switches::kUtilityProcess || content::RenderProcessHost::FromID(process_id)) { MaybeAppendSecureOriginsAllowlistSwitch(command_line); } } if (process_type == ::switches::kRendererProcess) { #if BUILDFLAG(IS_WIN) // Append --app-user-model-id. PWSTR current_app_id; if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&current_app_id))) { command_line->AppendSwitchNative(switches::kAppUserModelId, current_app_id); CoTaskMemFree(current_app_id); } #endif if (delegate_) { auto app_path = static_cast<api::App*>(delegate_)->GetAppPath(); command_line->AppendSwitchPath(switches::kAppPath, app_path); } auto env = base::Environment::Create(); if (env->HasVar("ELECTRON_PROFILE_INIT_SCRIPTS")) { command_line->AppendSwitch("profile-electron-init"); } // Extension background pages don't have WebContentsPreferences, but they // support WebSQL by default. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) content::RenderProcessHost* process = content::RenderProcessHost::FromID(process_id); if (extensions::ProcessMap::Get(process->GetBrowserContext()) ->Contains(process_id)) command_line->AppendSwitch(switches::kEnableWebSQL); #endif content::WebContents* web_contents = GetWebContentsFromProcessID(process_id); if (web_contents) { auto* web_preferences = WebContentsPreferences::From(web_contents); if (web_preferences) web_preferences->AppendCommandLineSwitches( command_line, IsRendererSubFrame(process_id)); } } } void ElectronBrowserClient::DidCreatePpapiPlugin( content::BrowserPpapiHost* host) {} // attempt to get api key from env std::string ElectronBrowserClient::GetGeolocationApiKey() { auto env = base::Environment::Create(); std::string api_key; env->GetVar("GOOGLE_API_KEY", &api_key); return api_key; } content::GeneratedCodeCacheSettings ElectronBrowserClient::GetGeneratedCodeCacheSettings( content::BrowserContext* context) { // TODO(deepak1556): Use platform cache directory. base::FilePath cache_path = context->GetPath(); // If we pass 0 for size, disk_cache will pick a default size using the // heuristics based on available disk size. These are implemented in // disk_cache::PreferredCacheSize in net/disk_cache/cache_util.cc. return content::GeneratedCodeCacheSettings(true, 0, cache_path); } void ElectronBrowserClient::AllowCertificateError( content::WebContents* web_contents, int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, bool is_main_frame_request, bool strict_enforcement, base::OnceCallback<void(content::CertificateRequestResultType)> callback) { if (delegate_) { delegate_->AllowCertificateError(web_contents, cert_error, ssl_info, request_url, is_main_frame_request, strict_enforcement, std::move(callback)); } } base::OnceClosure ElectronBrowserClient::SelectClientCertificate( content::BrowserContext* browser_context, content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, net::ClientCertIdentityList client_certs, std::unique_ptr<content::ClientCertificateDelegate> delegate) { if (client_certs.empty()) { delegate->ContinueWithCertificate(nullptr, nullptr); } else if (delegate_) { delegate_->SelectClientCertificate( browser_context, web_contents, cert_request_info, std::move(client_certs), std::move(delegate)); } return base::OnceClosure(); } bool ElectronBrowserClient::CanCreateWindow( content::RenderFrameHost* opener, const GURL& opener_url, const GURL& opener_top_level_frame_url, const url::Origin& source_origin, content::mojom::WindowContainerType container_type, const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& features, const std::string& raw_features, const scoped_refptr<network::ResourceRequestBody>& body, bool user_gesture, bool opener_suppressed, bool* no_javascript_access) { DCHECK_CURRENTLY_ON(BrowserThread::UI); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(opener); WebContentsPreferences* prefs = WebContentsPreferences::From(web_contents); if (prefs) { if (prefs->ShouldDisablePopups()) { // <webview> without allowpopups attribute should return // null from window.open calls return false; } else { *no_javascript_access = false; return true; } } if (delegate_) { return delegate_->CanCreateWindow( opener, opener_url, opener_top_level_frame_url, source_origin, container_type, target_url, referrer, frame_name, disposition, features, raw_features, body, user_gesture, opener_suppressed, no_javascript_access); } return false; } std::unique_ptr<content::VideoOverlayWindow> ElectronBrowserClient::CreateWindowForVideoPictureInPicture( content::VideoPictureInPictureWindowController* controller) { auto overlay_window = content::VideoOverlayWindow::Create(controller); #if BUILDFLAG(IS_WIN) std::wstring app_user_model_id = Browser::Get()->GetAppUserModelID(); if (!app_user_model_id.empty()) { auto* overlay_window_view = static_cast<VideoOverlayWindowViews*>(overlay_window.get()); ui::win::SetAppIdForWindow(app_user_model_id, overlay_window_view->GetNativeWindow() ->GetHost() ->GetAcceleratedWidget()); } #endif return overlay_window; } void ElectronBrowserClient::GetAdditionalAllowedSchemesForFileSystem( std::vector<std::string>* additional_schemes) { auto schemes_list = api::GetStandardSchemes(); if (!schemes_list.empty()) additional_schemes->insert(additional_schemes->end(), schemes_list.begin(), schemes_list.end()); additional_schemes->push_back(content::kChromeDevToolsScheme); additional_schemes->push_back(content::kChromeUIScheme); } void ElectronBrowserClient::GetAdditionalWebUISchemes( std::vector<std::string>* additional_schemes) { additional_schemes->push_back(content::kChromeDevToolsScheme); } void ElectronBrowserClient::SiteInstanceGotProcess( content::SiteInstance* site_instance) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto* browser_context = static_cast<ElectronBrowserContext*>(site_instance->GetBrowserContext()); if (!browser_context->IsOffTheRecord()) { extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); const extensions::Extension* extension = registry->enabled_extensions().GetExtensionOrAppByURL( site_instance->GetSiteURL()); if (!extension) return; extensions::ProcessMap::Get(browser_context) ->Insert(extension->id(), site_instance->GetProcess()->GetID()); } #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) } bool ElectronBrowserClient::IsSuitableHost( content::RenderProcessHost* process_host, const GURL& site_url) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto* browser_context = process_host->GetBrowserContext(); extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); extensions::ProcessMap* process_map = extensions::ProcessMap::Get(browser_context); // Otherwise, just make sure the process privilege matches the privilege // required by the site. RenderProcessHostPrivilege privilege_required = GetPrivilegeRequiredByUrl(site_url, registry); return GetProcessPrivilege(process_host, process_map, registry) == privilege_required; #else return content::ContentBrowserClient::IsSuitableHost(process_host, site_url); #endif } bool ElectronBrowserClient::ShouldUseProcessPerSite( content::BrowserContext* browser_context, const GURL& effective_url) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) const extensions::Extension* extension = GetEnabledExtensionFromEffectiveURL(browser_context, effective_url); return extension != nullptr; #else return content::ContentBrowserClient::ShouldUseProcessPerSite(browser_context, effective_url); #endif } void ElectronBrowserClient::GetMediaDeviceIDSalt( content::RenderFrameHost* rfh, const net::SiteForCookies& site_for_cookies, const blink::StorageKey& storage_key, base::OnceCallback<void(bool, const std::string&)> callback) { constexpr bool persistent_media_device_id_allowed = true; std::string persistent_media_device_id_salt = static_cast<ElectronBrowserContext*>(rfh->GetBrowserContext()) ->GetMediaDeviceIDSalt(); std::move(callback).Run(persistent_media_device_id_allowed, persistent_media_device_id_salt); } base::FilePath ElectronBrowserClient::GetLoggingFileName( const base::CommandLine& cmd_line) { return logging::GetLogFileName(cmd_line); } std::unique_ptr<net::ClientCertStore> ElectronBrowserClient::CreateClientCertStore( content::BrowserContext* browser_context) { #if BUILDFLAG(USE_NSS_CERTS) return std::make_unique<net::ClientCertStoreNSS>( net::ClientCertStoreNSS::PasswordDelegateFactory()); #elif BUILDFLAG(IS_WIN) return std::make_unique<net::ClientCertStoreWin>(); #elif BUILDFLAG(IS_MAC) return std::make_unique<net::ClientCertStoreMac>(); #elif defined(USE_OPENSSL) return std::unique_ptr<net::ClientCertStore>(); #endif } std::unique_ptr<device::LocationProvider> ElectronBrowserClient::OverrideSystemLocationProvider() { #if BUILDFLAG(OVERRIDE_LOCATION_PROVIDER) return std::make_unique<FakeLocationProvider>(); #else return nullptr; #endif } void ElectronBrowserClient::ConfigureNetworkContextParams( content::BrowserContext* browser_context, bool in_memory, const base::FilePath& relative_partition_path, network::mojom::NetworkContextParams* network_context_params, cert_verifier::mojom::CertVerifierCreationParams* cert_verifier_creation_params) { DCHECK(browser_context); return NetworkContextServiceFactory::GetForContext(browser_context) ->ConfigureNetworkContextParams(network_context_params, cert_verifier_creation_params); } network::mojom::NetworkContext* ElectronBrowserClient::GetSystemNetworkContext() { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(g_browser_process->system_network_context_manager()); return g_browser_process->system_network_context_manager()->GetContext(); } std::unique_ptr<content::BrowserMainParts> ElectronBrowserClient::CreateBrowserMainParts(bool /* is_integration_test */) { auto browser_main_parts = std::make_unique<ElectronBrowserMainParts>(); #if BUILDFLAG(IS_MAC) browser_main_parts_ = browser_main_parts.get(); #endif return browser_main_parts; } void ElectronBrowserClient::WebNotificationAllowed( content::RenderFrameHost* rfh, base::OnceCallback<void(bool, bool)> callback) { content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(rfh); if (!web_contents) { std::move(callback).Run(false, false); return; } auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); if (!permission_helper) { std::move(callback).Run(false, false); return; } permission_helper->RequestWebNotificationPermission( rfh, base::BindOnce(std::move(callback), web_contents->IsAudioMuted())); } void ElectronBrowserClient::RenderProcessHostDestroyed( content::RenderProcessHost* host) { int process_id = host->GetID(); pending_processes_.erase(process_id); renderer_is_subframe_.erase(process_id); host->RemoveObserver(this); } void ElectronBrowserClient::RenderProcessReady( content::RenderProcessHost* host) { if (delegate_) { static_cast<api::App*>(delegate_)->RenderProcessReady(host); } } void ElectronBrowserClient::RenderProcessExited( content::RenderProcessHost* host, const content::ChildProcessTerminationInfo& info) { if (delegate_) { static_cast<api::App*>(delegate_)->RenderProcessExited(host); } } void OnOpenExternal(const GURL& escaped_url, bool allowed) { if (allowed) { platform_util::OpenExternal( escaped_url, platform_util::OpenExternalOptions(), base::DoNothing()); } } void HandleExternalProtocolInUI( const GURL& url, content::WeakDocumentPtr document_ptr, content::WebContents::OnceGetter web_contents_getter, bool has_user_gesture) { content::WebContents* web_contents = std::move(web_contents_getter).Run(); if (!web_contents) return; auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); if (!permission_helper) return; content::RenderFrameHost* rfh = document_ptr.AsRenderFrameHostIfValid(); if (!rfh) { // If the render frame host is not valid it means it was a top level // navigation and the frame has already been disposed of. In this case we // take the current main frame and declare it responsible for the // transition. rfh = web_contents->GetPrimaryMainFrame(); } GURL escaped_url(base::EscapeExternalHandlerValue(url.spec())); auto callback = base::BindOnce(&OnOpenExternal, escaped_url); permission_helper->RequestOpenExternalPermission(rfh, std::move(callback), has_user_gesture, url); } bool ElectronBrowserClient::HandleExternalProtocol( const GURL& url, content::WebContents::Getter web_contents_getter, int frame_tree_node_id, content::NavigationUIData* navigation_data, bool is_primary_main_frame, bool is_in_fenced_frame_tree, network::mojom::WebSandboxFlags sandbox_flags, ui::PageTransition page_transition, bool has_user_gesture, const absl::optional<url::Origin>& initiating_origin, content::RenderFrameHost* initiator_document, mojo::PendingRemote<network::mojom::URLLoaderFactory>* out_factory) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&HandleExternalProtocolInUI, url, initiator_document ? initiator_document->GetWeakDocumentPtr() : content::WeakDocumentPtr(), std::move(web_contents_getter), has_user_gesture)); return true; } std::vector<std::unique_ptr<content::NavigationThrottle>> ElectronBrowserClient::CreateThrottlesForNavigation( content::NavigationHandle* handle) { std::vector<std::unique_ptr<content::NavigationThrottle>> throttles; throttles.push_back(std::make_unique<ElectronNavigationThrottle>(handle)); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) throttles.push_back( std::make_unique<extensions::ExtensionNavigationThrottle>(handle)); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) std::unique_ptr<content::NavigationThrottle> pdf_iframe_throttle = PDFIFrameNavigationThrottle::MaybeCreateThrottleFor(handle); if (pdf_iframe_throttle) throttles.push_back(std::move(pdf_iframe_throttle)); std::unique_ptr<content::NavigationThrottle> pdf_throttle = pdf::PdfNavigationThrottle::MaybeCreateThrottleFor( handle, std::make_unique<ChromePdfStreamDelegate>()); if (pdf_throttle) throttles.push_back(std::move(pdf_throttle)); #endif return throttles; } content::MediaObserver* ElectronBrowserClient::GetMediaObserver() { return MediaCaptureDevicesDispatcher::GetInstance(); } std::unique_ptr<content::DevToolsManagerDelegate> ElectronBrowserClient::CreateDevToolsManagerDelegate() { return std::make_unique<DevToolsManagerDelegate>(); } NotificationPresenter* ElectronBrowserClient::GetNotificationPresenter() { if (!notification_presenter_) { notification_presenter_.reset(NotificationPresenter::Create()); } return notification_presenter_.get(); } content::PlatformNotificationService* ElectronBrowserClient::GetPlatformNotificationService() { if (!notification_service_) { notification_service_ = std::make_unique<PlatformNotificationService>(this); } return notification_service_.get(); } base::FilePath ElectronBrowserClient::GetDefaultDownloadDirectory() { base::FilePath download_path; if (base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_path)) return download_path; return base::FilePath(); } scoped_refptr<network::SharedURLLoaderFactory> ElectronBrowserClient::GetSystemSharedURLLoaderFactory() { if (!g_browser_process) return nullptr; return g_browser_process->shared_url_loader_factory(); } void ElectronBrowserClient::OnNetworkServiceCreated( network::mojom::NetworkService* network_service) { if (!g_browser_process) return; g_browser_process->system_network_context_manager()->OnNetworkServiceCreated( network_service); } std::vector<base::FilePath> ElectronBrowserClient::GetNetworkContextsParentDirectory() { base::FilePath session_data; base::PathService::Get(DIR_SESSION_DATA, &session_data); DCHECK(!session_data.empty()); return {session_data}; } std::string ElectronBrowserClient::GetProduct() { return "Chrome/" CHROME_VERSION_STRING; } std::string ElectronBrowserClient::GetUserAgent() { if (user_agent_override_.empty()) return GetApplicationUserAgent(); return user_agent_override_; } void ElectronBrowserClient::SetUserAgent(const std::string& user_agent) { user_agent_override_ = user_agent; } blink::UserAgentMetadata ElectronBrowserClient::GetUserAgentMetadata() { return embedder_support::GetUserAgentMetadata(); } void ElectronBrowserClient::RegisterNonNetworkNavigationURLLoaderFactories( int frame_tree_node_id, ukm::SourceIdObj ukm_source_id, NonNetworkURLLoaderFactoryMap* factories) { content::WebContents* web_contents = content::WebContents::FromFrameTreeNodeId(frame_tree_node_id); content::BrowserContext* context = web_contents->GetBrowserContext(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) factories->emplace( extensions::kExtensionScheme, extensions::CreateExtensionNavigationURLLoaderFactory( context, ukm_source_id, false /* we don't support extensions::WebViewGuest */)); #endif // Always allow navigating to file:// URLs. auto* protocol_registry = ProtocolRegistry::FromBrowserContext(context); protocol_registry->RegisterURLLoaderFactories(factories, true /* allow_file_access */); } void ElectronBrowserClient:: RegisterNonNetworkWorkerMainResourceURLLoaderFactories( content::BrowserContext* browser_context, NonNetworkURLLoaderFactoryMap* factories) { auto* protocol_registry = ProtocolRegistry::FromBrowserContext(browser_context); // Workers are not allowed to request file:// URLs, there is no particular // reason for it, and we could consider supporting it in future. protocol_registry->RegisterURLLoaderFactories(factories, false /* allow_file_access */); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) namespace { // The FileURLLoaderFactory provided to the extension background pages. // Checks with the ChildProcessSecurityPolicy to validate the file access. class FileURLLoaderFactory : public network::SelfDeletingURLLoaderFactory { public: static mojo::PendingRemote<network::mojom::URLLoaderFactory> Create( int child_id) { mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote; // The FileURLLoaderFactory will delete itself when there are no more // receivers - see the SelfDeletingURLLoaderFactory::OnDisconnect method. new FileURLLoaderFactory(child_id, pending_remote.InitWithNewPipeAndPassReceiver()); return pending_remote; } // disable copy FileURLLoaderFactory(const FileURLLoaderFactory&) = delete; FileURLLoaderFactory& operator=(const FileURLLoaderFactory&) = delete; private: explicit FileURLLoaderFactory( int child_id, mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver) : network::SelfDeletingURLLoaderFactory(std::move(factory_receiver)), child_id_(child_id) {} ~FileURLLoaderFactory() override = default; // network::mojom::URLLoaderFactory: void CreateLoaderAndStart( mojo::PendingReceiver<network::mojom::URLLoader> loader, int32_t request_id, uint32_t options, const network::ResourceRequest& request, mojo::PendingRemote<network::mojom::URLLoaderClient> client, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) override { if (!content::ChildProcessSecurityPolicy::GetInstance()->CanRequestURL( child_id_, request.url)) { mojo::Remote<network::mojom::URLLoaderClient>(std::move(client)) ->OnComplete( network::URLLoaderCompletionStatus(net::ERR_ACCESS_DENIED)); return; } content::CreateFileURLLoaderBypassingSecurityChecks( request, std::move(loader), std::move(client), /*observer=*/nullptr, /* allow_directory_listing */ true); } int child_id_; }; } // namespace #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void ElectronBrowserClient::RegisterNonNetworkSubresourceURLLoaderFactories( int render_process_id, int render_frame_id, const absl::optional<url::Origin>& request_initiator_origin, NonNetworkURLLoaderFactoryMap* factories) { auto* render_process_host = content::RenderProcessHost::FromID(render_process_id); DCHECK(render_process_host); if (!render_process_host || !render_process_host->GetBrowserContext()) return; content::RenderFrameHost* frame_host = content::RenderFrameHost::FromID(render_process_id, render_frame_id); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(frame_host); // Allow accessing file:// subresources from non-file protocols if web // security is disabled. bool allow_file_access = false; if (web_contents) { const auto& web_preferences = web_contents->GetOrCreateWebPreferences(); if (!web_preferences.web_security_enabled) allow_file_access = true; } ProtocolRegistry::FromBrowserContext(render_process_host->GetBrowserContext()) ->RegisterURLLoaderFactories(factories, allow_file_access); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto factory = extensions::CreateExtensionURLLoaderFactory(render_process_id, render_frame_id); if (factory) factories->emplace(extensions::kExtensionScheme, std::move(factory)); if (!web_contents) return; extensions::ElectronExtensionWebContentsObserver* web_observer = extensions::ElectronExtensionWebContentsObserver::FromWebContents( web_contents); // There is nothing to do if no ElectronExtensionWebContentsObserver is // attached to the |web_contents|. if (!web_observer) return; const extensions::Extension* extension = web_observer->GetExtensionFromFrame(frame_host, false); if (!extension) return; // Support for chrome:// scheme if appropriate. if (extension->is_extension() && extensions::Manifest::IsComponentLocation(extension->location())) { // Components of chrome that are implemented as extensions or platform apps // are allowed to use chrome://resources/ and chrome://theme/ URLs. factories->emplace(content::kChromeUIScheme, content::CreateWebUIURLLoaderFactory( frame_host, content::kChromeUIScheme, {content::kChromeUIResourcesHost})); } // Extensions with the necessary permissions get access to file:// URLs that // gets approval from ChildProcessSecurityPolicy. Keep this logic in sync with // ExtensionWebContentsObserver::RenderFrameCreated. extensions::Manifest::Type type = extension->GetType(); if (type == extensions::Manifest::TYPE_EXTENSION && AllowFileAccess(extension->id(), web_contents->GetBrowserContext())) { factories->emplace(url::kFileScheme, FileURLLoaderFactory::Create(render_process_id)); } #endif } void ElectronBrowserClient:: RegisterNonNetworkServiceWorkerUpdateURLLoaderFactories( content::BrowserContext* browser_context, NonNetworkURLLoaderFactoryMap* factories) { DCHECK(browser_context); DCHECK(factories); auto* protocol_registry = ProtocolRegistry::FromBrowserContext(browser_context); protocol_registry->RegisterURLLoaderFactories(factories, false /* allow_file_access */); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) factories->emplace( extensions::kExtensionScheme, extensions::CreateExtensionServiceWorkerScriptURLLoaderFactory( browser_context)); #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) } bool ElectronBrowserClient::ShouldTreatURLSchemeAsFirstPartyWhenTopLevel( base::StringPiece scheme, bool is_embedded_origin_secure) { if (is_embedded_origin_secure && scheme == content::kChromeUIScheme) return true; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) return scheme == extensions::kExtensionScheme; #else return false; #endif } bool ElectronBrowserClient::WillInterceptWebSocket( content::RenderFrameHost* frame) { if (!frame) return false; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto* browser_context = frame->GetProcess()->GetBrowserContext(); auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context); // NOTE: Some unit test environments do not initialize // BrowserContextKeyedAPI factories for e.g. WebRequest. if (!web_request.get()) return false; bool has_listener = web_request->HasListener(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) const auto* web_request_api = extensions::BrowserContextKeyedAPIFactory<extensions::WebRequestAPI>::Get( browser_context); if (web_request_api) has_listener |= web_request_api->MayHaveProxies(); #endif return has_listener; } void ElectronBrowserClient::CreateWebSocket( content::RenderFrameHost* frame, WebSocketFactory factory, const GURL& url, const net::SiteForCookies& site_for_cookies, const absl::optional<std::string>& user_agent, mojo::PendingRemote<network::mojom::WebSocketHandshakeClient> handshake_client) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto* browser_context = frame->GetProcess()->GetBrowserContext(); auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context); DCHECK(web_request.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!web_request->HasListener()) { auto* web_request_api = extensions::BrowserContextKeyedAPIFactory< extensions::WebRequestAPI>::Get(browser_context); if (web_request_api && web_request_api->MayHaveProxies()) { web_request_api->ProxyWebSocket(frame, std::move(factory), url, site_for_cookies, user_agent, std::move(handshake_client)); return; } } #endif ProxyingWebSocket::StartProxying( web_request.get(), std::move(factory), url, site_for_cookies, user_agent, std::move(handshake_client), true, frame->GetProcess()->GetID(), frame->GetRoutingID(), frame->GetLastCommittedOrigin(), browser_context, &next_id_); } bool ElectronBrowserClient::WillCreateURLLoaderFactory( content::BrowserContext* browser_context, content::RenderFrameHost* frame_host, int render_process_id, URLLoaderFactoryType type, const url::Origin& request_initiator, absl::optional<int64_t> navigation_id, ukm::SourceIdObj ukm_source_id, mojo::PendingReceiver<network::mojom::URLLoaderFactory>* factory_receiver, mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>* header_client, bool* bypass_redirect_checks, bool* disable_secure_dns, network::mojom::URLLoaderFactoryOverridePtr* factory_override, scoped_refptr<base::SequencedTaskRunner> navigation_response_task_runner) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context); DCHECK(web_request.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!web_request->HasListener()) { auto* web_request_api = extensions::BrowserContextKeyedAPIFactory< extensions::WebRequestAPI>::Get(browser_context); DCHECK(web_request_api); bool use_proxy_for_web_request = web_request_api->MaybeProxyURLLoaderFactory( browser_context, frame_host, render_process_id, type, navigation_id, ukm_source_id, factory_receiver, header_client, navigation_response_task_runner); if (bypass_redirect_checks) *bypass_redirect_checks = use_proxy_for_web_request; if (use_proxy_for_web_request) return true; } #endif auto proxied_receiver = std::move(*factory_receiver); mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory_remote; *factory_receiver = target_factory_remote.InitWithNewPipeAndPassReceiver(); // Required by WebRequestInfoInitParams. // // Note that in Electron we allow webRequest to capture requests sent from // browser process, so creation of |navigation_ui_data| is different from // Chromium which only does for renderer-initialized navigations. std::unique_ptr<extensions::ExtensionNavigationUIData> navigation_ui_data; if (navigation_id.has_value()) { navigation_ui_data = std::make_unique<extensions::ExtensionNavigationUIData>(); } mojo::PendingReceiver<network::mojom::TrustedURLLoaderHeaderClient> header_client_receiver; if (header_client) header_client_receiver = header_client->InitWithNewPipeAndPassReceiver(); auto* protocol_registry = ProtocolRegistry::FromBrowserContext(browser_context); new ProxyingURLLoaderFactory( web_request.get(), protocol_registry->intercept_handlers(), render_process_id, frame_host ? frame_host->GetRoutingID() : MSG_ROUTING_NONE, &next_id_, std::move(navigation_ui_data), std::move(navigation_id), std::move(proxied_receiver), std::move(target_factory_remote), std::move(header_client_receiver), type); return true; } std::vector<std::unique_ptr<content::URLLoaderRequestInterceptor>> ElectronBrowserClient::WillCreateURLLoaderRequestInterceptors( content::NavigationUIData* navigation_ui_data, int frame_tree_node_id, int64_t navigation_id, scoped_refptr<base::SequencedTaskRunner> navigation_response_task_runner) { std::vector<std::unique_ptr<content::URLLoaderRequestInterceptor>> interceptors; #if BUILDFLAG(ENABLE_PDF_VIEWER) { std::unique_ptr<content::URLLoaderRequestInterceptor> pdf_interceptor = pdf::PdfURLLoaderRequestInterceptor::MaybeCreateInterceptor( frame_tree_node_id, std::make_unique<ChromePdfStreamDelegate>()); if (pdf_interceptor) interceptors.push_back(std::move(pdf_interceptor)); } #endif return interceptors; } void ElectronBrowserClient::OverrideURLLoaderFactoryParams( content::BrowserContext* browser_context, const url::Origin& origin, bool is_for_isolated_world, network::mojom::URLLoaderFactoryParams* factory_params) { if (factory_params->top_frame_id) { // Bypass CORB and CORS when web security is disabled. auto* rfh = content::RenderFrameHost::FromFrameToken( content::GlobalRenderFrameHostToken( factory_params->process_id, blink::LocalFrameToken(factory_params->top_frame_id.value()))); auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); auto* prefs = WebContentsPreferences::From(web_contents); if (prefs && !prefs->IsWebSecurityEnabled()) { factory_params->is_corb_enabled = false; factory_params->disable_web_security = true; } } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::URLLoaderFactoryManager::OverrideURLLoaderFactoryParams( browser_context, origin, is_for_isolated_world, factory_params); #endif } void ElectronBrowserClient:: RegisterAssociatedInterfaceBindersForRenderFrameHost( content::RenderFrameHost& render_frame_host, // NOLINT(runtime/references) blink::AssociatedInterfaceRegistry& associated_registry) { // NOLINT(runtime/references) auto* contents = content::WebContents::FromRenderFrameHost(&render_frame_host); if (contents) { auto* prefs = WebContentsPreferences::From(contents); if (render_frame_host.GetFrameTreeNodeId() == contents->GetPrimaryMainFrame()->GetFrameTreeNodeId() || (prefs && prefs->AllowsNodeIntegrationInSubFrames())) { associated_registry.AddInterface<mojom::ElectronApiIPC>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<mojom::ElectronApiIPC> receiver) { ElectronApiIPCHandlerImpl::Create(render_frame_host, std::move(receiver)); }, &render_frame_host)); } } associated_registry.AddInterface<mojom::ElectronWebContentsUtility>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<mojom::ElectronWebContentsUtility> receiver) { ElectronWebContentsUtilityHandlerImpl::Create(render_frame_host, std::move(receiver)); }, &render_frame_host)); associated_registry.AddInterface<mojom::ElectronAutofillDriver>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<mojom::ElectronAutofillDriver> receiver) { AutofillDriverFactory::BindAutofillDriver(std::move(receiver), render_frame_host); }, &render_frame_host)); #if BUILDFLAG(ENABLE_PRINTING) associated_registry.AddInterface<printing::mojom::PrintManagerHost>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<printing::mojom::PrintManagerHost> receiver) { PrintViewManagerElectron::BindPrintManagerHost(std::move(receiver), render_frame_host); }, &render_frame_host)); #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) associated_registry.AddInterface<extensions::mojom::LocalFrameHost>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<extensions::mojom::LocalFrameHost> receiver) { extensions::ExtensionWebContentsObserver::BindLocalFrameHost( std::move(receiver), render_frame_host); }, &render_frame_host)); associated_registry.AddInterface<guest_view::mojom::GuestViewHost>( base::BindRepeating(&extensions::ExtensionsGuestView::CreateForComponents, render_frame_host.GetGlobalId())); associated_registry.AddInterface<extensions::mojom::GuestView>( base::BindRepeating(&extensions::ExtensionsGuestView::CreateForExtensions, render_frame_host.GetGlobalId())); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) associated_registry.AddInterface<pdf::mojom::PdfService>(base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<pdf::mojom::PdfService> receiver) { pdf::PDFDocumentHelper::BindPdfService( std::move(receiver), render_frame_host, std::make_unique<ElectronPDFDocumentHelperClient>()); }, &render_frame_host)); #endif } std::string ElectronBrowserClient::GetApplicationLocale() { if (BrowserThread::CurrentlyOn(BrowserThread::IO)) return g_io_thread_application_locale.Get(); return *g_application_locale; } bool ElectronBrowserClient::ShouldEnableStrictSiteIsolation() { // Enable site isolation. It is off by default in Chromium <= 69. return true; } void ElectronBrowserClient::BindHostReceiverForRenderer( content::RenderProcessHost* render_process_host, mojo::GenericPendingReceiver receiver) { #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) if (auto host_receiver = receiver.As<spellcheck::mojom::SpellCheckHost>()) { SpellCheckHostChromeImpl::Create(render_process_host->GetID(), std::move(host_receiver)); return; } #endif } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void BindMimeHandlerService( content::RenderFrameHost* frame_host, mojo::PendingReceiver<extensions::mime_handler::MimeHandlerService> receiver) { content::WebContents* contents = content::WebContents::FromRenderFrameHost(frame_host); auto* guest_view = extensions::MimeHandlerViewGuest::FromWebContents(contents); if (!guest_view) return; extensions::MimeHandlerServiceImpl::Create(guest_view->GetStreamWeakPtr(), std::move(receiver)); } void BindBeforeUnloadControl( content::RenderFrameHost* frame_host, mojo::PendingReceiver<extensions::mime_handler::BeforeUnloadControl> receiver) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame_host); if (!web_contents) return; auto* guest_view = extensions::MimeHandlerViewGuest::FromWebContents(web_contents); if (!guest_view) return; guest_view->FuseBeforeUnloadControl(std::move(receiver)); } #endif void ElectronBrowserClient::ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) associated_registry->AddInterface<extensions::mojom::EventRouter>( base::BindRepeating(&extensions::EventRouter::BindForRenderer, render_process_host->GetID())); associated_registry->AddInterface<extensions::mojom::RendererHost>( base::BindRepeating(&extensions::RendererStartupHelper::BindForRenderer, render_process_host->GetID())); associated_registry->AddInterface<extensions::mojom::ServiceWorkerHost>( base::BindRepeating(&extensions::ServiceWorkerHost::BindReceiver, render_process_host->GetID())); #endif } void ElectronBrowserClient::RegisterBrowserInterfaceBindersForFrame( content::RenderFrameHost* render_frame_host, mojo::BinderMapWithContext<content::RenderFrameHost*>* map) { map->Add<network_hints::mojom::NetworkHintsHandler>( base::BindRepeating(&BindNetworkHintsHandler)); map->Add<blink::mojom::BadgeService>( base::BindRepeating(&badging::BadgeManager::BindFrameReceiver)); map->Add<blink::mojom::KeyboardLockService>(base::BindRepeating( &content::KeyboardLockServiceImpl::CreateMojoService)); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) map->Add<extensions::mime_handler::MimeHandlerService>( base::BindRepeating(&BindMimeHandlerService)); map->Add<extensions::mime_handler::BeforeUnloadControl>( base::BindRepeating(&BindBeforeUnloadControl)); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); if (!web_contents) return; const GURL& site = render_frame_host->GetSiteInstance()->GetSiteURL(); if (!site.SchemeIs(extensions::kExtensionScheme)) return; content::BrowserContext* browser_context = render_frame_host->GetProcess()->GetBrowserContext(); auto* extension = extensions::ExtensionRegistry::Get(browser_context) ->enabled_extensions() .GetByID(site.host()); if (!extension) return; extensions::ExtensionsBrowserClient::Get() ->RegisterBrowserInterfaceBindersForFrame(map, render_frame_host, extension); #endif } #if BUILDFLAG(IS_LINUX) void ElectronBrowserClient::GetAdditionalMappedFilesForChildProcess( const base::CommandLine& command_line, int child_process_id, content::PosixFileDescriptorInfo* mappings) { int crash_signal_fd = GetCrashSignalFD(command_line); if (crash_signal_fd >= 0) { mappings->Share(kCrashDumpSignal, crash_signal_fd); } } #endif std::unique_ptr<content::LoginDelegate> ElectronBrowserClient::CreateLoginDelegate( const net::AuthChallengeInfo& auth_info, content::WebContents* web_contents, const content::GlobalRequestID& request_id, bool is_main_frame, const GURL& url, scoped_refptr<net::HttpResponseHeaders> response_headers, bool first_auth_attempt, LoginAuthRequiredCallback auth_required_callback) { return std::make_unique<LoginHandler>( auth_info, web_contents, is_main_frame, url, response_headers, first_auth_attempt, std::move(auth_required_callback)); } std::vector<std::unique_ptr<blink::URLLoaderThrottle>> ElectronBrowserClient::CreateURLLoaderThrottles( const network::ResourceRequest& request, content::BrowserContext* browser_context, const base::RepeatingCallback<content::WebContents*()>& wc_getter, content::NavigationUIData* navigation_ui_data, int frame_tree_node_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); std::vector<std::unique_ptr<blink::URLLoaderThrottle>> result; #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) result.push_back(std::make_unique<PluginResponseInterceptorURLLoaderThrottle>( request.destination, frame_tree_node_id)); #endif return result; } base::flat_set<std::string> ElectronBrowserClient::GetPluginMimeTypesWithExternalHandlers( content::BrowserContext* browser_context) { base::flat_set<std::string> mime_types; #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto map = PluginUtils::GetMimeTypeToExtensionIdMap(browser_context); for (const auto& pair : map) mime_types.insert(pair.first); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) mime_types.insert(pdf::kInternalPluginMimeType); #endif return mime_types; } content::SerialDelegate* ElectronBrowserClient::GetSerialDelegate() { if (!serial_delegate_) serial_delegate_ = std::make_unique<ElectronSerialDelegate>(); return serial_delegate_.get(); } content::BluetoothDelegate* ElectronBrowserClient::GetBluetoothDelegate() { if (!bluetooth_delegate_) bluetooth_delegate_ = std::make_unique<ElectronBluetoothDelegate>(); return bluetooth_delegate_.get(); } content::UsbDelegate* ElectronBrowserClient::GetUsbDelegate() { if (!usb_delegate_) usb_delegate_ = std::make_unique<ElectronUsbDelegate>(); return usb_delegate_.get(); } void BindBadgeServiceForServiceWorker( const content::ServiceWorkerVersionBaseInfo& info, mojo::PendingReceiver<blink::mojom::BadgeService> receiver) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::RenderProcessHost* render_process_host = content::RenderProcessHost::FromID(info.process_id); if (!render_process_host) return; badging::BadgeManager::BindServiceWorkerReceiver( render_process_host, info.scope, std::move(receiver)); } void ElectronBrowserClient::RegisterBrowserInterfaceBindersForServiceWorker( content::BrowserContext* browser_context, const content::ServiceWorkerVersionBaseInfo& service_worker_version_info, mojo::BinderMapWithContext<const content::ServiceWorkerVersionBaseInfo&>* map) { map->Add<blink::mojom::BadgeService>( base::BindRepeating(&BindBadgeServiceForServiceWorker)); } #if BUILDFLAG(IS_MAC) device::GeolocationManager* ElectronBrowserClient::GetGeolocationManager() { return device::GeolocationManager::GetInstance(); } #endif content::HidDelegate* ElectronBrowserClient::GetHidDelegate() { if (!hid_delegate_) hid_delegate_ = std::make_unique<ElectronHidDelegate>(); return hid_delegate_.get(); } content::WebAuthenticationDelegate* ElectronBrowserClient::GetWebAuthenticationDelegate() { if (!web_authentication_delegate_) { web_authentication_delegate_ = std::make_unique<ElectronWebAuthenticationDelegate>(); } return web_authentication_delegate_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,439
Convert legacy IPC calls in extensions code to use mojo
https://chromium-review.googlesource.com/c/chromium/src/+/4995136 turned on the build flag to use the new mojo IPC pipe for messaging in extensions. In #40418 we turned this off because we have not converted our extensions code to use mojo. It appears that in chromium the follow CLs were landed to use mojo in extensions: - 4947890: [extensions] Convert Extension Messaging APIs over to mojo | https://chromium-review.googlesource.com/c/chromium/src/+/4947890 - 4950041: [extensions] Port Event Acks to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4950041 - 4902564: [extensions] Move WakeEventPage to mojom::RendererHost | https://chromium-review.googlesource.com/c/chromium/src/+/4902564 - 4956841: [extensions] Port GetMessageBundle over to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4956841 Once these changes have landed, the following flag override in build/args/all.gn should be removed: `enable_extensions_legacy_ipc = true`
https://github.com/electron/electron/issues/40439
https://github.com/electron/electron/pull/40511
088affd4a4311e03b8ed400cdf5d82f1db2125a4
371bca69b69351dc47d4b4dcfdf9a626f43b3b51
2023-11-02T18:50:40Z
c++
2023-11-15T14:30:47Z
shell/browser/electron_browser_client.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_ELECTRON_BROWSER_CLIENT_H_ #define ELECTRON_SHELL_BROWSER_ELECTRON_BROWSER_CLIENT_H_ #include <map> #include <memory> #include <set> #include <string> #include <vector> #include "base/files/file_path.h" #include "base/memory/raw_ptr.h" #include "base/synchronization/lock.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/render_process_host_observer.h" #include "content/public/browser/web_contents.h" #include "electron/buildflags/buildflags.h" #include "net/ssl/client_cert_identity.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "shell/browser/bluetooth/electron_bluetooth_delegate.h" #include "shell/browser/hid/electron_hid_delegate.h" #include "shell/browser/serial/electron_serial_delegate.h" #include "shell/browser/usb/electron_usb_delegate.h" #include "third_party/blink/public/mojom/badging/badging.mojom-forward.h" namespace content { class ClientCertificateDelegate; class QuotaPermissionContext; } // namespace content namespace net { class SSLCertRequestInfo; } namespace electron { class ElectronBrowserMainParts; class NotificationPresenter; class PlatformNotificationService; class ElectronWebAuthenticationDelegate; class ElectronBrowserClient : public content::ContentBrowserClient, public content::RenderProcessHostObserver { public: static ElectronBrowserClient* Get(); static void SetApplicationLocale(const std::string& locale); ElectronBrowserClient(); ~ElectronBrowserClient() override; // disable copy ElectronBrowserClient(const ElectronBrowserClient&) = delete; ElectronBrowserClient& operator=(const ElectronBrowserClient&) = delete; using Delegate = content::ContentBrowserClient; void set_delegate(Delegate* delegate) { delegate_ = delegate; } // Returns the WebContents for pending render processes. content::WebContents* GetWebContentsFromProcessID(int process_id); NotificationPresenter* GetNotificationPresenter(); void WebNotificationAllowed(content::RenderFrameHost* rfh, base::OnceCallback<void(bool, bool)> callback); // content::NavigatorDelegate std::vector<std::unique_ptr<content::NavigationThrottle>> CreateThrottlesForNavigation(content::NavigationHandle* handle) override; // content::ContentBrowserClient: std::string GetApplicationLocale() override; bool ShouldEnableStrictSiteIsolation() override; void BindHostReceiverForRenderer( content::RenderProcessHost* render_process_host, mojo::GenericPendingReceiver receiver) override; void ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) override; void RegisterBrowserInterfaceBindersForFrame( content::RenderFrameHost* render_frame_host, mojo::BinderMapWithContext<content::RenderFrameHost*>* map) override; void RegisterBrowserInterfaceBindersForServiceWorker( content::BrowserContext* browser_context, const content::ServiceWorkerVersionBaseInfo& service_worker_version_info, mojo::BinderMapWithContext<const content::ServiceWorkerVersionBaseInfo&>* map) override; #if BUILDFLAG(IS_LINUX) void GetAdditionalMappedFilesForChildProcess( const base::CommandLine& command_line, int child_process_id, content::PosixFileDescriptorInfo* mappings) override; #endif std::string GetUserAgent() override; void SetUserAgent(const std::string& user_agent); blink::UserAgentMetadata GetUserAgentMetadata() override; content::SerialDelegate* GetSerialDelegate() override; content::BluetoothDelegate* GetBluetoothDelegate() override; content::HidDelegate* GetHidDelegate() override; content::UsbDelegate* GetUsbDelegate() override; content::WebAuthenticationDelegate* GetWebAuthenticationDelegate() override; #if BUILDFLAG(IS_MAC) device::GeolocationManager* GetGeolocationManager() override; #endif content::PlatformNotificationService* GetPlatformNotificationService(); protected: void RenderProcessWillLaunch(content::RenderProcessHost* host) override; content::SpeechRecognitionManagerDelegate* CreateSpeechRecognitionManagerDelegate() override; content::TtsPlatform* GetTtsPlatform() override; void OverrideWebkitPrefs(content::WebContents* web_contents, blink::web_pref::WebPreferences* prefs) override; void RegisterPendingSiteInstance( content::RenderFrameHost* render_frame_host, content::SiteInstance* pending_site_instance) override; void AppendExtraCommandLineSwitches(base::CommandLine* command_line, int child_process_id) override; void DidCreatePpapiPlugin(content::BrowserPpapiHost* browser_host) override; std::string GetGeolocationApiKey() override; content::GeneratedCodeCacheSettings GetGeneratedCodeCacheSettings( content::BrowserContext* context) override; void AllowCertificateError( content::WebContents* web_contents, int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, bool is_main_frame_request, bool strict_enforcement, base::OnceCallback<void(content::CertificateRequestResultType)> callback) override; base::OnceClosure SelectClientCertificate( content::BrowserContext* browser_context, content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, net::ClientCertIdentityList client_certs, std::unique_ptr<content::ClientCertificateDelegate> delegate) override; bool CanCreateWindow(content::RenderFrameHost* opener, const GURL& opener_url, const GURL& opener_top_level_frame_url, const url::Origin& source_origin, content::mojom::WindowContainerType container_type, const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& features, const std::string& raw_features, const scoped_refptr<network::ResourceRequestBody>& body, bool user_gesture, bool opener_suppressed, bool* no_javascript_access) override; std::unique_ptr<content::VideoOverlayWindow> CreateWindowForVideoPictureInPicture( content::VideoPictureInPictureWindowController* controller) override; void GetAdditionalAllowedSchemesForFileSystem( std::vector<std::string>* additional_schemes) override; void GetAdditionalWebUISchemes( std::vector<std::string>* additional_schemes) override; std::unique_ptr<net::ClientCertStore> CreateClientCertStore( content::BrowserContext* browser_context) override; std::unique_ptr<device::LocationProvider> OverrideSystemLocationProvider() override; void ConfigureNetworkContextParams( content::BrowserContext* browser_context, bool in_memory, const base::FilePath& relative_partition_path, network::mojom::NetworkContextParams* network_context_params, cert_verifier::mojom::CertVerifierCreationParams* cert_verifier_creation_params) override; network::mojom::NetworkContext* GetSystemNetworkContext() override; content::MediaObserver* GetMediaObserver() override; std::unique_ptr<content::DevToolsManagerDelegate> CreateDevToolsManagerDelegate() override; std::unique_ptr<content::BrowserMainParts> CreateBrowserMainParts( bool /* is_integration_test */) override; base::FilePath GetDefaultDownloadDirectory() override; scoped_refptr<network::SharedURLLoaderFactory> GetSystemSharedURLLoaderFactory() override; void OnNetworkServiceCreated( network::mojom::NetworkService* network_service) override; std::vector<base::FilePath> GetNetworkContextsParentDirectory() override; std::string GetProduct() override; void RegisterNonNetworkNavigationURLLoaderFactories( int frame_tree_node_id, ukm::SourceIdObj ukm_source_id, NonNetworkURLLoaderFactoryMap* factories) override; void RegisterNonNetworkWorkerMainResourceURLLoaderFactories( content::BrowserContext* browser_context, NonNetworkURLLoaderFactoryMap* factories) override; void RegisterNonNetworkSubresourceURLLoaderFactories( int render_process_id, int render_frame_id, const absl::optional<url::Origin>& request_initiator_origin, NonNetworkURLLoaderFactoryMap* factories) override; void RegisterNonNetworkServiceWorkerUpdateURLLoaderFactories( content::BrowserContext* browser_context, NonNetworkURLLoaderFactoryMap* factories) override; void CreateWebSocket( content::RenderFrameHost* frame, WebSocketFactory factory, const GURL& url, const net::SiteForCookies& site_for_cookies, const absl::optional<std::string>& user_agent, mojo::PendingRemote<network::mojom::WebSocketHandshakeClient> handshake_client) override; bool WillInterceptWebSocket(content::RenderFrameHost*) override; bool WillCreateURLLoaderFactory( content::BrowserContext* browser_context, content::RenderFrameHost* frame, int render_process_id, URLLoaderFactoryType type, const url::Origin& request_initiator, absl::optional<int64_t> navigation_id, ukm::SourceIdObj ukm_source_id, mojo::PendingReceiver<network::mojom::URLLoaderFactory>* factory_receiver, mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>* header_client, bool* bypass_redirect_checks, bool* disable_secure_dns, network::mojom::URLLoaderFactoryOverridePtr* factory_override, scoped_refptr<base::SequencedTaskRunner> navigation_response_task_runner) override; std::vector<std::unique_ptr<content::URLLoaderRequestInterceptor>> WillCreateURLLoaderRequestInterceptors( content::NavigationUIData* navigation_ui_data, int frame_tree_node_id, int64_t navigation_id, scoped_refptr<base::SequencedTaskRunner> navigation_response_task_runner) override; bool ShouldTreatURLSchemeAsFirstPartyWhenTopLevel( base::StringPiece scheme, bool is_embedded_origin_secure) override; void OverrideURLLoaderFactoryParams( content::BrowserContext* browser_context, const url::Origin& origin, bool is_for_isolated_world, network::mojom::URLLoaderFactoryParams* factory_params) override; void RegisterAssociatedInterfaceBindersForRenderFrameHost( content::RenderFrameHost& render_frame_host, blink::AssociatedInterfaceRegistry& associated_registry) override; bool HandleExternalProtocol( const GURL& url, content::WebContents::Getter web_contents_getter, int frame_tree_node_id, content::NavigationUIData* navigation_data, bool is_primary_main_frame, bool is_in_fenced_frame_tree, network::mojom::WebSandboxFlags sandbox_flags, ui::PageTransition page_transition, bool has_user_gesture, const absl::optional<url::Origin>& initiating_origin, content::RenderFrameHost* initiator_document, mojo::PendingRemote<network::mojom::URLLoaderFactory>* out_factory) override; std::unique_ptr<content::LoginDelegate> CreateLoginDelegate( const net::AuthChallengeInfo& auth_info, content::WebContents* web_contents, const content::GlobalRequestID& request_id, bool is_main_frame, const GURL& url, scoped_refptr<net::HttpResponseHeaders> response_headers, bool first_auth_attempt, LoginAuthRequiredCallback auth_required_callback) override; void SiteInstanceGotProcess(content::SiteInstance* site_instance) override; std::vector<std::unique_ptr<blink::URLLoaderThrottle>> CreateURLLoaderThrottles( const network::ResourceRequest& request, content::BrowserContext* browser_context, const base::RepeatingCallback<content::WebContents*()>& wc_getter, content::NavigationUIData* navigation_ui_data, int frame_tree_node_id) override; base::flat_set<std::string> GetPluginMimeTypesWithExternalHandlers( content::BrowserContext* browser_context) override; bool IsSuitableHost(content::RenderProcessHost* process_host, const GURL& site_url) override; bool ShouldUseProcessPerSite(content::BrowserContext* browser_context, const GURL& effective_url) override; void GetMediaDeviceIDSalt( content::RenderFrameHost* rfh, const net::SiteForCookies& site_for_cookies, const blink::StorageKey& storage_key, base::OnceCallback<void(bool, const std::string&)> callback) override; base::FilePath GetLoggingFileName(const base::CommandLine& cmd_line) override; // content::RenderProcessHostObserver: void RenderProcessHostDestroyed(content::RenderProcessHost* host) override; void RenderProcessReady(content::RenderProcessHost* host) override; void RenderProcessExited( content::RenderProcessHost* host, const content::ChildProcessTerminationInfo& info) override; private: content::SiteInstance* GetSiteInstanceFromAffinity( content::BrowserContext* browser_context, const GURL& url, content::RenderFrameHost* rfh) const; bool IsRendererSubFrame(int process_id) const; // pending_render_process => web contents. std::map<int, content::WebContents*> pending_processes_; std::set<int> renderer_is_subframe_; std::unique_ptr<PlatformNotificationService> notification_service_; std::unique_ptr<NotificationPresenter> notification_presenter_; raw_ptr<Delegate> delegate_ = nullptr; std::string user_agent_override_ = ""; // Simple shared ID generator, used by ProxyingURLLoaderFactory and // ProxyingWebSocket classes. uint64_t next_id_ = 0; std::unique_ptr<ElectronSerialDelegate> serial_delegate_; std::unique_ptr<ElectronBluetoothDelegate> bluetooth_delegate_; std::unique_ptr<ElectronUsbDelegate> usb_delegate_; std::unique_ptr<ElectronHidDelegate> hid_delegate_; std::unique_ptr<ElectronWebAuthenticationDelegate> web_authentication_delegate_; #if BUILDFLAG(IS_MAC) raw_ptr<ElectronBrowserMainParts> browser_main_parts_ = nullptr; #endif }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_ELECTRON_BROWSER_CLIENT_H_
closed
electron/electron
https://github.com/electron/electron
40,439
Convert legacy IPC calls in extensions code to use mojo
https://chromium-review.googlesource.com/c/chromium/src/+/4995136 turned on the build flag to use the new mojo IPC pipe for messaging in extensions. In #40418 we turned this off because we have not converted our extensions code to use mojo. It appears that in chromium the follow CLs were landed to use mojo in extensions: - 4947890: [extensions] Convert Extension Messaging APIs over to mojo | https://chromium-review.googlesource.com/c/chromium/src/+/4947890 - 4950041: [extensions] Port Event Acks to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4950041 - 4902564: [extensions] Move WakeEventPage to mojom::RendererHost | https://chromium-review.googlesource.com/c/chromium/src/+/4902564 - 4956841: [extensions] Port GetMessageBundle over to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4956841 Once these changes have landed, the following flag override in build/args/all.gn should be removed: `enable_extensions_legacy_ipc = true`
https://github.com/electron/electron/issues/40439
https://github.com/electron/electron/pull/40511
088affd4a4311e03b8ed400cdf5d82f1db2125a4
371bca69b69351dc47d4b4dcfdf9a626f43b3b51
2023-11-02T18:50:40Z
c++
2023-11-15T14:30:47Z
shell/browser/electron_browser_context.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_context.h" #include <memory> #include <utility> #include "base/barrier_closure.h" #include "base/base_paths.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/strings/escape.h" #include "base/strings/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/prefs/json_pref_store.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/pref_service_factory.h" #include "components/prefs/value_map_pref_store.h" #include "components/proxy_config/pref_proxy_config_tracker_impl.h" #include "components/proxy_config/proxy_config_pref_names.h" #include "content/browser/blob_storage/chrome_blob_storage_context.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/cors_origin_pattern_setter.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents_media_capture_id.h" #include "media/audio/audio_device_description.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/network_context.mojom.h" #include "shell/browser/cookie_change_notifier.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_download_manager_delegate.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/net/resolve_proxy_helper.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/special_storage_policy.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/zoom_level_delegate.h" #include "shell/common/application_info.h" #include "shell/common/electron_constants.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/options_switches.h" #include "shell/common/thread_restrictions.h" #include "third_party/blink/public/mojom/media/capture_handle_config.mojom.h" #include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/browser/extension_pref_store.h" #include "extensions/browser/extension_pref_value_map_factory.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/pref_names.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/browser/extensions/electron_extension_system_factory.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "components/pref_registry/pref_registry_syncable.h" #include "components/user_prefs/user_prefs.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "base/i18n/rtl.h" #include "components/language/core/browser/language_prefs.h" #include "components/spellcheck/browser/pref_names.h" #include "components/spellcheck/common/spellcheck_common.h" #endif using content::BrowserThread; namespace electron { namespace { // Copied from chrome/browser/media/webrtc/desktop_capture_devices_util.cc. media::mojom::CaptureHandlePtr CreateCaptureHandle( content::WebContents* capturer, const url::Origin& capturer_origin, const content::DesktopMediaID& captured_id) { if (capturer_origin.opaque()) { return nullptr; } content::RenderFrameHost* const captured_rfh = content::RenderFrameHost::FromID( captured_id.web_contents_id.render_process_id, captured_id.web_contents_id.main_render_frame_id); if (!captured_rfh || !captured_rfh->IsActive()) { return nullptr; } content::WebContents* const captured = content::WebContents::FromRenderFrameHost(captured_rfh); if (!captured) { return nullptr; } const auto& captured_config = captured->GetCaptureHandleConfig(); if (!captured_config.all_origins_permitted && base::ranges::none_of( captured_config.permitted_origins, [capturer_origin](const url::Origin& permitted_origin) { return capturer_origin.IsSameOriginWith(permitted_origin); })) { return nullptr; } // Observing CaptureHandle when either the capturing or the captured party // is incognito is disallowed, except for self-capture. if (capturer->GetPrimaryMainFrame() != captured->GetPrimaryMainFrame()) { if (capturer->GetBrowserContext()->IsOffTheRecord() || captured->GetBrowserContext()->IsOffTheRecord()) { return nullptr; } } if (!captured_config.expose_origin && captured_config.capture_handle.empty()) { return nullptr; } auto result = media::mojom::CaptureHandle::New(); if (captured_config.expose_origin) { result->origin = captured->GetPrimaryMainFrame()->GetLastCommittedOrigin(); } result->capture_handle = captured_config.capture_handle; return result; } // Copied from chrome/browser/media/webrtc/desktop_capture_devices_util.cc. media::mojom::DisplayMediaInformationPtr DesktopMediaIDToDisplayMediaInformation( content::WebContents* capturer, const url::Origin& capturer_origin, const content::DesktopMediaID& media_id) { media::mojom::DisplayCaptureSurfaceType display_surface = media::mojom::DisplayCaptureSurfaceType::MONITOR; bool logical_surface = true; media::mojom::CursorCaptureType cursor = media::mojom::CursorCaptureType::NEVER; #if defined(USE_AURA) const bool uses_aura = media_id.window_id != content::DesktopMediaID::kNullId ? true : false; #else const bool uses_aura = false; #endif // defined(USE_AURA) media::mojom::CaptureHandlePtr capture_handle; switch (media_id.type) { case content::DesktopMediaID::TYPE_SCREEN: display_surface = media::mojom::DisplayCaptureSurfaceType::MONITOR; cursor = uses_aura ? media::mojom::CursorCaptureType::MOTION : media::mojom::CursorCaptureType::ALWAYS; break; case content::DesktopMediaID::TYPE_WINDOW: display_surface = media::mojom::DisplayCaptureSurfaceType::WINDOW; cursor = uses_aura ? media::mojom::CursorCaptureType::MOTION : media::mojom::CursorCaptureType::ALWAYS; break; case content::DesktopMediaID::TYPE_WEB_CONTENTS: display_surface = media::mojom::DisplayCaptureSurfaceType::BROWSER; cursor = media::mojom::CursorCaptureType::MOTION; capture_handle = CreateCaptureHandle(capturer, capturer_origin, media_id); break; case content::DesktopMediaID::TYPE_NONE: break; } return media::mojom::DisplayMediaInformation::New( display_surface, logical_surface, cursor, std::move(capture_handle)); } // Convert string to lower case and escape it. std::string MakePartitionName(const std::string& input) { return base::EscapePath(base::ToLowerASCII(input)); } } // namespace // static ElectronBrowserContext::BrowserContextMap& ElectronBrowserContext::browser_context_map() { static base::NoDestructor<ElectronBrowserContext::BrowserContextMap> browser_context_map; return *browser_context_map; } ElectronBrowserContext::ElectronBrowserContext( const PartitionOrPath partition_location, bool in_memory, base::Value::Dict options) : in_memory_pref_store_(new ValueMapPrefStore), storage_policy_(base::MakeRefCounted<SpecialStoragePolicy>()), protocol_registry_(base::WrapUnique(new ProtocolRegistry)), in_memory_(in_memory), ssl_config_(network::mojom::SSLConfig::New()) { // Read options. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); use_cache_ = !command_line->HasSwitch(switches::kDisableHttpCache); if (auto use_cache_opt = options.FindBool("cache")) { use_cache_ = use_cache_opt.value(); } base::StringToInt(command_line->GetSwitchValueASCII(switches::kDiskCacheSize), &max_cache_size_); if (auto* path_value = std::get_if<std::reference_wrapper<const std::string>>( &partition_location)) { base::PathService::Get(DIR_SESSION_DATA, &path_); const std::string& partition_loc = path_value->get(); if (!in_memory && !partition_loc.empty()) { path_ = path_.Append(FILE_PATH_LITERAL("Partitions")) .Append(base::FilePath::FromUTF8Unsafe( MakePartitionName(partition_loc))); } } else if (auto* filepath_partition = std::get_if<std::reference_wrapper<const base::FilePath>>( &partition_location)) { const base::FilePath& partition_path = filepath_partition->get(); path_ = std::move(partition_path); } BrowserContextDependencyManager::GetInstance()->MarkBrowserContextLive(this); // Initialize Pref Registry. InitPrefs(); cookie_change_notifier_ = std::make_unique<CookieChangeNotifier>(this); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServices(this); extension_system_ = static_cast<extensions::ElectronExtensionSystem*>( extensions::ExtensionSystem::Get(this)); extension_system_->InitForRegularProfile(true /* extensions_enabled */); extension_system_->FinishInitialization(); } #endif } ElectronBrowserContext::~ElectronBrowserContext() { DCHECK_CURRENTLY_ON(BrowserThread::UI); NotifyWillBeDestroyed(); // Notify any keyed services of browser context destruction. BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices( this); ShutdownStoragePartitions(); BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, std::move(resource_context_)); } void ElectronBrowserContext::InitPrefs() { auto prefs_path = GetPath().Append(FILE_PATH_LITERAL("Preferences")); ScopedAllowBlockingForElectron allow_blocking; PrefServiceFactory prefs_factory; scoped_refptr<JsonPrefStore> pref_store = base::MakeRefCounted<JsonPrefStore>(prefs_path); pref_store->ReadPrefs(); // Synchronous. prefs_factory.set_user_prefs(pref_store); prefs_factory.set_command_line_prefs(in_memory_pref_store()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { auto* ext_pref_store = new ExtensionPrefStore( ExtensionPrefValueMapFactory::GetForBrowserContext(this), IsOffTheRecord()); prefs_factory.set_extension_prefs(ext_pref_store); } #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) auto registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>(); #else auto registry = base::MakeRefCounted<PrefRegistrySimple>(); #endif registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory, base::FilePath()); base::FilePath download_dir; base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_dir); registry->RegisterFilePathPref(prefs::kDownloadDefaultDirectory, download_dir); registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths); InspectableWebContents::RegisterPrefs(registry.get()); MediaDeviceIDSalt::RegisterPrefs(registry.get()); ZoomLevelDelegate::RegisterPrefs(registry.get()); PrefProxyConfigTrackerImpl::RegisterPrefs(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) extensions::ExtensionPrefs::RegisterProfilePrefs(registry.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) BrowserContextDependencyManager::GetInstance() ->RegisterProfilePrefsForServices(registry.get()); language::LanguagePrefs::RegisterProfilePrefs(registry.get()); #endif prefs_ = prefs_factory.Create(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) user_prefs::UserPrefs::Set(this, prefs_.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) // No configured dictionaries, the default will be en-US if (prefs()->GetList(spellcheck::prefs::kSpellCheckDictionaries).empty()) { std::string default_code = spellcheck::GetCorrespondingSpellCheckLanguage( base::i18n::GetConfiguredLocale()); if (!default_code.empty()) { base::Value::List language_codes; language_codes.Append(default_code); prefs()->Set(spellcheck::prefs::kSpellCheckDictionaries, base::Value(std::move(language_codes))); } } #endif } void ElectronBrowserContext::SetUserAgent(const std::string& user_agent) { user_agent_ = user_agent; } base::FilePath ElectronBrowserContext::GetPath() { return path_; } bool ElectronBrowserContext::IsOffTheRecord() { return in_memory_; } bool ElectronBrowserContext::CanUseHttpCache() const { return use_cache_; } int ElectronBrowserContext::GetMaxCacheSize() const { return max_cache_size_; } content::ResourceContext* ElectronBrowserContext::GetResourceContext() { if (!resource_context_) resource_context_ = std::make_unique<content::ResourceContext>(); return resource_context_.get(); } std::string ElectronBrowserContext::GetMediaDeviceIDSalt() { if (!media_device_id_salt_.get()) media_device_id_salt_ = std::make_unique<MediaDeviceIDSalt>(prefs_.get()); return media_device_id_salt_->GetSalt(); } std::unique_ptr<content::ZoomLevelDelegate> ElectronBrowserContext::CreateZoomLevelDelegate( const base::FilePath& partition_path) { if (!IsOffTheRecord()) { return std::make_unique<ZoomLevelDelegate>(prefs(), partition_path); } return std::unique_ptr<content::ZoomLevelDelegate>(); } content::DownloadManagerDelegate* ElectronBrowserContext::GetDownloadManagerDelegate() { if (!download_manager_delegate_.get()) { auto* download_manager = this->GetDownloadManager(); download_manager_delegate_ = std::make_unique<ElectronDownloadManagerDelegate>(download_manager); } return download_manager_delegate_.get(); } content::BrowserPluginGuestManager* ElectronBrowserContext::GetGuestManager() { if (!guest_manager_) guest_manager_ = std::make_unique<WebViewManager>(); return guest_manager_.get(); } content::PlatformNotificationService* ElectronBrowserContext::GetPlatformNotificationService() { return ElectronBrowserClient::Get()->GetPlatformNotificationService(); } content::PermissionControllerDelegate* ElectronBrowserContext::GetPermissionControllerDelegate() { if (!permission_manager_.get()) permission_manager_ = std::make_unique<ElectronPermissionManager>(); return permission_manager_.get(); } storage::SpecialStoragePolicy* ElectronBrowserContext::GetSpecialStoragePolicy() { return storage_policy_.get(); } std::string ElectronBrowserContext::GetUserAgent() const { return user_agent_.value_or(ElectronBrowserClient::Get()->GetUserAgent()); } predictors::PreconnectManager* ElectronBrowserContext::GetPreconnectManager() { if (!preconnect_manager_.get()) { preconnect_manager_ = std::make_unique<predictors::PreconnectManager>(nullptr, this); } return preconnect_manager_.get(); } scoped_refptr<network::SharedURLLoaderFactory> ElectronBrowserContext::GetURLLoaderFactory() { if (url_loader_factory_) return url_loader_factory_; mojo::PendingRemote<network::mojom::URLLoaderFactory> network_factory_remote; mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver = network_factory_remote.InitWithNewPipeAndPassReceiver(); // Consult the embedder. mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient> header_client; static_cast<content::ContentBrowserClient*>(ElectronBrowserClient::Get()) ->WillCreateURLLoaderFactory( this, nullptr, -1, content::ContentBrowserClient::URLLoaderFactoryType::kNavigation, url::Origin(), absl::nullopt, ukm::kInvalidSourceIdObj, &factory_receiver, &header_client, nullptr, nullptr, nullptr, nullptr); network::mojom::URLLoaderFactoryParamsPtr params = network::mojom::URLLoaderFactoryParams::New(); params->header_client = std::move(header_client); params->process_id = network::mojom::kBrowserProcessId; params->is_trusted = true; params->is_corb_enabled = false; // The tests of net module would fail if this setting is true, it seems that // the non-NetworkService implementation always has web security enabled. params->disable_web_security = false; auto* storage_partition = GetDefaultStoragePartition(); storage_partition->GetNetworkContext()->CreateURLLoaderFactory( std::move(factory_receiver), std::move(params)); url_loader_factory_ = base::MakeRefCounted<network::WrapperSharedURLLoaderFactory>( std::move(network_factory_remote)); return url_loader_factory_; } content::PushMessagingService* ElectronBrowserContext::GetPushMessagingService() { return nullptr; } content::SSLHostStateDelegate* ElectronBrowserContext::GetSSLHostStateDelegate() { return nullptr; } content::BackgroundFetchDelegate* ElectronBrowserContext::GetBackgroundFetchDelegate() { return nullptr; } content::BackgroundSyncController* ElectronBrowserContext::GetBackgroundSyncController() { return nullptr; } content::BrowsingDataRemoverDelegate* ElectronBrowserContext::GetBrowsingDataRemoverDelegate() { return nullptr; } content::ClientHintsControllerDelegate* ElectronBrowserContext::GetClientHintsControllerDelegate() { return nullptr; } content::StorageNotificationService* ElectronBrowserContext::GetStorageNotificationService() { return nullptr; } content::ReduceAcceptLanguageControllerDelegate* ElectronBrowserContext::GetReduceAcceptLanguageControllerDelegate() { // Needs implementation // Refs https://chromium-review.googlesource.com/c/chromium/src/+/3687391 return nullptr; } ResolveProxyHelper* ElectronBrowserContext::GetResolveProxyHelper() { if (!resolve_proxy_helper_) { resolve_proxy_helper_ = base::MakeRefCounted<ResolveProxyHelper>(this); } return resolve_proxy_helper_.get(); } network::mojom::SSLConfigPtr ElectronBrowserContext::GetSSLConfig() { return ssl_config_.Clone(); } void ElectronBrowserContext::SetSSLConfig(network::mojom::SSLConfigPtr config) { ssl_config_ = std::move(config); if (ssl_config_client_) { ssl_config_client_->OnSSLConfigUpdated(ssl_config_.Clone()); } } void ElectronBrowserContext::SetSSLConfigClient( mojo::Remote<network::mojom::SSLConfigClient> client) { ssl_config_client_ = std::move(client); } void ElectronBrowserContext::SetDisplayMediaRequestHandler( DisplayMediaRequestHandler handler) { display_media_request_handler_ = handler; } void ElectronBrowserContext::DisplayMediaDeviceChosen( const content::MediaStreamRequest& request, content::MediaResponseCallback callback, gin::Arguments* args) { blink::mojom::StreamDevicesSetPtr stream_devices_set = blink::mojom::StreamDevicesSet::New(); v8::Local<v8::Value> result; if (!args->GetNext(&result) || result->IsNullOrUndefined()) { std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } gin_helper::Dictionary result_dict; if (!gin::ConvertFromV8(args->isolate(), result, &result_dict)) { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "Display Media Request streams callback must be called with null " "or a valid object"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } stream_devices_set->stream_devices.emplace_back( blink::mojom::StreamDevices::New()); blink::mojom::StreamDevices& devices = *stream_devices_set->stream_devices[0]; bool video_requested = request.video_type != blink::mojom::MediaStreamType::NO_SERVICE; bool audio_requested = request.audio_type != blink::mojom::MediaStreamType::NO_SERVICE; bool has_video = false; if (video_requested && result_dict.Has("video")) { gin_helper::Dictionary video_dict; std::string id; std::string name; content::RenderFrameHost* rfh; if (result_dict.Get("video", &video_dict) && video_dict.Get("id", &id) && video_dict.Get("name", &name)) { blink::MediaStreamDevice video_device(request.video_type, id, name); video_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( nullptr, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(video_device.id)); devices.video_device = video_device; } else if (result_dict.Get("video", &rfh)) { auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); blink::MediaStreamDevice video_device( request.video_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID()) .ToString(), base::UTF16ToUTF8(web_contents->GetTitle())); video_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( web_contents, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(video_device.id)); devices.video_device = video_device; } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "video must be a WebFrameMain or DesktopCapturerSource"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } has_video = true; } if (audio_requested && result_dict.Has("audio")) { gin_helper::Dictionary audio_dict; std::string id; std::string name; content::RenderFrameHost* rfh; // NB. this is not permitted by the documentation, but is left here as an // "escape hatch" for providing an arbitrary name/id if needed in the // future. if (result_dict.Get("audio", &audio_dict) && audio_dict.Get("id", &id) && audio_dict.Get("name", &name)) { blink::MediaStreamDevice audio_device(request.audio_type, id, name); audio_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( nullptr, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(request.requested_audio_device_id)); devices.audio_device = audio_device; } else if (result_dict.Get("audio", &rfh)) { bool enable_local_echo = false; result_dict.Get("enableLocalEcho", &enable_local_echo); bool disable_local_echo = !enable_local_echo; auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); blink::MediaStreamDevice audio_device( request.audio_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID(), disable_local_echo) .ToString(), "Tab audio"); audio_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( web_contents, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(request.requested_audio_device_id)); devices.audio_device = audio_device; } else if (result_dict.Get("audio", &id)) { blink::MediaStreamDevice audio_device(request.audio_type, id, "System audio"); audio_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( nullptr, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(request.requested_audio_device_id)); devices.audio_device = audio_device; } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "audio must be a WebFrameMain, \"loopback\" or " "\"loopbackWithMute\""); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } } if ((video_requested && !has_video)) { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "Video was requested, but no video stream was provided"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } std::move(callback).Run(*stream_devices_set, blink::mojom::MediaStreamRequestResult::OK, nullptr); } bool ElectronBrowserContext::ChooseDisplayMediaDevice( const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { if (!display_media_request_handler_) return false; DisplayMediaResponseCallbackJs callbackJs = base::BindOnce(&DisplayMediaDeviceChosen, request, std::move(callback)); display_media_request_handler_.Run(request, std::move(callbackJs)); return true; } void ElectronBrowserContext::GrantDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { granted_devices_[permission_type][origin].push_back( std::make_unique<base::Value>(device.Clone())); } void ElectronBrowserContext::RevokeDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return; for (auto it = origin_devices_it->second.begin(); it != origin_devices_it->second.end();) { if (DoesDeviceMatch(device, it->get(), permission_type)) { it = origin_devices_it->second.erase(it); } else { ++it; } } } bool ElectronBrowserContext::DoesDeviceMatch( const base::Value& device, const base::Value* device_to_compare, blink::PermissionType permission_type) { if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::HID) || permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::USB)) { if (device.GetDict().FindInt(kDeviceVendorIdKey) != device_to_compare->GetDict().FindInt(kDeviceVendorIdKey) || device.GetDict().FindInt(kDeviceProductIdKey) != device_to_compare->GetDict().FindInt(kDeviceProductIdKey)) { return false; } const auto* serial_number = device_to_compare->GetDict().FindString(kDeviceSerialNumberKey); const auto* device_serial_number = device.GetDict().FindString(kDeviceSerialNumberKey); if (serial_number && device_serial_number && *device_serial_number == *serial_number) return true; } else if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL)) { #if BUILDFLAG(IS_WIN) const auto* instance_id = device.GetDict().FindString(kDeviceInstanceIdKey); const auto* port_instance_id = device_to_compare->GetDict().FindString(kDeviceInstanceIdKey); if (instance_id && port_instance_id && *instance_id == *port_instance_id) return true; #else const auto* serial_number = device.GetDict().FindString(kSerialNumberKey); const auto* port_serial_number = device_to_compare->GetDict().FindString(kSerialNumberKey); if (device.GetDict().FindInt(kVendorIdKey) != device_to_compare->GetDict().FindInt(kVendorIdKey) || device.GetDict().FindInt(kProductIdKey) != device_to_compare->GetDict().FindInt(kProductIdKey) || (serial_number && port_serial_number && *port_serial_number != *serial_number)) { return false; } #if BUILDFLAG(IS_MAC) const auto* usb_driver_key = device.GetDict().FindString(kUsbDriverKey); const auto* port_usb_driver_key = device_to_compare->GetDict().FindString(kUsbDriverKey); if (usb_driver_key && port_usb_driver_key && *usb_driver_key != *port_usb_driver_key) { return false; } #endif // BUILDFLAG(IS_MAC) return true; #endif // BUILDFLAG(IS_WIN) } return false; } bool ElectronBrowserContext::CheckDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return false; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return false; for (const auto& device_to_compare : origin_devices_it->second) { if (DoesDeviceMatch(device, device_to_compare.get(), permission_type)) return true; } return false; } // static ElectronBrowserContext* ElectronBrowserContext::From( const std::string& partition, bool in_memory, base::Value::Dict options) { PartitionKey key(partition, in_memory); ElectronBrowserContext* browser_context = browser_context_map()[key].get(); if (browser_context) { return browser_context; } auto* new_context = new ElectronBrowserContext(std::cref(partition), in_memory, std::move(options)); browser_context_map()[key] = std::unique_ptr<ElectronBrowserContext>(new_context); return new_context; } ElectronBrowserContext* ElectronBrowserContext::FromPath( const base::FilePath& path, base::Value::Dict options) { PartitionKey key(path); ElectronBrowserContext* browser_context = browser_context_map()[key].get(); if (browser_context) { return browser_context; } auto* new_context = new ElectronBrowserContext(std::cref(path), false, std::move(options)); browser_context_map()[key] = std::unique_ptr<ElectronBrowserContext>(new_context); return new_context; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,439
Convert legacy IPC calls in extensions code to use mojo
https://chromium-review.googlesource.com/c/chromium/src/+/4995136 turned on the build flag to use the new mojo IPC pipe for messaging in extensions. In #40418 we turned this off because we have not converted our extensions code to use mojo. It appears that in chromium the follow CLs were landed to use mojo in extensions: - 4947890: [extensions] Convert Extension Messaging APIs over to mojo | https://chromium-review.googlesource.com/c/chromium/src/+/4947890 - 4950041: [extensions] Port Event Acks to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4950041 - 4902564: [extensions] Move WakeEventPage to mojom::RendererHost | https://chromium-review.googlesource.com/c/chromium/src/+/4902564 - 4956841: [extensions] Port GetMessageBundle over to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4956841 Once these changes have landed, the following flag override in build/args/all.gn should be removed: `enable_extensions_legacy_ipc = true`
https://github.com/electron/electron/issues/40439
https://github.com/electron/electron/pull/40511
088affd4a4311e03b8ed400cdf5d82f1db2125a4
371bca69b69351dc47d4b4dcfdf9a626f43b3b51
2023-11-02T18:50:40Z
c++
2023-11-15T14:30:47Z
shell/browser/extensions/electron_extension_message_filter.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/extensions/electron_extension_message_filter.h" #include <stdint.h> #include <memory> #include "base/files/file_path.h" #include "base/functional/bind.h" #include "base/functional/callback_helpers.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "base/task/thread_pool.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/render_process_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/l10n_file_util.h" #include "extensions/common/extension_messages.h" #include "extensions/common/extension_set.h" #include "extensions/common/manifest_handlers/default_locale_handler.h" #include "extensions/common/manifest_handlers/shared_module_info.h" #include "extensions/common/message_bundle.h" using content::BrowserThread; namespace electron { const uint32_t kExtensionFilteredMessageClasses[] = { ExtensionMsgStart, }; ElectronExtensionMessageFilter::ElectronExtensionMessageFilter( int render_process_id, content::BrowserContext* browser_context) : BrowserMessageFilter(kExtensionFilteredMessageClasses, std::size(kExtensionFilteredMessageClasses)), render_process_id_(render_process_id), browser_context_(browser_context) { DCHECK_CURRENTLY_ON(BrowserThread::UI); } ElectronExtensionMessageFilter::~ElectronExtensionMessageFilter() { DCHECK_CURRENTLY_ON(BrowserThread::UI); } bool ElectronExtensionMessageFilter::OnMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(ElectronExtensionMessageFilter, message) IPC_MESSAGE_HANDLER_DELAY_REPLY(ExtensionHostMsg_GetMessageBundle, OnGetExtMessageBundle) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void ElectronExtensionMessageFilter::OverrideThreadForMessage( const IPC::Message& message, BrowserThread::ID* thread) { switch (message.type()) { case ExtensionHostMsg_GetMessageBundle::ID: *thread = BrowserThread::UI; break; default: break; } } void ElectronExtensionMessageFilter::OnDestruct() const { if (BrowserThread::CurrentlyOn(BrowserThread::UI)) { delete this; } else { content::GetUIThreadTaskRunner({})->DeleteSoon(FROM_HERE, this); } } void ElectronExtensionMessageFilter::OnGetExtMessageBundle( const std::string& extension_id, IPC::Message* reply_msg) { DCHECK_CURRENTLY_ON(BrowserThread::UI); const extensions::ExtensionSet& extension_set = extensions::ExtensionRegistry::Get(browser_context_) ->enabled_extensions(); const extensions::Extension* extension = extension_set.GetByID(extension_id); if (!extension) { // The extension has gone. ExtensionHostMsg_GetMessageBundle::WriteReplyParams( reply_msg, extensions::MessageBundle::SubstitutionMap()); Send(reply_msg); return; } const std::string& default_locale = extensions::LocaleInfo::GetDefaultLocale(extension); if (default_locale.empty()) { // A little optimization: send the answer here to avoid an extra thread hop. std::unique_ptr<extensions::MessageBundle::SubstitutionMap> dictionary_map( extensions::l10n_file_util:: LoadNonLocalizedMessageBundleSubstitutionMap(extension_id)); ExtensionHostMsg_GetMessageBundle::WriteReplyParams(reply_msg, *dictionary_map); Send(reply_msg); return; } std::vector<base::FilePath> paths_to_load; paths_to_load.push_back(extension->path()); auto imports = extensions::SharedModuleInfo::GetImports(extension); // Iterate through the imports in reverse. This will allow later imported // modules to override earlier imported modules, as the list order is // maintained from the definition in manifest.json of the imports. for (auto it = imports.rbegin(); it != imports.rend(); ++it) { const extensions::Extension* imported_extension = extension_set.GetByID(it->extension_id); if (!imported_extension) { NOTREACHED() << "Missing shared module " << it->extension_id; continue; } paths_to_load.push_back(imported_extension->path()); } // This blocks tab loading. Priority is inherited from the calling context. base::ThreadPool::PostTask( FROM_HERE, {base::MayBlock()}, base::BindOnce( &ElectronExtensionMessageFilter::OnGetExtMessageBundleAsync, this, paths_to_load, extension_id, default_locale, extension_l10n_util::GetGzippedMessagesPermissionForExtension( extension), reply_msg)); } void ElectronExtensionMessageFilter::OnGetExtMessageBundleAsync( const std::vector<base::FilePath>& extension_paths, const std::string& main_extension_id, const std::string& default_locale, extension_l10n_util::GzippedMessagesPermission gzip_permission, IPC::Message* reply_msg) { std::unique_ptr<extensions::MessageBundle::SubstitutionMap> dictionary_map( extensions::l10n_file_util::LoadMessageBundleSubstitutionMapFromPaths( extension_paths, main_extension_id, default_locale, gzip_permission)); ExtensionHostMsg_GetMessageBundle::WriteReplyParams(reply_msg, *dictionary_map); Send(reply_msg); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,439
Convert legacy IPC calls in extensions code to use mojo
https://chromium-review.googlesource.com/c/chromium/src/+/4995136 turned on the build flag to use the new mojo IPC pipe for messaging in extensions. In #40418 we turned this off because we have not converted our extensions code to use mojo. It appears that in chromium the follow CLs were landed to use mojo in extensions: - 4947890: [extensions] Convert Extension Messaging APIs over to mojo | https://chromium-review.googlesource.com/c/chromium/src/+/4947890 - 4950041: [extensions] Port Event Acks to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4950041 - 4902564: [extensions] Move WakeEventPage to mojom::RendererHost | https://chromium-review.googlesource.com/c/chromium/src/+/4902564 - 4956841: [extensions] Port GetMessageBundle over to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4956841 Once these changes have landed, the following flag override in build/args/all.gn should be removed: `enable_extensions_legacy_ipc = true`
https://github.com/electron/electron/issues/40439
https://github.com/electron/electron/pull/40511
088affd4a4311e03b8ed400cdf5d82f1db2125a4
371bca69b69351dc47d4b4dcfdf9a626f43b3b51
2023-11-02T18:50:40Z
c++
2023-11-15T14:30:47Z
shell/browser/extensions/electron_extension_message_filter.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_EXTENSIONS_ELECTRON_EXTENSION_MESSAGE_FILTER_H_ #define ELECTRON_SHELL_BROWSER_EXTENSIONS_ELECTRON_EXTENSION_MESSAGE_FILTER_H_ #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "base/task/sequenced_task_runner_helpers.h" #include "content/public/browser/browser_message_filter.h" #include "content/public/browser/browser_thread.h" #include "extensions/common/extension_l10n_util.h" namespace content { class BrowserContext; } namespace extensions { struct Message; } namespace electron { // This class filters out incoming Electron-specific IPC messages from the // extension process on the IPC thread. class ElectronExtensionMessageFilter : public content::BrowserMessageFilter { public: ElectronExtensionMessageFilter(int render_process_id, content::BrowserContext* browser_context); // disable copy ElectronExtensionMessageFilter(const ElectronExtensionMessageFilter&) = delete; ElectronExtensionMessageFilter& operator=( const ElectronExtensionMessageFilter&) = delete; // content::BrowserMessageFilter methods: bool OnMessageReceived(const IPC::Message& message) override; void OverrideThreadForMessage(const IPC::Message& message, content::BrowserThread::ID* thread) override; void OnDestruct() const override; private: friend class content::BrowserThread; friend class base::DeleteHelper<ElectronExtensionMessageFilter>; ~ElectronExtensionMessageFilter() override; void OnGetExtMessageBundle(const std::string& extension_id, IPC::Message* reply_msg); void OnGetExtMessageBundleAsync( const std::vector<base::FilePath>& extension_paths, const std::string& main_extension_id, const std::string& default_locale, extension_l10n_util::GzippedMessagesPermission gzip_permission, IPC::Message* reply_msg); const int render_process_id_; // The BrowserContext associated with our renderer process. This should only // be accessed on the UI thread! Furthermore since this class is refcounted it // may outlive |browser_context_|, so make sure to nullptr check if in doubt; // async calls and the like. raw_ptr<content::BrowserContext> browser_context_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_EXTENSIONS_ELECTRON_EXTENSION_MESSAGE_FILTER_H_
closed
electron/electron
https://github.com/electron/electron
40,439
Convert legacy IPC calls in extensions code to use mojo
https://chromium-review.googlesource.com/c/chromium/src/+/4995136 turned on the build flag to use the new mojo IPC pipe for messaging in extensions. In #40418 we turned this off because we have not converted our extensions code to use mojo. It appears that in chromium the follow CLs were landed to use mojo in extensions: - 4947890: [extensions] Convert Extension Messaging APIs over to mojo | https://chromium-review.googlesource.com/c/chromium/src/+/4947890 - 4950041: [extensions] Port Event Acks to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4950041 - 4902564: [extensions] Move WakeEventPage to mojom::RendererHost | https://chromium-review.googlesource.com/c/chromium/src/+/4902564 - 4956841: [extensions] Port GetMessageBundle over to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4956841 Once these changes have landed, the following flag override in build/args/all.gn should be removed: `enable_extensions_legacy_ipc = true`
https://github.com/electron/electron/issues/40439
https://github.com/electron/electron/pull/40511
088affd4a4311e03b8ed400cdf5d82f1db2125a4
371bca69b69351dc47d4b4dcfdf9a626f43b3b51
2023-11-02T18:50:40Z
c++
2023-11-15T14:30:47Z
build/args/all.gn
is_electron_build = true root_extra_deps = [ "//electron" ] # Registry of NMVs --> https://github.com/nodejs/node/blob/main/doc/abi_version_registry.json node_module_version = 119 v8_promise_internal_field_count = 1 v8_embedder_string = "-electron.0" # TODO: this breaks mksnapshot v8_enable_snapshot_native_code_counters = false # we use this api v8_enable_javascript_promise_hooks = true enable_cdm_host_verification = false proprietary_codecs = true ffmpeg_branding = "Chrome" enable_printing = true # Removes DLLs from the build, which are only meant to be used for Chromium development. # See https://github.com/electron/electron/pull/17985 angle_enable_vulkan_validation_layers = false dawn_enable_vulkan_validation_layers = false # These are disabled because they cause the zip manifest to differ between # testing and release builds. # See https://chromium-review.googlesource.com/c/chromium/src/+/2774898. enable_pseudolocales = false # Make application name configurable at runtime for cookie crypto allow_runtime_configurable_key_storage = true # CET shadow stack is incompatible with v8, until v8 is CET compliant # enabling this flag causes main process crashes where CET is enabled # Ref: https://source.chromium.org/chromium/chromium/src/+/45fba672185aae233e75d6ddc81ea1e0b30db050:v8/BUILD.gn;l=357 enable_cet_shadow_stack = false # For similar reasons, disable CFI, which is not well supported in V8. # Chromium doesn't have any problems with this because they do not run # V8 in the browser process. # Ref: https://source.chromium.org/chromium/chromium/src/+/45fba672185aae233e75d6ddc81ea1e0b30db050:v8/BUILD.gn;l=281 is_cfi = false # TODO: fix this once sysroots have been updated. use_qt = false # https://chromium-review.googlesource.com/c/chromium/src/+/4365718 # TODO(codebytere): fix perfetto incompatibility with Node.js. use_perfetto_client_library = false # Disables the builtins PGO for V8 v8_builtins_profiling_log_file = "" # https://chromium.googlesource.com/chromium/src/+/main/docs/dangling_ptr.md # TODO(vertedinde): hunt down dangling pointers on Linux enable_dangling_raw_ptr_checks = false # This flag speeds up the performance of fork/execve on linux systems. # Ref: https://chromium-review.googlesource.com/c/v8/v8/+/4602858 v8_enable_private_mapping_fork_optimization = true # https://chromium-review.googlesource.com/c/chromium/src/+/4995136 # TODO(jkleinsc): convert legacy IPC calls in extensions to use mojo # https://github.com/electron/electron/issues/40439 enable_extensions_legacy_ipc = true
closed
electron/electron
https://github.com/electron/electron
40,439
Convert legacy IPC calls in extensions code to use mojo
https://chromium-review.googlesource.com/c/chromium/src/+/4995136 turned on the build flag to use the new mojo IPC pipe for messaging in extensions. In #40418 we turned this off because we have not converted our extensions code to use mojo. It appears that in chromium the follow CLs were landed to use mojo in extensions: - 4947890: [extensions] Convert Extension Messaging APIs over to mojo | https://chromium-review.googlesource.com/c/chromium/src/+/4947890 - 4950041: [extensions] Port Event Acks to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4950041 - 4902564: [extensions] Move WakeEventPage to mojom::RendererHost | https://chromium-review.googlesource.com/c/chromium/src/+/4902564 - 4956841: [extensions] Port GetMessageBundle over to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4956841 Once these changes have landed, the following flag override in build/args/all.gn should be removed: `enable_extensions_legacy_ipc = true`
https://github.com/electron/electron/issues/40439
https://github.com/electron/electron/pull/40511
088affd4a4311e03b8ed400cdf5d82f1db2125a4
371bca69b69351dc47d4b4dcfdf9a626f43b3b51
2023-11-02T18:50:40Z
c++
2023-11-15T14:30:47Z
filenames.gni
filenames = { default_app_ts_sources = [ "default_app/default_app.ts", "default_app/main.ts", "default_app/preload.ts", ] default_app_static_sources = [ "default_app/icon.png", "default_app/index.html", "default_app/package.json", "default_app/styles.css", ] default_app_octicon_sources = [ "node_modules/@primer/octicons/build/build.css", "node_modules/@primer/octicons/build/svg/book-24.svg", "node_modules/@primer/octicons/build/svg/code-square-24.svg", "node_modules/@primer/octicons/build/svg/gift-24.svg", "node_modules/@primer/octicons/build/svg/mark-github-16.svg", "node_modules/@primer/octicons/build/svg/star-fill-24.svg", ] lib_sources_linux = [ "shell/browser/browser_linux.cc", "shell/browser/electron_browser_main_parts_linux.cc", "shell/browser/lib/power_observer_linux.cc", "shell/browser/lib/power_observer_linux.h", "shell/browser/linux/unity_service.cc", "shell/browser/linux/unity_service.h", "shell/browser/notifications/linux/libnotify_notification.cc", "shell/browser/notifications/linux/libnotify_notification.h", "shell/browser/notifications/linux/notification_presenter_linux.cc", "shell/browser/notifications/linux/notification_presenter_linux.h", "shell/browser/relauncher_linux.cc", "shell/browser/ui/electron_desktop_window_tree_host_linux.cc", "shell/browser/ui/file_dialog_gtk.cc", "shell/browser/ui/gtk/menu_gtk.cc", "shell/browser/ui/gtk/menu_gtk.h", "shell/browser/ui/gtk/menu_util.cc", "shell/browser/ui/gtk/menu_util.h", "shell/browser/ui/message_box_gtk.cc", "shell/browser/ui/status_icon_gtk.cc", "shell/browser/ui/status_icon_gtk.h", "shell/browser/ui/tray_icon_linux.cc", "shell/browser/ui/tray_icon_linux.h", "shell/browser/ui/views/client_frame_view_linux.cc", "shell/browser/ui/views/client_frame_view_linux.h", "shell/common/application_info_linux.cc", "shell/common/language_util_linux.cc", "shell/common/node_bindings_linux.cc", "shell/common/node_bindings_linux.h", "shell/common/platform_util_linux.cc", ] lib_sources_linux_x11 = [ "shell/browser/ui/views/global_menu_bar_registrar_x11.cc", "shell/browser/ui/views/global_menu_bar_registrar_x11.h", "shell/browser/ui/views/global_menu_bar_x11.cc", "shell/browser/ui/views/global_menu_bar_x11.h", "shell/browser/ui/x/event_disabler.cc", "shell/browser/ui/x/event_disabler.h", "shell/browser/ui/x/x_window_utils.cc", "shell/browser/ui/x/x_window_utils.h", ] lib_sources_posix = [ "shell/browser/electron_browser_main_parts_posix.cc" ] lib_sources_win = [ "shell/browser/api/electron_api_power_monitor_win.cc", "shell/browser/api/electron_api_system_preferences_win.cc", "shell/browser/browser_win.cc", "shell/browser/native_window_views_win.cc", "shell/browser/notifications/win/notification_presenter_win.cc", "shell/browser/notifications/win/notification_presenter_win.h", "shell/browser/notifications/win/windows_toast_notification.cc", "shell/browser/notifications/win/windows_toast_notification.h", "shell/browser/relauncher_win.cc", "shell/browser/ui/certificate_trust_win.cc", "shell/browser/ui/file_dialog_win.cc", "shell/browser/ui/message_box_win.cc", "shell/browser/ui/tray_icon_win.cc", "shell/browser/ui/views/electron_views_delegate_win.cc", "shell/browser/ui/views/win_icon_painter.cc", "shell/browser/ui/views/win_icon_painter.h", "shell/browser/ui/views/win_frame_view.cc", "shell/browser/ui/views/win_frame_view.h", "shell/browser/ui/views/win_caption_button.cc", "shell/browser/ui/views/win_caption_button.h", "shell/browser/ui/views/win_caption_button_container.cc", "shell/browser/ui/views/win_caption_button_container.h", "shell/browser/ui/win/dialog_thread.cc", "shell/browser/ui/win/dialog_thread.h", "shell/browser/ui/win/electron_desktop_native_widget_aura.cc", "shell/browser/ui/win/electron_desktop_native_widget_aura.h", "shell/browser/ui/win/electron_desktop_window_tree_host_win.cc", "shell/browser/ui/win/electron_desktop_window_tree_host_win.h", "shell/browser/ui/win/jump_list.cc", "shell/browser/ui/win/jump_list.h", "shell/browser/ui/win/notify_icon_host.cc", "shell/browser/ui/win/notify_icon_host.h", "shell/browser/ui/win/notify_icon.cc", "shell/browser/ui/win/notify_icon.h", "shell/browser/ui/win/taskbar_host.cc", "shell/browser/ui/win/taskbar_host.h", "shell/browser/win/dark_mode.cc", "shell/browser/win/dark_mode.h", "shell/browser/win/scoped_hstring.cc", "shell/browser/win/scoped_hstring.h", "shell/common/api/electron_api_native_image_win.cc", "shell/common/application_info_win.cc", "shell/common/language_util_win.cc", "shell/common/node_bindings_win.cc", "shell/common/node_bindings_win.h", "shell/common/platform_util_win.cc", ] lib_sources_mac = [ "shell/app/electron_main_delegate_mac.h", "shell/app/electron_main_delegate_mac.mm", "shell/browser/api/electron_api_app_mac.mm", "shell/browser/api/electron_api_menu_mac.h", "shell/browser/api/electron_api_menu_mac.mm", "shell/browser/api/electron_api_native_theme_mac.mm", "shell/browser/api/electron_api_power_monitor_mac.mm", "shell/browser/api/electron_api_push_notifications_mac.mm", "shell/browser/api/electron_api_system_preferences_mac.mm", "shell/browser/api/electron_api_web_contents_mac.mm", "shell/browser/auto_updater_mac.mm", "shell/browser/browser_mac.mm", "shell/browser/electron_browser_main_parts_mac.mm", "shell/browser/mac/dict_util.h", "shell/browser/mac/dict_util.mm", "shell/browser/mac/electron_application.h", "shell/browser/mac/electron_application.mm", "shell/browser/mac/electron_application_delegate.h", "shell/browser/mac/electron_application_delegate.mm", "shell/browser/mac/in_app_purchase_observer.h", "shell/browser/mac/in_app_purchase_observer.mm", "shell/browser/mac/in_app_purchase_product.h", "shell/browser/mac/in_app_purchase_product.mm", "shell/browser/mac/in_app_purchase.h", "shell/browser/mac/in_app_purchase.mm", "shell/browser/native_browser_view_mac.h", "shell/browser/native_browser_view_mac.mm", "shell/browser/native_window_mac.h", "shell/browser/native_window_mac.mm", "shell/browser/notifications/mac/cocoa_notification.h", "shell/browser/notifications/mac/cocoa_notification.mm", "shell/browser/notifications/mac/notification_center_delegate.h", "shell/browser/notifications/mac/notification_center_delegate.mm", "shell/browser/notifications/mac/notification_presenter_mac.h", "shell/browser/notifications/mac/notification_presenter_mac.mm", "shell/browser/osr/osr_host_display_client_mac.mm", "shell/browser/osr/osr_web_contents_view_mac.mm", "shell/browser/relauncher_mac.cc", "shell/browser/ui/certificate_trust_mac.mm", "shell/browser/ui/cocoa/delayed_native_view_host.h", "shell/browser/ui/cocoa/delayed_native_view_host.mm", "shell/browser/ui/cocoa/electron_bundle_mover.h", "shell/browser/ui/cocoa/electron_bundle_mover.mm", "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.h", "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm", "shell/browser/ui/cocoa/electron_menu_controller.h", "shell/browser/ui/cocoa/electron_menu_controller.mm", "shell/browser/ui/cocoa/electron_native_widget_mac.h", "shell/browser/ui/cocoa/electron_native_widget_mac.mm", "shell/browser/ui/cocoa/electron_ns_panel.h", "shell/browser/ui/cocoa/electron_ns_panel.mm", "shell/browser/ui/cocoa/electron_ns_window.h", "shell/browser/ui/cocoa/electron_ns_window.mm", "shell/browser/ui/cocoa/electron_ns_window_delegate.h", "shell/browser/ui/cocoa/electron_ns_window_delegate.mm", "shell/browser/ui/cocoa/electron_preview_item.h", "shell/browser/ui/cocoa/electron_preview_item.mm", "shell/browser/ui/cocoa/electron_touch_bar.h", "shell/browser/ui/cocoa/electron_touch_bar.mm", "shell/browser/ui/cocoa/event_dispatching_window.h", "shell/browser/ui/cocoa/event_dispatching_window.mm", "shell/browser/ui/cocoa/NSString+ANSI.h", "shell/browser/ui/cocoa/NSString+ANSI.mm", "shell/browser/ui/cocoa/root_view_mac.h", "shell/browser/ui/cocoa/root_view_mac.mm", "shell/browser/ui/cocoa/views_delegate_mac.h", "shell/browser/ui/cocoa/views_delegate_mac.mm", "shell/browser/ui/cocoa/window_buttons_proxy.h", "shell/browser/ui/cocoa/window_buttons_proxy.mm", "shell/browser/ui/drag_util_mac.mm", "shell/browser/ui/file_dialog_mac.mm", "shell/browser/ui/inspectable_web_contents_view_mac.h", "shell/browser/ui/inspectable_web_contents_view_mac.mm", "shell/browser/ui/message_box_mac.mm", "shell/browser/ui/tray_icon_cocoa.h", "shell/browser/ui/tray_icon_cocoa.mm", "shell/common/api/electron_api_clipboard_mac.mm", "shell/common/api/electron_api_native_image_mac.mm", "shell/common/asar/archive_mac.mm", "shell/common/application_info_mac.mm", "shell/common/language_util_mac.mm", "shell/common/mac/main_application_bundle.h", "shell/common/mac/main_application_bundle.mm", "shell/common/node_bindings_mac.cc", "shell/common/node_bindings_mac.h", "shell/common/platform_util_mac.mm", ] lib_sources_views = [ "shell/browser/api/electron_api_menu_views.cc", "shell/browser/api/electron_api_menu_views.h", "shell/browser/native_browser_view_views.cc", "shell/browser/native_browser_view_views.h", "shell/browser/native_window_views.cc", "shell/browser/native_window_views.h", "shell/browser/ui/drag_util_views.cc", "shell/browser/ui/views/autofill_popup_view.cc", "shell/browser/ui/views/autofill_popup_view.h", "shell/browser/ui/views/electron_views_delegate.cc", "shell/browser/ui/views/electron_views_delegate.h", "shell/browser/ui/views/frameless_view.cc", "shell/browser/ui/views/frameless_view.h", "shell/browser/ui/views/inspectable_web_contents_view_views.cc", "shell/browser/ui/views/inspectable_web_contents_view_views.h", "shell/browser/ui/views/menu_bar.cc", "shell/browser/ui/views/menu_bar.h", "shell/browser/ui/views/menu_delegate.cc", "shell/browser/ui/views/menu_delegate.h", "shell/browser/ui/views/menu_model_adapter.cc", "shell/browser/ui/views/menu_model_adapter.h", "shell/browser/ui/views/native_frame_view.cc", "shell/browser/ui/views/native_frame_view.h", "shell/browser/ui/views/root_view.cc", "shell/browser/ui/views/root_view.h", "shell/browser/ui/views/submenu_button.cc", "shell/browser/ui/views/submenu_button.h", ] lib_sources = [ "shell/app/command_line_args.cc", "shell/app/command_line_args.h", "shell/app/electron_content_client.cc", "shell/app/electron_content_client.h", "shell/app/electron_crash_reporter_client.cc", "shell/app/electron_crash_reporter_client.h", "shell/app/electron_main_delegate.cc", "shell/app/electron_main_delegate.h", "shell/app/node_main.cc", "shell/app/node_main.h", "shell/app/uv_task_runner.cc", "shell/app/uv_task_runner.h", "shell/browser/api/electron_api_app.cc", "shell/browser/api/electron_api_app.h", "shell/browser/api/electron_api_auto_updater.cc", "shell/browser/api/electron_api_auto_updater.h", "shell/browser/api/electron_api_base_window.cc", "shell/browser/api/electron_api_base_window.h", "shell/browser/api/electron_api_browser_view.cc", "shell/browser/api/electron_api_browser_view.h", "shell/browser/api/electron_api_browser_window.cc", "shell/browser/api/electron_api_browser_window.h", "shell/browser/api/electron_api_content_tracing.cc", "shell/browser/api/electron_api_cookies.cc", "shell/browser/api/electron_api_cookies.h", "shell/browser/api/electron_api_crash_reporter.cc", "shell/browser/api/electron_api_crash_reporter.h", "shell/browser/api/electron_api_data_pipe_holder.cc", "shell/browser/api/electron_api_data_pipe_holder.h", "shell/browser/api/electron_api_debugger.cc", "shell/browser/api/electron_api_debugger.h", "shell/browser/api/electron_api_desktop_capturer.cc", "shell/browser/api/electron_api_desktop_capturer.h", "shell/browser/api/electron_api_dialog.cc", "shell/browser/api/electron_api_download_item.cc", "shell/browser/api/electron_api_download_item.h", "shell/browser/api/electron_api_event_emitter.cc", "shell/browser/api/electron_api_event_emitter.h", "shell/browser/api/electron_api_global_shortcut.cc", "shell/browser/api/electron_api_global_shortcut.h", "shell/browser/api/electron_api_in_app_purchase.cc", "shell/browser/api/electron_api_in_app_purchase.h", "shell/browser/api/electron_api_menu.cc", "shell/browser/api/electron_api_menu.h", "shell/browser/api/electron_api_native_theme.cc", "shell/browser/api/electron_api_native_theme.h", "shell/browser/api/electron_api_net.cc", "shell/browser/api/electron_api_net_log.cc", "shell/browser/api/electron_api_net_log.h", "shell/browser/api/electron_api_notification.cc", "shell/browser/api/electron_api_notification.h", "shell/browser/api/electron_api_power_monitor.cc", "shell/browser/api/electron_api_power_monitor.h", "shell/browser/api/electron_api_power_save_blocker.cc", "shell/browser/api/electron_api_power_save_blocker.h", "shell/browser/api/electron_api_printing.cc", "shell/browser/api/electron_api_protocol.cc", "shell/browser/api/electron_api_protocol.h", "shell/browser/api/electron_api_push_notifications.cc", "shell/browser/api/electron_api_push_notifications.h", "shell/browser/api/electron_api_safe_storage.cc", "shell/browser/api/electron_api_safe_storage.h", "shell/browser/api/electron_api_screen.cc", "shell/browser/api/electron_api_screen.h", "shell/browser/api/electron_api_service_worker_context.cc", "shell/browser/api/electron_api_service_worker_context.h", "shell/browser/api/electron_api_session.cc", "shell/browser/api/electron_api_session.h", "shell/browser/api/electron_api_system_preferences.cc", "shell/browser/api/electron_api_system_preferences.h", "shell/browser/api/electron_api_tray.cc", "shell/browser/api/electron_api_tray.h", "shell/browser/api/electron_api_url_loader.cc", "shell/browser/api/electron_api_url_loader.h", "shell/browser/api/electron_api_utility_process.cc", "shell/browser/api/electron_api_utility_process.h", "shell/browser/api/electron_api_view.cc", "shell/browser/api/electron_api_view.h", "shell/browser/api/electron_api_web_contents.cc", "shell/browser/api/electron_api_web_contents.h", "shell/browser/api/electron_api_web_contents_impl.cc", "shell/browser/api/electron_api_web_contents_view.cc", "shell/browser/api/electron_api_web_contents_view.h", "shell/browser/api/electron_api_web_frame_main.cc", "shell/browser/api/electron_api_web_frame_main.h", "shell/browser/api/electron_api_web_request.cc", "shell/browser/api/electron_api_web_request.h", "shell/browser/api/electron_api_web_view_manager.cc", "shell/browser/api/frame_subscriber.cc", "shell/browser/api/frame_subscriber.h", "shell/browser/api/gpu_info_enumerator.cc", "shell/browser/api/gpu_info_enumerator.h", "shell/browser/api/gpuinfo_manager.cc", "shell/browser/api/gpuinfo_manager.h", "shell/browser/api/message_port.cc", "shell/browser/api/message_port.h", "shell/browser/api/process_metric.cc", "shell/browser/api/process_metric.h", "shell/browser/api/save_page_handler.cc", "shell/browser/api/save_page_handler.h", "shell/browser/api/ui_event.cc", "shell/browser/api/ui_event.h", "shell/browser/auto_updater.cc", "shell/browser/auto_updater.h", "shell/browser/background_throttling_source.h", "shell/browser/badging/badge_manager.cc", "shell/browser/badging/badge_manager.h", "shell/browser/badging/badge_manager_factory.cc", "shell/browser/badging/badge_manager_factory.h", "shell/browser/bluetooth/electron_bluetooth_delegate.cc", "shell/browser/bluetooth/electron_bluetooth_delegate.h", "shell/browser/browser.cc", "shell/browser/browser.h", "shell/browser/browser_observer.h", "shell/browser/browser_process_impl.cc", "shell/browser/browser_process_impl.h", "shell/browser/child_web_contents_tracker.cc", "shell/browser/child_web_contents_tracker.h", "shell/browser/cookie_change_notifier.cc", "shell/browser/cookie_change_notifier.h", "shell/browser/draggable_region_provider.h", "shell/browser/electron_api_ipc_handler_impl.cc", "shell/browser/electron_api_ipc_handler_impl.h", "shell/browser/electron_autofill_driver.cc", "shell/browser/electron_autofill_driver.h", "shell/browser/electron_autofill_driver_factory.cc", "shell/browser/electron_autofill_driver_factory.h", "shell/browser/electron_browser_client.cc", "shell/browser/electron_browser_client.h", "shell/browser/electron_browser_context.cc", "shell/browser/electron_browser_context.h", "shell/browser/electron_browser_main_parts.cc", "shell/browser/electron_browser_main_parts.h", "shell/browser/electron_download_manager_delegate.cc", "shell/browser/electron_download_manager_delegate.h", "shell/browser/electron_gpu_client.cc", "shell/browser/electron_gpu_client.h", "shell/browser/electron_javascript_dialog_manager.cc", "shell/browser/electron_javascript_dialog_manager.h", "shell/browser/electron_navigation_throttle.cc", "shell/browser/electron_navigation_throttle.h", "shell/browser/electron_permission_manager.cc", "shell/browser/electron_permission_manager.h", "shell/browser/electron_speech_recognition_manager_delegate.cc", "shell/browser/electron_speech_recognition_manager_delegate.h", "shell/browser/electron_web_contents_utility_handler_impl.cc", "shell/browser/electron_web_contents_utility_handler_impl.h", "shell/browser/electron_web_ui_controller_factory.cc", "shell/browser/electron_web_ui_controller_factory.h", "shell/browser/event_emitter_mixin.h", "shell/browser/extended_web_contents_observer.h", "shell/browser/feature_list.cc", "shell/browser/feature_list.h", "shell/browser/file_select_helper.cc", "shell/browser/file_select_helper.h", "shell/browser/file_select_helper_mac.mm", "shell/browser/font_defaults.cc", "shell/browser/font_defaults.h", "shell/browser/hid/electron_hid_delegate.cc", "shell/browser/hid/electron_hid_delegate.h", "shell/browser/hid/hid_chooser_context.cc", "shell/browser/hid/hid_chooser_context.h", "shell/browser/hid/hid_chooser_context_factory.cc", "shell/browser/hid/hid_chooser_context_factory.h", "shell/browser/hid/hid_chooser_controller.cc", "shell/browser/hid/hid_chooser_controller.h", "shell/browser/javascript_environment.cc", "shell/browser/javascript_environment.h", "shell/browser/lib/bluetooth_chooser.cc", "shell/browser/lib/bluetooth_chooser.h", "shell/browser/login_handler.cc", "shell/browser/login_handler.h", "shell/browser/media/media_capture_devices_dispatcher.cc", "shell/browser/media/media_capture_devices_dispatcher.h", "shell/browser/media/media_device_id_salt.cc", "shell/browser/media/media_device_id_salt.h", "shell/browser/microtasks_runner.cc", "shell/browser/microtasks_runner.h", "shell/browser/native_browser_view.cc", "shell/browser/native_browser_view.h", "shell/browser/native_window.cc", "shell/browser/native_window.h", "shell/browser/native_window_features.cc", "shell/browser/native_window_features.h", "shell/browser/native_window_observer.h", "shell/browser/net/asar/asar_file_validator.cc", "shell/browser/net/asar/asar_file_validator.h", "shell/browser/net/asar/asar_url_loader.cc", "shell/browser/net/asar/asar_url_loader.h", "shell/browser/net/asar/asar_url_loader_factory.cc", "shell/browser/net/asar/asar_url_loader_factory.h", "shell/browser/net/cert_verifier_client.cc", "shell/browser/net/cert_verifier_client.h", "shell/browser/net/electron_url_loader_factory.cc", "shell/browser/net/electron_url_loader_factory.h", "shell/browser/net/network_context_service.cc", "shell/browser/net/network_context_service.h", "shell/browser/net/network_context_service_factory.cc", "shell/browser/net/network_context_service_factory.h", "shell/browser/net/node_stream_loader.cc", "shell/browser/net/node_stream_loader.h", "shell/browser/net/proxying_url_loader_factory.cc", "shell/browser/net/proxying_url_loader_factory.h", "shell/browser/net/proxying_websocket.cc", "shell/browser/net/proxying_websocket.h", "shell/browser/net/resolve_host_function.cc", "shell/browser/net/resolve_host_function.h", "shell/browser/net/resolve_proxy_helper.cc", "shell/browser/net/resolve_proxy_helper.h", "shell/browser/net/system_network_context_manager.cc", "shell/browser/net/system_network_context_manager.h", "shell/browser/net/url_pipe_loader.cc", "shell/browser/net/url_pipe_loader.h", "shell/browser/net/web_request_api_interface.h", "shell/browser/network_hints_handler_impl.cc", "shell/browser/network_hints_handler_impl.h", "shell/browser/notifications/notification.cc", "shell/browser/notifications/notification.h", "shell/browser/notifications/notification_delegate.h", "shell/browser/notifications/notification_presenter.cc", "shell/browser/notifications/notification_presenter.h", "shell/browser/notifications/platform_notification_service.cc", "shell/browser/notifications/platform_notification_service.h", "shell/browser/osr/osr_host_display_client.cc", "shell/browser/osr/osr_host_display_client.h", "shell/browser/osr/osr_render_widget_host_view.cc", "shell/browser/osr/osr_render_widget_host_view.h", "shell/browser/osr/osr_video_consumer.cc", "shell/browser/osr/osr_video_consumer.h", "shell/browser/osr/osr_view_proxy.cc", "shell/browser/osr/osr_view_proxy.h", "shell/browser/osr/osr_web_contents_view.cc", "shell/browser/osr/osr_web_contents_view.h", "shell/browser/plugins/plugin_utils.cc", "shell/browser/plugins/plugin_utils.h", "shell/browser/protocol_registry.cc", "shell/browser/protocol_registry.h", "shell/browser/relauncher.cc", "shell/browser/relauncher.h", "shell/browser/serial/electron_serial_delegate.cc", "shell/browser/serial/electron_serial_delegate.h", "shell/browser/serial/serial_chooser_context.cc", "shell/browser/serial/serial_chooser_context.h", "shell/browser/serial/serial_chooser_context_factory.cc", "shell/browser/serial/serial_chooser_context_factory.h", "shell/browser/serial/serial_chooser_controller.cc", "shell/browser/serial/serial_chooser_controller.h", "shell/browser/session_preferences.cc", "shell/browser/session_preferences.h", "shell/browser/special_storage_policy.cc", "shell/browser/special_storage_policy.h", "shell/browser/ui/accelerator_util.cc", "shell/browser/ui/accelerator_util.h", "shell/browser/ui/autofill_popup.cc", "shell/browser/ui/autofill_popup.h", "shell/browser/ui/certificate_trust.h", "shell/browser/ui/devtools_manager_delegate.cc", "shell/browser/ui/devtools_manager_delegate.h", "shell/browser/ui/devtools_ui.cc", "shell/browser/ui/devtools_ui.h", "shell/browser/ui/drag_util.cc", "shell/browser/ui/drag_util.h", "shell/browser/ui/electron_menu_model.cc", "shell/browser/ui/electron_menu_model.h", "shell/browser/ui/file_dialog.h", "shell/browser/ui/inspectable_web_contents.cc", "shell/browser/ui/inspectable_web_contents.h", "shell/browser/ui/inspectable_web_contents_delegate.h", "shell/browser/ui/inspectable_web_contents_view.cc", "shell/browser/ui/inspectable_web_contents_view.h", "shell/browser/ui/inspectable_web_contents_view_delegate.cc", "shell/browser/ui/inspectable_web_contents_view_delegate.h", "shell/browser/ui/message_box.h", "shell/browser/ui/tray_icon.cc", "shell/browser/ui/tray_icon.h", "shell/browser/ui/tray_icon_observer.h", "shell/browser/ui/webui/accessibility_ui.cc", "shell/browser/ui/webui/accessibility_ui.h", "shell/browser/usb/electron_usb_delegate.cc", "shell/browser/usb/electron_usb_delegate.h", "shell/browser/usb/usb_chooser_context.cc", "shell/browser/usb/usb_chooser_context.h", "shell/browser/usb/usb_chooser_context_factory.cc", "shell/browser/usb/usb_chooser_context_factory.h", "shell/browser/usb/usb_chooser_controller.cc", "shell/browser/usb/usb_chooser_controller.h", "shell/browser/web_contents_permission_helper.cc", "shell/browser/web_contents_permission_helper.h", "shell/browser/web_contents_preferences.cc", "shell/browser/web_contents_preferences.h", "shell/browser/web_contents_zoom_controller.cc", "shell/browser/web_contents_zoom_controller.h", "shell/browser/web_contents_zoom_observer.h", "shell/browser/web_view_guest_delegate.cc", "shell/browser/web_view_guest_delegate.h", "shell/browser/web_view_manager.cc", "shell/browser/web_view_manager.h", "shell/browser/webauthn/electron_authenticator_request_delegate.cc", "shell/browser/webauthn/electron_authenticator_request_delegate.h", "shell/browser/window_list.cc", "shell/browser/window_list.h", "shell/browser/window_list_observer.h", "shell/browser/zoom_level_delegate.cc", "shell/browser/zoom_level_delegate.h", "shell/common/api/crashpad_support.cc", "shell/common/api/electron_api_asar.cc", "shell/common/api/electron_api_clipboard.cc", "shell/common/api/electron_api_clipboard.h", "shell/common/api/electron_api_command_line.cc", "shell/common/api/electron_api_environment.cc", "shell/common/api/electron_api_key_weak_map.h", "shell/common/api/electron_api_native_image.cc", "shell/common/api/electron_api_native_image.h", "shell/common/api/electron_api_shell.cc", "shell/common/api/electron_api_testing.cc", "shell/common/api/electron_api_v8_util.cc", "shell/common/api/electron_bindings.cc", "shell/common/api/electron_bindings.h", "shell/common/api/features.cc", "shell/common/api/object_life_monitor.cc", "shell/common/api/object_life_monitor.h", "shell/common/application_info.cc", "shell/common/application_info.h", "shell/common/asar/archive.cc", "shell/common/asar/archive.h", "shell/common/asar/asar_util.cc", "shell/common/asar/asar_util.h", "shell/common/asar/scoped_temporary_file.cc", "shell/common/asar/scoped_temporary_file.h", "shell/common/color_util.cc", "shell/common/color_util.h", "shell/common/crash_keys.cc", "shell/common/crash_keys.h", "shell/common/electron_command_line.cc", "shell/common/electron_command_line.h", "shell/common/electron_constants.cc", "shell/common/electron_constants.h", "shell/common/electron_paths.h", "shell/common/gin_converters/accelerator_converter.cc", "shell/common/gin_converters/accelerator_converter.h", "shell/common/gin_converters/base_converter.h", "shell/common/gin_converters/blink_converter.cc", "shell/common/gin_converters/blink_converter.h", "shell/common/gin_converters/callback_converter.h", "shell/common/gin_converters/content_converter.cc", "shell/common/gin_converters/content_converter.h", "shell/common/gin_converters/file_dialog_converter.cc", "shell/common/gin_converters/file_dialog_converter.h", "shell/common/gin_converters/file_path_converter.h", "shell/common/gin_converters/frame_converter.cc", "shell/common/gin_converters/frame_converter.h", "shell/common/gin_converters/gfx_converter.cc", "shell/common/gin_converters/gfx_converter.h", "shell/common/gin_converters/guid_converter.h", "shell/common/gin_converters/gurl_converter.h", "shell/common/gin_converters/hid_device_info_converter.h", "shell/common/gin_converters/image_converter.cc", "shell/common/gin_converters/image_converter.h", "shell/common/gin_converters/media_converter.cc", "shell/common/gin_converters/media_converter.h", "shell/common/gin_converters/message_box_converter.cc", "shell/common/gin_converters/message_box_converter.h", "shell/common/gin_converters/native_window_converter.h", "shell/common/gin_converters/net_converter.cc", "shell/common/gin_converters/net_converter.h", "shell/common/gin_converters/optional_converter.h", "shell/common/gin_converters/serial_port_info_converter.h", "shell/common/gin_converters/std_converter.h", "shell/common/gin_converters/time_converter.cc", "shell/common/gin_converters/time_converter.h", "shell/common/gin_converters/usb_device_info_converter.h", "shell/common/gin_converters/value_converter.cc", "shell/common/gin_converters/value_converter.h", "shell/common/gin_helper/arguments.cc", "shell/common/gin_helper/arguments.h", "shell/common/gin_helper/callback.cc", "shell/common/gin_helper/callback.h", "shell/common/gin_helper/cleaned_up_at_exit.cc", "shell/common/gin_helper/cleaned_up_at_exit.h", "shell/common/gin_helper/constructible.h", "shell/common/gin_helper/constructor.h", "shell/common/gin_helper/destroyable.cc", "shell/common/gin_helper/destroyable.h", "shell/common/gin_helper/dictionary.h", "shell/common/gin_helper/error_thrower.cc", "shell/common/gin_helper/error_thrower.h", "shell/common/gin_helper/event.cc", "shell/common/gin_helper/event.h", "shell/common/gin_helper/event_emitter.h", "shell/common/gin_helper/event_emitter_caller.cc", "shell/common/gin_helper/event_emitter_caller.h", "shell/common/gin_helper/event_emitter_template.cc", "shell/common/gin_helper/event_emitter_template.h", "shell/common/gin_helper/function_template.cc", "shell/common/gin_helper/function_template.h", "shell/common/gin_helper/function_template_extensions.h", "shell/common/gin_helper/locker.cc", "shell/common/gin_helper/locker.h", "shell/common/gin_helper/microtasks_scope.cc", "shell/common/gin_helper/microtasks_scope.h", "shell/common/gin_helper/object_template_builder.cc", "shell/common/gin_helper/object_template_builder.h", "shell/common/gin_helper/persistent_dictionary.cc", "shell/common/gin_helper/persistent_dictionary.h", "shell/common/gin_helper/pinnable.h", "shell/common/gin_helper/promise.cc", "shell/common/gin_helper/promise.h", "shell/common/gin_helper/trackable_object.cc", "shell/common/gin_helper/trackable_object.h", "shell/common/gin_helper/wrappable.cc", "shell/common/gin_helper/wrappable.h", "shell/common/gin_helper/wrappable_base.h", "shell/common/heap_snapshot.cc", "shell/common/heap_snapshot.h", "shell/common/key_weak_map.h", "shell/common/keyboard_util.cc", "shell/common/keyboard_util.h", "shell/common/language_util.h", "shell/common/logging.cc", "shell/common/logging.h", "shell/common/node_bindings.cc", "shell/common/node_bindings.h", "shell/common/node_includes.h", "shell/common/node_util.cc", "shell/common/node_util.h", "shell/common/options_switches.cc", "shell/common/options_switches.h", "shell/common/platform_util.cc", "shell/common/platform_util.h", "shell/common/platform_util_internal.h", "shell/common/process_util.cc", "shell/common/process_util.h", "shell/common/skia_util.cc", "shell/common/skia_util.h", "shell/common/thread_restrictions.h", "shell/common/v8_value_serializer.cc", "shell/common/v8_value_serializer.h", "shell/common/world_ids.h", "shell/renderer/api/context_bridge/object_cache.cc", "shell/renderer/api/context_bridge/object_cache.h", "shell/renderer/api/electron_api_context_bridge.cc", "shell/renderer/api/electron_api_context_bridge.h", "shell/renderer/api/electron_api_crash_reporter_renderer.cc", "shell/renderer/api/electron_api_ipc_renderer.cc", "shell/renderer/api/electron_api_spell_check_client.cc", "shell/renderer/api/electron_api_spell_check_client.h", "shell/renderer/api/electron_api_web_frame.cc", "shell/renderer/browser_exposed_renderer_interfaces.cc", "shell/renderer/browser_exposed_renderer_interfaces.h", "shell/renderer/content_settings_observer.cc", "shell/renderer/content_settings_observer.h", "shell/renderer/electron_api_service_impl.cc", "shell/renderer/electron_api_service_impl.h", "shell/renderer/electron_autofill_agent.cc", "shell/renderer/electron_autofill_agent.h", "shell/renderer/electron_render_frame_observer.cc", "shell/renderer/electron_render_frame_observer.h", "shell/renderer/electron_renderer_client.cc", "shell/renderer/electron_renderer_client.h", "shell/renderer/electron_sandboxed_renderer_client.cc", "shell/renderer/electron_sandboxed_renderer_client.h", "shell/renderer/renderer_client_base.cc", "shell/renderer/renderer_client_base.h", "shell/renderer/web_worker_observer.cc", "shell/renderer/web_worker_observer.h", "shell/services/node/node_service.cc", "shell/services/node/node_service.h", "shell/services/node/parent_port.cc", "shell/services/node/parent_port.h", "shell/utility/electron_content_utility_client.cc", "shell/utility/electron_content_utility_client.h", ] lib_sources_extensions = [ "shell/browser/extensions/api/extension_action/extension_action_api.cc", "shell/browser/extensions/api/extension_action/extension_action_api.h", "shell/browser/extensions/api/management/electron_management_api_delegate.cc", "shell/browser/extensions/api/management/electron_management_api_delegate.h", "shell/browser/extensions/api/resources_private/resources_private_api.cc", "shell/browser/extensions/api/resources_private/resources_private_api.h", "shell/browser/extensions/api/runtime/electron_runtime_api_delegate.cc", "shell/browser/extensions/api/runtime/electron_runtime_api_delegate.h", "shell/browser/extensions/api/scripting/scripting_api.cc", "shell/browser/extensions/api/scripting/scripting_api.h", "shell/browser/extensions/api/streams_private/streams_private_api.cc", "shell/browser/extensions/api/streams_private/streams_private_api.h", "shell/browser/extensions/api/tabs/tabs_api.cc", "shell/browser/extensions/api/tabs/tabs_api.h", "shell/browser/extensions/electron_browser_context_keyed_service_factories.cc", "shell/browser/extensions/electron_browser_context_keyed_service_factories.h", "shell/browser/extensions/electron_component_extension_resource_manager.cc", "shell/browser/extensions/electron_component_extension_resource_manager.h", "shell/browser/extensions/electron_display_info_provider.cc", "shell/browser/extensions/electron_display_info_provider.h", "shell/browser/extensions/electron_extension_host_delegate.cc", "shell/browser/extensions/electron_extension_host_delegate.h", "shell/browser/extensions/electron_extension_loader.cc", "shell/browser/extensions/electron_extension_loader.h", "shell/browser/extensions/electron_extension_message_filter.cc", "shell/browser/extensions/electron_extension_message_filter.h", "shell/browser/extensions/electron_extension_system_factory.cc", "shell/browser/extensions/electron_extension_system_factory.h", "shell/browser/extensions/electron_extension_system.cc", "shell/browser/extensions/electron_extension_system.h", "shell/browser/extensions/electron_extension_web_contents_observer.cc", "shell/browser/extensions/electron_extension_web_contents_observer.h", "shell/browser/extensions/electron_extensions_api_client.cc", "shell/browser/extensions/electron_extensions_api_client.h", "shell/browser/extensions/electron_extensions_browser_api_provider.cc", "shell/browser/extensions/electron_extensions_browser_api_provider.h", "shell/browser/extensions/electron_extensions_browser_client.cc", "shell/browser/extensions/electron_extensions_browser_client.h", "shell/browser/extensions/electron_kiosk_delegate.cc", "shell/browser/extensions/electron_kiosk_delegate.h", "shell/browser/extensions/electron_messaging_delegate.cc", "shell/browser/extensions/electron_messaging_delegate.h", "shell/browser/extensions/electron_navigation_ui_data.cc", "shell/browser/extensions/electron_navigation_ui_data.h", "shell/browser/extensions/electron_process_manager_delegate.cc", "shell/browser/extensions/electron_process_manager_delegate.h", "shell/common/extensions/electron_extensions_api_provider.cc", "shell/common/extensions/electron_extensions_api_provider.h", "shell/common/extensions/electron_extensions_client.cc", "shell/common/extensions/electron_extensions_client.h", "shell/common/gin_converters/extension_converter.cc", "shell/common/gin_converters/extension_converter.h", "shell/renderer/extensions/electron_extensions_dispatcher_delegate.cc", "shell/renderer/extensions/electron_extensions_dispatcher_delegate.h", "shell/renderer/extensions/electron_extensions_renderer_client.cc", "shell/renderer/extensions/electron_extensions_renderer_client.h", ] framework_sources = [ "shell/app/electron_library_main.h", "shell/app/electron_library_main.mm", ] login_helper_sources = [ "shell/app/electron_login_helper.mm" ] }
closed
electron/electron
https://github.com/electron/electron
40,439
Convert legacy IPC calls in extensions code to use mojo
https://chromium-review.googlesource.com/c/chromium/src/+/4995136 turned on the build flag to use the new mojo IPC pipe for messaging in extensions. In #40418 we turned this off because we have not converted our extensions code to use mojo. It appears that in chromium the follow CLs were landed to use mojo in extensions: - 4947890: [extensions] Convert Extension Messaging APIs over to mojo | https://chromium-review.googlesource.com/c/chromium/src/+/4947890 - 4950041: [extensions] Port Event Acks to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4950041 - 4902564: [extensions] Move WakeEventPage to mojom::RendererHost | https://chromium-review.googlesource.com/c/chromium/src/+/4902564 - 4956841: [extensions] Port GetMessageBundle over to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4956841 Once these changes have landed, the following flag override in build/args/all.gn should be removed: `enable_extensions_legacy_ipc = true`
https://github.com/electron/electron/issues/40439
https://github.com/electron/electron/pull/40511
088affd4a4311e03b8ed400cdf5d82f1db2125a4
371bca69b69351dc47d4b4dcfdf9a626f43b3b51
2023-11-02T18:50:40Z
c++
2023-11-15T14:30:47Z
shell/browser/electron_browser_client.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_client.h" #if BUILDFLAG(IS_WIN) #include <shlobj.h> #endif #include <memory> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/debug/crash_logging.h" #include "base/environment.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/lazy_instance.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/stl_util.h" #include "base/strings/escape.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version.h" #include "components/embedder_support/user_agent_utils.h" #include "components/net_log/chrome_net_log.h" #include "components/network_hints/common/network_hints.mojom.h" #include "content/browser/keyboard_lock/keyboard_lock_service_impl.h" // nogncheck #include "content/browser/site_instance_impl.h" // nogncheck #include "content/public/browser/browser_main_runner.h" #include "content/public/browser/browser_ppapi_host.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/client_certificate_delegate.h" #include "content/public/browser/login_delegate.h" #include "content/public/browser/overlay_window.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/service_worker_version_base_info.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/tts_controller.h" #include "content/public/browser/tts_platform.h" #include "content/public/browser/url_loader_request_interceptor.h" #include "content/public/browser/weak_document_ptr.h" #include "content/public/common/content_descriptors.h" #include "content/public/common/content_paths.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "crypto/crypto_buildflags.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "electron/shell/common/api/api.mojom.h" #include "extensions/browser/extension_navigation_ui_data.h" #include "mojo/public/cpp/bindings/binder_map.h" #include "net/ssl/ssl_cert_request_info.h" #include "net/ssl/ssl_private_key.h" #include "ppapi/buildflags/buildflags.h" #include "ppapi/host/ppapi_host.h" #include "printing/buildflags/buildflags.h" #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "services/device/public/cpp/geolocation/location_provider.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/is_potentially_trustworthy.h" #include "services/network/public/cpp/network_switches.h" #include "services/network/public/cpp/resource_request_body.h" #include "services/network/public/cpp/self_deleting_url_loader_factory.h" #include "shell/app/electron_crash_reporter_client.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/api/electron_api_crash_reporter.h" #include "shell/browser/api/electron_api_protocol.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/api/electron_api_web_request.h" #include "shell/browser/badging/badge_manager.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_api_ipc_handler_impl.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/electron_speech_recognition_manager_delegate.h" #include "shell/browser/electron_web_contents_utility_handler_impl.h" #include "shell/browser/font_defaults.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/native_window.h" #include "shell/browser/net/network_context_service.h" #include "shell/browser/net/network_context_service_factory.h" #include "shell/browser/net/proxying_url_loader_factory.h" #include "shell/browser/net/proxying_websocket.h" #include "shell/browser/net/system_network_context_manager.h" #include "shell/browser/network_hints_handler_impl.h" #include "shell/browser/notifications/notification_presenter.h" #include "shell/browser/notifications/platform_notification_service.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/serial/electron_serial_delegate.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/webauthn/electron_authenticator_request_delegate.h" #include "shell/browser/window_list.h" #include "shell/common/api/api.mojom.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/logging.h" #include "shell/common/options_switches.h" #include "shell/common/platform_util.h" #include "shell/common/thread_restrictions.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" #include "third_party/blink/public/common/loader/url_loader_throttle.h" #include "third_party/blink/public/common/renderer_preferences/renderer_preferences.h" #include "third_party/blink/public/common/tokens/tokens.h" #include "third_party/blink/public/common/web_preferences/web_preferences.h" #include "third_party/blink/public/mojom/badging/badging.mojom.h" #include "ui/base/resource/resource_bundle.h" #include "ui/native_theme/native_theme.h" #include "v8/include/v8.h" #if BUILDFLAG(USE_NSS_CERTS) #include "net/ssl/client_cert_store_nss.h" #elif BUILDFLAG(IS_WIN) #include "net/ssl/client_cert_store_win.h" #elif BUILDFLAG(IS_MAC) #include "net/ssl/client_cert_store_mac.h" #elif defined(USE_OPENSSL) #include "net/ssl/client_cert_store.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spell_check_host_chrome_impl.h" // nogncheck #include "components/spellcheck/common/spellcheck.mojom.h" // nogncheck #endif #if BUILDFLAG(OVERRIDE_LOCATION_PROVIDER) #include "shell/browser/fake_location_provider.h" #endif // BUILDFLAG(OVERRIDE_LOCATION_PROVIDER) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "base/functional/bind.h" #include "chrome/common/webui_url_constants.h" #include "components/guest_view/common/guest_view.mojom.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/file_url_loader.h" #include "content/public/browser/web_ui_url_loader_factory.h" #include "extensions/browser/api/messaging/messaging_api_message_filter.h" #include "extensions/browser/api/mime_handler_private/mime_handler_private.h" #include "extensions/browser/api/web_request/web_request_api.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_message_filter.h" #include "extensions/browser/extension_navigation_throttle.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_protocols.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/guest_view/extensions_guest_view.h" #include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h" #include "extensions/browser/process_manager.h" #include "extensions/browser/process_map.h" #include "extensions/browser/renderer_startup_helper.h" #include "extensions/browser/service_worker/service_worker_host.h" #include "extensions/browser/url_loader_factory_manager.h" #include "extensions/common/api/mime_handler.mojom.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/mojom/event_router.mojom.h" #include "extensions/common/mojom/guest_view.mojom.h" #include "extensions/common/mojom/renderer_host.mojom.h" #include "extensions/common/switches.h" #include "shell/browser/extensions/electron_extension_message_filter.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "chrome/browser/plugins/plugin_response_interceptor_url_loader_throttle.h" // nogncheck #include "shell/browser/plugins/plugin_utils.h" #endif #if BUILDFLAG(IS_MAC) #include "content/browser/mac_helpers.h" #include "content/public/browser/child_process_host.h" #endif #if BUILDFLAG(IS_LINUX) #include "components/crash/core/app/crash_switches.h" // nogncheck #include "components/crash/core/app/crashpad.h" // nogncheck #endif #if BUILDFLAG(IS_WIN) #include "chrome/browser/ui/views/overlay/video_overlay_window_views.h" #include "shell/browser/browser.h" #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/base/win/shell.h" #include "ui/views/widget/widget.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "shell/browser/printing/print_view_manager_electron.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "chrome/browser/pdf/chrome_pdf_stream_delegate.h" #include "chrome/browser/plugins/pdf_iframe_navigation_throttle.h" // nogncheck #include "components/pdf/browser/pdf_document_helper.h" // nogncheck #include "components/pdf/browser/pdf_navigation_throttle.h" #include "components/pdf/browser/pdf_url_loader_request_interceptor.h" #include "components/pdf/common/internal_plugin_helpers.h" #include "shell/browser/electron_pdf_document_helper_client.h" #endif using content::BrowserThread; namespace electron { namespace { ElectronBrowserClient* g_browser_client = nullptr; base::LazyInstance<std::string>::DestructorAtExit g_io_thread_application_locale = LAZY_INSTANCE_INITIALIZER; base::NoDestructor<std::string> g_application_locale; void SetApplicationLocaleOnIOThread(const std::string& locale) { DCHECK_CURRENTLY_ON(BrowserThread::IO); g_io_thread_application_locale.Get() = locale; } void BindNetworkHintsHandler( content::RenderFrameHost* frame_host, mojo::PendingReceiver<network_hints::mojom::NetworkHintsHandler> receiver) { NetworkHintsHandlerImpl::Create(frame_host, std::move(receiver)); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // Used by the GetPrivilegeRequiredByUrl() and GetProcessPrivilege() functions // below. Extension, and isolated apps require different privileges to be // granted to their RenderProcessHosts. This classification allows us to make // sure URLs are served by hosts with the right set of privileges. enum class RenderProcessHostPrivilege { kNormal, kHosted, kIsolated, kExtension, }; // Copied from chrome/browser/extensions/extension_util.cc. bool AllowFileAccess(const std::string& extension_id, content::BrowserContext* context) { return base::CommandLine::ForCurrentProcess()->HasSwitch( extensions::switches::kDisableExtensionsFileAccessCheck) || extensions::ExtensionPrefs::Get(context)->AllowFileAccess( extension_id); } RenderProcessHostPrivilege GetPrivilegeRequiredByUrl( const GURL& url, extensions::ExtensionRegistry* registry) { // Default to a normal renderer cause it is lower privileged. This should only // occur if the URL on a site instance is either malformed, or uninitialized. // If it is malformed, then there is no need for better privileges anyways. // If it is uninitialized, but eventually settles on being an a scheme other // than normal webrenderer, the navigation logic will correct us out of band // anyways. if (!url.is_valid()) return RenderProcessHostPrivilege::kNormal; if (!url.SchemeIs(extensions::kExtensionScheme)) return RenderProcessHostPrivilege::kNormal; return RenderProcessHostPrivilege::kExtension; } RenderProcessHostPrivilege GetProcessPrivilege( content::RenderProcessHost* process_host, extensions::ProcessMap* process_map, extensions::ExtensionRegistry* registry) { std::set<std::string> extension_ids = process_map->GetExtensionsInProcess(process_host->GetID()); if (extension_ids.empty()) return RenderProcessHostPrivilege::kNormal; return RenderProcessHostPrivilege::kExtension; } const extensions::Extension* GetEnabledExtensionFromEffectiveURL( content::BrowserContext* context, const GURL& effective_url) { if (!effective_url.SchemeIs(extensions::kExtensionScheme)) return nullptr; extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(context); if (!registry) return nullptr; return registry->enabled_extensions().GetByID(effective_url.host()); } #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(IS_LINUX) int GetCrashSignalFD(const base::CommandLine& command_line) { int fd; return crash_reporter::GetHandlerSocket(&fd, nullptr) ? fd : -1; } #endif // BUILDFLAG(IS_LINUX) void MaybeAppendSecureOriginsAllowlistSwitch(base::CommandLine* cmdline) { // |allowlist| combines pref/policy + cmdline switch in the browser process. // For renderer and utility (e.g. NetworkService) processes the switch is the // only available source, so below the combined (pref/policy + cmdline) // allowlist of secure origins is injected into |cmdline| for these other // processes. std::vector<std::string> allowlist = network::SecureOriginAllowlist::GetInstance().GetCurrentAllowlist(); if (!allowlist.empty()) { cmdline->AppendSwitchASCII( network::switches::kUnsafelyTreatInsecureOriginAsSecure, base::JoinString(allowlist, ",")); } } } // namespace // static ElectronBrowserClient* ElectronBrowserClient::Get() { return g_browser_client; } // static void ElectronBrowserClient::SetApplicationLocale(const std::string& locale) { if (!BrowserThread::IsThreadInitialized(BrowserThread::IO) || !content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&SetApplicationLocaleOnIOThread, locale))) { g_io_thread_application_locale.Get() = locale; } *g_application_locale = locale; } ElectronBrowserClient::ElectronBrowserClient() { DCHECK(!g_browser_client); g_browser_client = this; } ElectronBrowserClient::~ElectronBrowserClient() { DCHECK(g_browser_client); g_browser_client = nullptr; } content::WebContents* ElectronBrowserClient::GetWebContentsFromProcessID( int process_id) { // If the process is a pending process, we should use the web contents // for the frame host passed into RegisterPendingProcess. const auto iter = pending_processes_.find(process_id); if (iter != std::end(pending_processes_)) return iter->second; // Certain render process will be created with no associated render view, // for example: ServiceWorker. return WebContentsPreferences::GetWebContentsFromProcessID(process_id); } content::SiteInstance* ElectronBrowserClient::GetSiteInstanceFromAffinity( content::BrowserContext* browser_context, const GURL& url, content::RenderFrameHost* rfh) const { return nullptr; } bool ElectronBrowserClient::IsRendererSubFrame(int process_id) const { return base::Contains(renderer_is_subframe_, process_id); } void ElectronBrowserClient::RenderProcessWillLaunch( content::RenderProcessHost* host) { // When a render process is crashed, it might be reused. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) int process_id = host->GetID(); auto* browser_context = host->GetBrowserContext(); host->AddFilter( new extensions::ExtensionMessageFilter(process_id, browser_context)); host->AddFilter( new ElectronExtensionMessageFilter(process_id, browser_context)); host->AddFilter( new extensions::MessagingAPIMessageFilter(process_id, browser_context)); #endif // Remove in case the host is reused after a crash, otherwise noop. host->RemoveObserver(this); // ensure the ProcessPreferences is removed later host->AddObserver(this); } content::SpeechRecognitionManagerDelegate* ElectronBrowserClient::CreateSpeechRecognitionManagerDelegate() { return new ElectronSpeechRecognitionManagerDelegate; } content::TtsPlatform* ElectronBrowserClient::GetTtsPlatform() { return nullptr; } void ElectronBrowserClient::OverrideWebkitPrefs( content::WebContents* web_contents, blink::web_pref::WebPreferences* prefs) { prefs->javascript_enabled = true; prefs->web_security_enabled = true; prefs->plugins_enabled = true; prefs->dom_paste_enabled = true; prefs->allow_scripts_to_close_windows = true; prefs->javascript_can_access_clipboard = true; prefs->local_storage_enabled = true; prefs->databases_enabled = true; prefs->allow_universal_access_from_file_urls = electron::fuses::IsGrantFileProtocolExtraPrivilegesEnabled(); prefs->allow_file_access_from_file_urls = electron::fuses::IsGrantFileProtocolExtraPrivilegesEnabled(); prefs->webgl1_enabled = true; prefs->webgl2_enabled = true; prefs->allow_running_insecure_content = false; prefs->default_minimum_page_scale_factor = 1.f; prefs->default_maximum_page_scale_factor = 1.f; blink::RendererPreferences* renderer_prefs = web_contents->GetMutableRendererPrefs(); renderer_prefs->can_accept_load_drops = false; ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForNativeUi(); prefs->preferred_color_scheme = native_theme->ShouldUseDarkColors() ? blink::mojom::PreferredColorScheme::kDark : blink::mojom::PreferredColorScheme::kLight; SetFontDefaults(prefs); // Custom preferences of guest page. auto* web_preferences = WebContentsPreferences::From(web_contents); if (web_preferences) { web_preferences->OverrideWebkitPrefs(prefs, renderer_prefs); } } void ElectronBrowserClient::RegisterPendingSiteInstance( content::RenderFrameHost* rfh, content::SiteInstance* pending_site_instance) { // Remember the original web contents for the pending renderer process. auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); auto* pending_process = pending_site_instance->GetProcess(); pending_processes_[pending_process->GetID()] = web_contents; if (rfh->GetParent()) renderer_is_subframe_.insert(pending_process->GetID()); else renderer_is_subframe_.erase(pending_process->GetID()); } void ElectronBrowserClient::AppendExtraCommandLineSwitches( base::CommandLine* command_line, int process_id) { // Make sure we're about to launch a known executable { ScopedAllowBlockingForElectron allow_blocking; base::FilePath child_path; base::FilePath program = base::MakeAbsoluteFilePath(command_line->GetProgram()); #if BUILDFLAG(IS_MAC) auto renderer_child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_RENDERER); auto gpu_child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_GPU); auto plugin_child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_PLUGIN); if (program != renderer_child_path && program != gpu_child_path && program != plugin_child_path) { child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_NORMAL); CHECK_EQ(program, child_path) << "Aborted from launching unexpected helper executable"; } #else if (!base::PathService::Get(content::CHILD_PROCESS_EXE, &child_path)) { CHECK(false) << "Unable to get child process binary name."; } SCOPED_CRASH_KEY_STRING256("ChildProcess", "child_process_exe", child_path.AsUTF8Unsafe()); SCOPED_CRASH_KEY_STRING256("ChildProcess", "program", program.AsUTF8Unsafe()); CHECK_EQ(program, child_path); #endif } std::string process_type = command_line->GetSwitchValueASCII(::switches::kProcessType); #if BUILDFLAG(IS_LINUX) pid_t pid; if (crash_reporter::GetHandlerSocket(nullptr, &pid)) { command_line->AppendSwitchASCII( crash_reporter::switches::kCrashpadHandlerPid, base::NumberToString(pid)); } // Zygote Process gets booted before any JS runs, accessing GetClientId // will end up touching DIR_USER_DATA path provider and this will // configure default value because app.name from browser_init has // not run yet. if (process_type != ::switches::kZygoteProcess) { std::string switch_value = api::crash_reporter::GetClientId() + ",no_channel"; command_line->AppendSwitchASCII(::switches::kEnableCrashReporter, switch_value); } #endif // The zygote process is booted before JS runs, so DIR_USER_DATA isn't usable // at that time. It doesn't need --user-data-dir to be correct anyway, since // the zygote itself doesn't access anything in that directory. if (process_type != ::switches::kZygoteProcess) { base::FilePath user_data_dir; if (base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) command_line->AppendSwitchPath(::switches::kUserDataDir, user_data_dir); } if (process_type == ::switches::kUtilityProcess || process_type == ::switches::kRendererProcess) { // Copy following switches to child process. static const char* const kCommonSwitchNames[] = { switches::kStandardSchemes, switches::kEnableSandbox, switches::kSecureSchemes, switches::kBypassCSPSchemes, switches::kCORSSchemes, switches::kFetchSchemes, switches::kServiceWorkerSchemes, switches::kStreamingSchemes}; command_line->CopySwitchesFrom(*base::CommandLine::ForCurrentProcess(), kCommonSwitchNames); if (process_type == ::switches::kUtilityProcess || content::RenderProcessHost::FromID(process_id)) { MaybeAppendSecureOriginsAllowlistSwitch(command_line); } } if (process_type == ::switches::kRendererProcess) { #if BUILDFLAG(IS_WIN) // Append --app-user-model-id. PWSTR current_app_id; if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&current_app_id))) { command_line->AppendSwitchNative(switches::kAppUserModelId, current_app_id); CoTaskMemFree(current_app_id); } #endif if (delegate_) { auto app_path = static_cast<api::App*>(delegate_)->GetAppPath(); command_line->AppendSwitchPath(switches::kAppPath, app_path); } auto env = base::Environment::Create(); if (env->HasVar("ELECTRON_PROFILE_INIT_SCRIPTS")) { command_line->AppendSwitch("profile-electron-init"); } // Extension background pages don't have WebContentsPreferences, but they // support WebSQL by default. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) content::RenderProcessHost* process = content::RenderProcessHost::FromID(process_id); if (extensions::ProcessMap::Get(process->GetBrowserContext()) ->Contains(process_id)) command_line->AppendSwitch(switches::kEnableWebSQL); #endif content::WebContents* web_contents = GetWebContentsFromProcessID(process_id); if (web_contents) { auto* web_preferences = WebContentsPreferences::From(web_contents); if (web_preferences) web_preferences->AppendCommandLineSwitches( command_line, IsRendererSubFrame(process_id)); } } } void ElectronBrowserClient::DidCreatePpapiPlugin( content::BrowserPpapiHost* host) {} // attempt to get api key from env std::string ElectronBrowserClient::GetGeolocationApiKey() { auto env = base::Environment::Create(); std::string api_key; env->GetVar("GOOGLE_API_KEY", &api_key); return api_key; } content::GeneratedCodeCacheSettings ElectronBrowserClient::GetGeneratedCodeCacheSettings( content::BrowserContext* context) { // TODO(deepak1556): Use platform cache directory. base::FilePath cache_path = context->GetPath(); // If we pass 0 for size, disk_cache will pick a default size using the // heuristics based on available disk size. These are implemented in // disk_cache::PreferredCacheSize in net/disk_cache/cache_util.cc. return content::GeneratedCodeCacheSettings(true, 0, cache_path); } void ElectronBrowserClient::AllowCertificateError( content::WebContents* web_contents, int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, bool is_main_frame_request, bool strict_enforcement, base::OnceCallback<void(content::CertificateRequestResultType)> callback) { if (delegate_) { delegate_->AllowCertificateError(web_contents, cert_error, ssl_info, request_url, is_main_frame_request, strict_enforcement, std::move(callback)); } } base::OnceClosure ElectronBrowserClient::SelectClientCertificate( content::BrowserContext* browser_context, content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, net::ClientCertIdentityList client_certs, std::unique_ptr<content::ClientCertificateDelegate> delegate) { if (client_certs.empty()) { delegate->ContinueWithCertificate(nullptr, nullptr); } else if (delegate_) { delegate_->SelectClientCertificate( browser_context, web_contents, cert_request_info, std::move(client_certs), std::move(delegate)); } return base::OnceClosure(); } bool ElectronBrowserClient::CanCreateWindow( content::RenderFrameHost* opener, const GURL& opener_url, const GURL& opener_top_level_frame_url, const url::Origin& source_origin, content::mojom::WindowContainerType container_type, const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& features, const std::string& raw_features, const scoped_refptr<network::ResourceRequestBody>& body, bool user_gesture, bool opener_suppressed, bool* no_javascript_access) { DCHECK_CURRENTLY_ON(BrowserThread::UI); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(opener); WebContentsPreferences* prefs = WebContentsPreferences::From(web_contents); if (prefs) { if (prefs->ShouldDisablePopups()) { // <webview> without allowpopups attribute should return // null from window.open calls return false; } else { *no_javascript_access = false; return true; } } if (delegate_) { return delegate_->CanCreateWindow( opener, opener_url, opener_top_level_frame_url, source_origin, container_type, target_url, referrer, frame_name, disposition, features, raw_features, body, user_gesture, opener_suppressed, no_javascript_access); } return false; } std::unique_ptr<content::VideoOverlayWindow> ElectronBrowserClient::CreateWindowForVideoPictureInPicture( content::VideoPictureInPictureWindowController* controller) { auto overlay_window = content::VideoOverlayWindow::Create(controller); #if BUILDFLAG(IS_WIN) std::wstring app_user_model_id = Browser::Get()->GetAppUserModelID(); if (!app_user_model_id.empty()) { auto* overlay_window_view = static_cast<VideoOverlayWindowViews*>(overlay_window.get()); ui::win::SetAppIdForWindow(app_user_model_id, overlay_window_view->GetNativeWindow() ->GetHost() ->GetAcceleratedWidget()); } #endif return overlay_window; } void ElectronBrowserClient::GetAdditionalAllowedSchemesForFileSystem( std::vector<std::string>* additional_schemes) { auto schemes_list = api::GetStandardSchemes(); if (!schemes_list.empty()) additional_schemes->insert(additional_schemes->end(), schemes_list.begin(), schemes_list.end()); additional_schemes->push_back(content::kChromeDevToolsScheme); additional_schemes->push_back(content::kChromeUIScheme); } void ElectronBrowserClient::GetAdditionalWebUISchemes( std::vector<std::string>* additional_schemes) { additional_schemes->push_back(content::kChromeDevToolsScheme); } void ElectronBrowserClient::SiteInstanceGotProcess( content::SiteInstance* site_instance) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto* browser_context = static_cast<ElectronBrowserContext*>(site_instance->GetBrowserContext()); if (!browser_context->IsOffTheRecord()) { extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); const extensions::Extension* extension = registry->enabled_extensions().GetExtensionOrAppByURL( site_instance->GetSiteURL()); if (!extension) return; extensions::ProcessMap::Get(browser_context) ->Insert(extension->id(), site_instance->GetProcess()->GetID()); } #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) } bool ElectronBrowserClient::IsSuitableHost( content::RenderProcessHost* process_host, const GURL& site_url) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto* browser_context = process_host->GetBrowserContext(); extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); extensions::ProcessMap* process_map = extensions::ProcessMap::Get(browser_context); // Otherwise, just make sure the process privilege matches the privilege // required by the site. RenderProcessHostPrivilege privilege_required = GetPrivilegeRequiredByUrl(site_url, registry); return GetProcessPrivilege(process_host, process_map, registry) == privilege_required; #else return content::ContentBrowserClient::IsSuitableHost(process_host, site_url); #endif } bool ElectronBrowserClient::ShouldUseProcessPerSite( content::BrowserContext* browser_context, const GURL& effective_url) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) const extensions::Extension* extension = GetEnabledExtensionFromEffectiveURL(browser_context, effective_url); return extension != nullptr; #else return content::ContentBrowserClient::ShouldUseProcessPerSite(browser_context, effective_url); #endif } void ElectronBrowserClient::GetMediaDeviceIDSalt( content::RenderFrameHost* rfh, const net::SiteForCookies& site_for_cookies, const blink::StorageKey& storage_key, base::OnceCallback<void(bool, const std::string&)> callback) { constexpr bool persistent_media_device_id_allowed = true; std::string persistent_media_device_id_salt = static_cast<ElectronBrowserContext*>(rfh->GetBrowserContext()) ->GetMediaDeviceIDSalt(); std::move(callback).Run(persistent_media_device_id_allowed, persistent_media_device_id_salt); } base::FilePath ElectronBrowserClient::GetLoggingFileName( const base::CommandLine& cmd_line) { return logging::GetLogFileName(cmd_line); } std::unique_ptr<net::ClientCertStore> ElectronBrowserClient::CreateClientCertStore( content::BrowserContext* browser_context) { #if BUILDFLAG(USE_NSS_CERTS) return std::make_unique<net::ClientCertStoreNSS>( net::ClientCertStoreNSS::PasswordDelegateFactory()); #elif BUILDFLAG(IS_WIN) return std::make_unique<net::ClientCertStoreWin>(); #elif BUILDFLAG(IS_MAC) return std::make_unique<net::ClientCertStoreMac>(); #elif defined(USE_OPENSSL) return std::unique_ptr<net::ClientCertStore>(); #endif } std::unique_ptr<device::LocationProvider> ElectronBrowserClient::OverrideSystemLocationProvider() { #if BUILDFLAG(OVERRIDE_LOCATION_PROVIDER) return std::make_unique<FakeLocationProvider>(); #else return nullptr; #endif } void ElectronBrowserClient::ConfigureNetworkContextParams( content::BrowserContext* browser_context, bool in_memory, const base::FilePath& relative_partition_path, network::mojom::NetworkContextParams* network_context_params, cert_verifier::mojom::CertVerifierCreationParams* cert_verifier_creation_params) { DCHECK(browser_context); return NetworkContextServiceFactory::GetForContext(browser_context) ->ConfigureNetworkContextParams(network_context_params, cert_verifier_creation_params); } network::mojom::NetworkContext* ElectronBrowserClient::GetSystemNetworkContext() { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(g_browser_process->system_network_context_manager()); return g_browser_process->system_network_context_manager()->GetContext(); } std::unique_ptr<content::BrowserMainParts> ElectronBrowserClient::CreateBrowserMainParts(bool /* is_integration_test */) { auto browser_main_parts = std::make_unique<ElectronBrowserMainParts>(); #if BUILDFLAG(IS_MAC) browser_main_parts_ = browser_main_parts.get(); #endif return browser_main_parts; } void ElectronBrowserClient::WebNotificationAllowed( content::RenderFrameHost* rfh, base::OnceCallback<void(bool, bool)> callback) { content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(rfh); if (!web_contents) { std::move(callback).Run(false, false); return; } auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); if (!permission_helper) { std::move(callback).Run(false, false); return; } permission_helper->RequestWebNotificationPermission( rfh, base::BindOnce(std::move(callback), web_contents->IsAudioMuted())); } void ElectronBrowserClient::RenderProcessHostDestroyed( content::RenderProcessHost* host) { int process_id = host->GetID(); pending_processes_.erase(process_id); renderer_is_subframe_.erase(process_id); host->RemoveObserver(this); } void ElectronBrowserClient::RenderProcessReady( content::RenderProcessHost* host) { if (delegate_) { static_cast<api::App*>(delegate_)->RenderProcessReady(host); } } void ElectronBrowserClient::RenderProcessExited( content::RenderProcessHost* host, const content::ChildProcessTerminationInfo& info) { if (delegate_) { static_cast<api::App*>(delegate_)->RenderProcessExited(host); } } void OnOpenExternal(const GURL& escaped_url, bool allowed) { if (allowed) { platform_util::OpenExternal( escaped_url, platform_util::OpenExternalOptions(), base::DoNothing()); } } void HandleExternalProtocolInUI( const GURL& url, content::WeakDocumentPtr document_ptr, content::WebContents::OnceGetter web_contents_getter, bool has_user_gesture) { content::WebContents* web_contents = std::move(web_contents_getter).Run(); if (!web_contents) return; auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); if (!permission_helper) return; content::RenderFrameHost* rfh = document_ptr.AsRenderFrameHostIfValid(); if (!rfh) { // If the render frame host is not valid it means it was a top level // navigation and the frame has already been disposed of. In this case we // take the current main frame and declare it responsible for the // transition. rfh = web_contents->GetPrimaryMainFrame(); } GURL escaped_url(base::EscapeExternalHandlerValue(url.spec())); auto callback = base::BindOnce(&OnOpenExternal, escaped_url); permission_helper->RequestOpenExternalPermission(rfh, std::move(callback), has_user_gesture, url); } bool ElectronBrowserClient::HandleExternalProtocol( const GURL& url, content::WebContents::Getter web_contents_getter, int frame_tree_node_id, content::NavigationUIData* navigation_data, bool is_primary_main_frame, bool is_in_fenced_frame_tree, network::mojom::WebSandboxFlags sandbox_flags, ui::PageTransition page_transition, bool has_user_gesture, const absl::optional<url::Origin>& initiating_origin, content::RenderFrameHost* initiator_document, mojo::PendingRemote<network::mojom::URLLoaderFactory>* out_factory) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&HandleExternalProtocolInUI, url, initiator_document ? initiator_document->GetWeakDocumentPtr() : content::WeakDocumentPtr(), std::move(web_contents_getter), has_user_gesture)); return true; } std::vector<std::unique_ptr<content::NavigationThrottle>> ElectronBrowserClient::CreateThrottlesForNavigation( content::NavigationHandle* handle) { std::vector<std::unique_ptr<content::NavigationThrottle>> throttles; throttles.push_back(std::make_unique<ElectronNavigationThrottle>(handle)); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) throttles.push_back( std::make_unique<extensions::ExtensionNavigationThrottle>(handle)); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) std::unique_ptr<content::NavigationThrottle> pdf_iframe_throttle = PDFIFrameNavigationThrottle::MaybeCreateThrottleFor(handle); if (pdf_iframe_throttle) throttles.push_back(std::move(pdf_iframe_throttle)); std::unique_ptr<content::NavigationThrottle> pdf_throttle = pdf::PdfNavigationThrottle::MaybeCreateThrottleFor( handle, std::make_unique<ChromePdfStreamDelegate>()); if (pdf_throttle) throttles.push_back(std::move(pdf_throttle)); #endif return throttles; } content::MediaObserver* ElectronBrowserClient::GetMediaObserver() { return MediaCaptureDevicesDispatcher::GetInstance(); } std::unique_ptr<content::DevToolsManagerDelegate> ElectronBrowserClient::CreateDevToolsManagerDelegate() { return std::make_unique<DevToolsManagerDelegate>(); } NotificationPresenter* ElectronBrowserClient::GetNotificationPresenter() { if (!notification_presenter_) { notification_presenter_.reset(NotificationPresenter::Create()); } return notification_presenter_.get(); } content::PlatformNotificationService* ElectronBrowserClient::GetPlatformNotificationService() { if (!notification_service_) { notification_service_ = std::make_unique<PlatformNotificationService>(this); } return notification_service_.get(); } base::FilePath ElectronBrowserClient::GetDefaultDownloadDirectory() { base::FilePath download_path; if (base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_path)) return download_path; return base::FilePath(); } scoped_refptr<network::SharedURLLoaderFactory> ElectronBrowserClient::GetSystemSharedURLLoaderFactory() { if (!g_browser_process) return nullptr; return g_browser_process->shared_url_loader_factory(); } void ElectronBrowserClient::OnNetworkServiceCreated( network::mojom::NetworkService* network_service) { if (!g_browser_process) return; g_browser_process->system_network_context_manager()->OnNetworkServiceCreated( network_service); } std::vector<base::FilePath> ElectronBrowserClient::GetNetworkContextsParentDirectory() { base::FilePath session_data; base::PathService::Get(DIR_SESSION_DATA, &session_data); DCHECK(!session_data.empty()); return {session_data}; } std::string ElectronBrowserClient::GetProduct() { return "Chrome/" CHROME_VERSION_STRING; } std::string ElectronBrowserClient::GetUserAgent() { if (user_agent_override_.empty()) return GetApplicationUserAgent(); return user_agent_override_; } void ElectronBrowserClient::SetUserAgent(const std::string& user_agent) { user_agent_override_ = user_agent; } blink::UserAgentMetadata ElectronBrowserClient::GetUserAgentMetadata() { return embedder_support::GetUserAgentMetadata(); } void ElectronBrowserClient::RegisterNonNetworkNavigationURLLoaderFactories( int frame_tree_node_id, ukm::SourceIdObj ukm_source_id, NonNetworkURLLoaderFactoryMap* factories) { content::WebContents* web_contents = content::WebContents::FromFrameTreeNodeId(frame_tree_node_id); content::BrowserContext* context = web_contents->GetBrowserContext(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) factories->emplace( extensions::kExtensionScheme, extensions::CreateExtensionNavigationURLLoaderFactory( context, ukm_source_id, false /* we don't support extensions::WebViewGuest */)); #endif // Always allow navigating to file:// URLs. auto* protocol_registry = ProtocolRegistry::FromBrowserContext(context); protocol_registry->RegisterURLLoaderFactories(factories, true /* allow_file_access */); } void ElectronBrowserClient:: RegisterNonNetworkWorkerMainResourceURLLoaderFactories( content::BrowserContext* browser_context, NonNetworkURLLoaderFactoryMap* factories) { auto* protocol_registry = ProtocolRegistry::FromBrowserContext(browser_context); // Workers are not allowed to request file:// URLs, there is no particular // reason for it, and we could consider supporting it in future. protocol_registry->RegisterURLLoaderFactories(factories, false /* allow_file_access */); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) namespace { // The FileURLLoaderFactory provided to the extension background pages. // Checks with the ChildProcessSecurityPolicy to validate the file access. class FileURLLoaderFactory : public network::SelfDeletingURLLoaderFactory { public: static mojo::PendingRemote<network::mojom::URLLoaderFactory> Create( int child_id) { mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote; // The FileURLLoaderFactory will delete itself when there are no more // receivers - see the SelfDeletingURLLoaderFactory::OnDisconnect method. new FileURLLoaderFactory(child_id, pending_remote.InitWithNewPipeAndPassReceiver()); return pending_remote; } // disable copy FileURLLoaderFactory(const FileURLLoaderFactory&) = delete; FileURLLoaderFactory& operator=(const FileURLLoaderFactory&) = delete; private: explicit FileURLLoaderFactory( int child_id, mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver) : network::SelfDeletingURLLoaderFactory(std::move(factory_receiver)), child_id_(child_id) {} ~FileURLLoaderFactory() override = default; // network::mojom::URLLoaderFactory: void CreateLoaderAndStart( mojo::PendingReceiver<network::mojom::URLLoader> loader, int32_t request_id, uint32_t options, const network::ResourceRequest& request, mojo::PendingRemote<network::mojom::URLLoaderClient> client, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) override { if (!content::ChildProcessSecurityPolicy::GetInstance()->CanRequestURL( child_id_, request.url)) { mojo::Remote<network::mojom::URLLoaderClient>(std::move(client)) ->OnComplete( network::URLLoaderCompletionStatus(net::ERR_ACCESS_DENIED)); return; } content::CreateFileURLLoaderBypassingSecurityChecks( request, std::move(loader), std::move(client), /*observer=*/nullptr, /* allow_directory_listing */ true); } int child_id_; }; } // namespace #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void ElectronBrowserClient::RegisterNonNetworkSubresourceURLLoaderFactories( int render_process_id, int render_frame_id, const absl::optional<url::Origin>& request_initiator_origin, NonNetworkURLLoaderFactoryMap* factories) { auto* render_process_host = content::RenderProcessHost::FromID(render_process_id); DCHECK(render_process_host); if (!render_process_host || !render_process_host->GetBrowserContext()) return; content::RenderFrameHost* frame_host = content::RenderFrameHost::FromID(render_process_id, render_frame_id); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(frame_host); // Allow accessing file:// subresources from non-file protocols if web // security is disabled. bool allow_file_access = false; if (web_contents) { const auto& web_preferences = web_contents->GetOrCreateWebPreferences(); if (!web_preferences.web_security_enabled) allow_file_access = true; } ProtocolRegistry::FromBrowserContext(render_process_host->GetBrowserContext()) ->RegisterURLLoaderFactories(factories, allow_file_access); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto factory = extensions::CreateExtensionURLLoaderFactory(render_process_id, render_frame_id); if (factory) factories->emplace(extensions::kExtensionScheme, std::move(factory)); if (!web_contents) return; extensions::ElectronExtensionWebContentsObserver* web_observer = extensions::ElectronExtensionWebContentsObserver::FromWebContents( web_contents); // There is nothing to do if no ElectronExtensionWebContentsObserver is // attached to the |web_contents|. if (!web_observer) return; const extensions::Extension* extension = web_observer->GetExtensionFromFrame(frame_host, false); if (!extension) return; // Support for chrome:// scheme if appropriate. if (extension->is_extension() && extensions::Manifest::IsComponentLocation(extension->location())) { // Components of chrome that are implemented as extensions or platform apps // are allowed to use chrome://resources/ and chrome://theme/ URLs. factories->emplace(content::kChromeUIScheme, content::CreateWebUIURLLoaderFactory( frame_host, content::kChromeUIScheme, {content::kChromeUIResourcesHost})); } // Extensions with the necessary permissions get access to file:// URLs that // gets approval from ChildProcessSecurityPolicy. Keep this logic in sync with // ExtensionWebContentsObserver::RenderFrameCreated. extensions::Manifest::Type type = extension->GetType(); if (type == extensions::Manifest::TYPE_EXTENSION && AllowFileAccess(extension->id(), web_contents->GetBrowserContext())) { factories->emplace(url::kFileScheme, FileURLLoaderFactory::Create(render_process_id)); } #endif } void ElectronBrowserClient:: RegisterNonNetworkServiceWorkerUpdateURLLoaderFactories( content::BrowserContext* browser_context, NonNetworkURLLoaderFactoryMap* factories) { DCHECK(browser_context); DCHECK(factories); auto* protocol_registry = ProtocolRegistry::FromBrowserContext(browser_context); protocol_registry->RegisterURLLoaderFactories(factories, false /* allow_file_access */); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) factories->emplace( extensions::kExtensionScheme, extensions::CreateExtensionServiceWorkerScriptURLLoaderFactory( browser_context)); #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) } bool ElectronBrowserClient::ShouldTreatURLSchemeAsFirstPartyWhenTopLevel( base::StringPiece scheme, bool is_embedded_origin_secure) { if (is_embedded_origin_secure && scheme == content::kChromeUIScheme) return true; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) return scheme == extensions::kExtensionScheme; #else return false; #endif } bool ElectronBrowserClient::WillInterceptWebSocket( content::RenderFrameHost* frame) { if (!frame) return false; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto* browser_context = frame->GetProcess()->GetBrowserContext(); auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context); // NOTE: Some unit test environments do not initialize // BrowserContextKeyedAPI factories for e.g. WebRequest. if (!web_request.get()) return false; bool has_listener = web_request->HasListener(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) const auto* web_request_api = extensions::BrowserContextKeyedAPIFactory<extensions::WebRequestAPI>::Get( browser_context); if (web_request_api) has_listener |= web_request_api->MayHaveProxies(); #endif return has_listener; } void ElectronBrowserClient::CreateWebSocket( content::RenderFrameHost* frame, WebSocketFactory factory, const GURL& url, const net::SiteForCookies& site_for_cookies, const absl::optional<std::string>& user_agent, mojo::PendingRemote<network::mojom::WebSocketHandshakeClient> handshake_client) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto* browser_context = frame->GetProcess()->GetBrowserContext(); auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context); DCHECK(web_request.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!web_request->HasListener()) { auto* web_request_api = extensions::BrowserContextKeyedAPIFactory< extensions::WebRequestAPI>::Get(browser_context); if (web_request_api && web_request_api->MayHaveProxies()) { web_request_api->ProxyWebSocket(frame, std::move(factory), url, site_for_cookies, user_agent, std::move(handshake_client)); return; } } #endif ProxyingWebSocket::StartProxying( web_request.get(), std::move(factory), url, site_for_cookies, user_agent, std::move(handshake_client), true, frame->GetProcess()->GetID(), frame->GetRoutingID(), frame->GetLastCommittedOrigin(), browser_context, &next_id_); } bool ElectronBrowserClient::WillCreateURLLoaderFactory( content::BrowserContext* browser_context, content::RenderFrameHost* frame_host, int render_process_id, URLLoaderFactoryType type, const url::Origin& request_initiator, absl::optional<int64_t> navigation_id, ukm::SourceIdObj ukm_source_id, mojo::PendingReceiver<network::mojom::URLLoaderFactory>* factory_receiver, mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>* header_client, bool* bypass_redirect_checks, bool* disable_secure_dns, network::mojom::URLLoaderFactoryOverridePtr* factory_override, scoped_refptr<base::SequencedTaskRunner> navigation_response_task_runner) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context); DCHECK(web_request.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!web_request->HasListener()) { auto* web_request_api = extensions::BrowserContextKeyedAPIFactory< extensions::WebRequestAPI>::Get(browser_context); DCHECK(web_request_api); bool use_proxy_for_web_request = web_request_api->MaybeProxyURLLoaderFactory( browser_context, frame_host, render_process_id, type, navigation_id, ukm_source_id, factory_receiver, header_client, navigation_response_task_runner); if (bypass_redirect_checks) *bypass_redirect_checks = use_proxy_for_web_request; if (use_proxy_for_web_request) return true; } #endif auto proxied_receiver = std::move(*factory_receiver); mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory_remote; *factory_receiver = target_factory_remote.InitWithNewPipeAndPassReceiver(); // Required by WebRequestInfoInitParams. // // Note that in Electron we allow webRequest to capture requests sent from // browser process, so creation of |navigation_ui_data| is different from // Chromium which only does for renderer-initialized navigations. std::unique_ptr<extensions::ExtensionNavigationUIData> navigation_ui_data; if (navigation_id.has_value()) { navigation_ui_data = std::make_unique<extensions::ExtensionNavigationUIData>(); } mojo::PendingReceiver<network::mojom::TrustedURLLoaderHeaderClient> header_client_receiver; if (header_client) header_client_receiver = header_client->InitWithNewPipeAndPassReceiver(); auto* protocol_registry = ProtocolRegistry::FromBrowserContext(browser_context); new ProxyingURLLoaderFactory( web_request.get(), protocol_registry->intercept_handlers(), render_process_id, frame_host ? frame_host->GetRoutingID() : MSG_ROUTING_NONE, &next_id_, std::move(navigation_ui_data), std::move(navigation_id), std::move(proxied_receiver), std::move(target_factory_remote), std::move(header_client_receiver), type); return true; } std::vector<std::unique_ptr<content::URLLoaderRequestInterceptor>> ElectronBrowserClient::WillCreateURLLoaderRequestInterceptors( content::NavigationUIData* navigation_ui_data, int frame_tree_node_id, int64_t navigation_id, scoped_refptr<base::SequencedTaskRunner> navigation_response_task_runner) { std::vector<std::unique_ptr<content::URLLoaderRequestInterceptor>> interceptors; #if BUILDFLAG(ENABLE_PDF_VIEWER) { std::unique_ptr<content::URLLoaderRequestInterceptor> pdf_interceptor = pdf::PdfURLLoaderRequestInterceptor::MaybeCreateInterceptor( frame_tree_node_id, std::make_unique<ChromePdfStreamDelegate>()); if (pdf_interceptor) interceptors.push_back(std::move(pdf_interceptor)); } #endif return interceptors; } void ElectronBrowserClient::OverrideURLLoaderFactoryParams( content::BrowserContext* browser_context, const url::Origin& origin, bool is_for_isolated_world, network::mojom::URLLoaderFactoryParams* factory_params) { if (factory_params->top_frame_id) { // Bypass CORB and CORS when web security is disabled. auto* rfh = content::RenderFrameHost::FromFrameToken( content::GlobalRenderFrameHostToken( factory_params->process_id, blink::LocalFrameToken(factory_params->top_frame_id.value()))); auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); auto* prefs = WebContentsPreferences::From(web_contents); if (prefs && !prefs->IsWebSecurityEnabled()) { factory_params->is_corb_enabled = false; factory_params->disable_web_security = true; } } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::URLLoaderFactoryManager::OverrideURLLoaderFactoryParams( browser_context, origin, is_for_isolated_world, factory_params); #endif } void ElectronBrowserClient:: RegisterAssociatedInterfaceBindersForRenderFrameHost( content::RenderFrameHost& render_frame_host, // NOLINT(runtime/references) blink::AssociatedInterfaceRegistry& associated_registry) { // NOLINT(runtime/references) auto* contents = content::WebContents::FromRenderFrameHost(&render_frame_host); if (contents) { auto* prefs = WebContentsPreferences::From(contents); if (render_frame_host.GetFrameTreeNodeId() == contents->GetPrimaryMainFrame()->GetFrameTreeNodeId() || (prefs && prefs->AllowsNodeIntegrationInSubFrames())) { associated_registry.AddInterface<mojom::ElectronApiIPC>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<mojom::ElectronApiIPC> receiver) { ElectronApiIPCHandlerImpl::Create(render_frame_host, std::move(receiver)); }, &render_frame_host)); } } associated_registry.AddInterface<mojom::ElectronWebContentsUtility>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<mojom::ElectronWebContentsUtility> receiver) { ElectronWebContentsUtilityHandlerImpl::Create(render_frame_host, std::move(receiver)); }, &render_frame_host)); associated_registry.AddInterface<mojom::ElectronAutofillDriver>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<mojom::ElectronAutofillDriver> receiver) { AutofillDriverFactory::BindAutofillDriver(std::move(receiver), render_frame_host); }, &render_frame_host)); #if BUILDFLAG(ENABLE_PRINTING) associated_registry.AddInterface<printing::mojom::PrintManagerHost>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<printing::mojom::PrintManagerHost> receiver) { PrintViewManagerElectron::BindPrintManagerHost(std::move(receiver), render_frame_host); }, &render_frame_host)); #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) associated_registry.AddInterface<extensions::mojom::LocalFrameHost>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<extensions::mojom::LocalFrameHost> receiver) { extensions::ExtensionWebContentsObserver::BindLocalFrameHost( std::move(receiver), render_frame_host); }, &render_frame_host)); associated_registry.AddInterface<guest_view::mojom::GuestViewHost>( base::BindRepeating(&extensions::ExtensionsGuestView::CreateForComponents, render_frame_host.GetGlobalId())); associated_registry.AddInterface<extensions::mojom::GuestView>( base::BindRepeating(&extensions::ExtensionsGuestView::CreateForExtensions, render_frame_host.GetGlobalId())); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) associated_registry.AddInterface<pdf::mojom::PdfService>(base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<pdf::mojom::PdfService> receiver) { pdf::PDFDocumentHelper::BindPdfService( std::move(receiver), render_frame_host, std::make_unique<ElectronPDFDocumentHelperClient>()); }, &render_frame_host)); #endif } std::string ElectronBrowserClient::GetApplicationLocale() { if (BrowserThread::CurrentlyOn(BrowserThread::IO)) return g_io_thread_application_locale.Get(); return *g_application_locale; } bool ElectronBrowserClient::ShouldEnableStrictSiteIsolation() { // Enable site isolation. It is off by default in Chromium <= 69. return true; } void ElectronBrowserClient::BindHostReceiverForRenderer( content::RenderProcessHost* render_process_host, mojo::GenericPendingReceiver receiver) { #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) if (auto host_receiver = receiver.As<spellcheck::mojom::SpellCheckHost>()) { SpellCheckHostChromeImpl::Create(render_process_host->GetID(), std::move(host_receiver)); return; } #endif } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void BindMimeHandlerService( content::RenderFrameHost* frame_host, mojo::PendingReceiver<extensions::mime_handler::MimeHandlerService> receiver) { content::WebContents* contents = content::WebContents::FromRenderFrameHost(frame_host); auto* guest_view = extensions::MimeHandlerViewGuest::FromWebContents(contents); if (!guest_view) return; extensions::MimeHandlerServiceImpl::Create(guest_view->GetStreamWeakPtr(), std::move(receiver)); } void BindBeforeUnloadControl( content::RenderFrameHost* frame_host, mojo::PendingReceiver<extensions::mime_handler::BeforeUnloadControl> receiver) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame_host); if (!web_contents) return; auto* guest_view = extensions::MimeHandlerViewGuest::FromWebContents(web_contents); if (!guest_view) return; guest_view->FuseBeforeUnloadControl(std::move(receiver)); } #endif void ElectronBrowserClient::ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) associated_registry->AddInterface<extensions::mojom::EventRouter>( base::BindRepeating(&extensions::EventRouter::BindForRenderer, render_process_host->GetID())); associated_registry->AddInterface<extensions::mojom::RendererHost>( base::BindRepeating(&extensions::RendererStartupHelper::BindForRenderer, render_process_host->GetID())); associated_registry->AddInterface<extensions::mojom::ServiceWorkerHost>( base::BindRepeating(&extensions::ServiceWorkerHost::BindReceiver, render_process_host->GetID())); #endif } void ElectronBrowserClient::RegisterBrowserInterfaceBindersForFrame( content::RenderFrameHost* render_frame_host, mojo::BinderMapWithContext<content::RenderFrameHost*>* map) { map->Add<network_hints::mojom::NetworkHintsHandler>( base::BindRepeating(&BindNetworkHintsHandler)); map->Add<blink::mojom::BadgeService>( base::BindRepeating(&badging::BadgeManager::BindFrameReceiver)); map->Add<blink::mojom::KeyboardLockService>(base::BindRepeating( &content::KeyboardLockServiceImpl::CreateMojoService)); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) map->Add<extensions::mime_handler::MimeHandlerService>( base::BindRepeating(&BindMimeHandlerService)); map->Add<extensions::mime_handler::BeforeUnloadControl>( base::BindRepeating(&BindBeforeUnloadControl)); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); if (!web_contents) return; const GURL& site = render_frame_host->GetSiteInstance()->GetSiteURL(); if (!site.SchemeIs(extensions::kExtensionScheme)) return; content::BrowserContext* browser_context = render_frame_host->GetProcess()->GetBrowserContext(); auto* extension = extensions::ExtensionRegistry::Get(browser_context) ->enabled_extensions() .GetByID(site.host()); if (!extension) return; extensions::ExtensionsBrowserClient::Get() ->RegisterBrowserInterfaceBindersForFrame(map, render_frame_host, extension); #endif } #if BUILDFLAG(IS_LINUX) void ElectronBrowserClient::GetAdditionalMappedFilesForChildProcess( const base::CommandLine& command_line, int child_process_id, content::PosixFileDescriptorInfo* mappings) { int crash_signal_fd = GetCrashSignalFD(command_line); if (crash_signal_fd >= 0) { mappings->Share(kCrashDumpSignal, crash_signal_fd); } } #endif std::unique_ptr<content::LoginDelegate> ElectronBrowserClient::CreateLoginDelegate( const net::AuthChallengeInfo& auth_info, content::WebContents* web_contents, const content::GlobalRequestID& request_id, bool is_main_frame, const GURL& url, scoped_refptr<net::HttpResponseHeaders> response_headers, bool first_auth_attempt, LoginAuthRequiredCallback auth_required_callback) { return std::make_unique<LoginHandler>( auth_info, web_contents, is_main_frame, url, response_headers, first_auth_attempt, std::move(auth_required_callback)); } std::vector<std::unique_ptr<blink::URLLoaderThrottle>> ElectronBrowserClient::CreateURLLoaderThrottles( const network::ResourceRequest& request, content::BrowserContext* browser_context, const base::RepeatingCallback<content::WebContents*()>& wc_getter, content::NavigationUIData* navigation_ui_data, int frame_tree_node_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); std::vector<std::unique_ptr<blink::URLLoaderThrottle>> result; #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) result.push_back(std::make_unique<PluginResponseInterceptorURLLoaderThrottle>( request.destination, frame_tree_node_id)); #endif return result; } base::flat_set<std::string> ElectronBrowserClient::GetPluginMimeTypesWithExternalHandlers( content::BrowserContext* browser_context) { base::flat_set<std::string> mime_types; #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto map = PluginUtils::GetMimeTypeToExtensionIdMap(browser_context); for (const auto& pair : map) mime_types.insert(pair.first); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) mime_types.insert(pdf::kInternalPluginMimeType); #endif return mime_types; } content::SerialDelegate* ElectronBrowserClient::GetSerialDelegate() { if (!serial_delegate_) serial_delegate_ = std::make_unique<ElectronSerialDelegate>(); return serial_delegate_.get(); } content::BluetoothDelegate* ElectronBrowserClient::GetBluetoothDelegate() { if (!bluetooth_delegate_) bluetooth_delegate_ = std::make_unique<ElectronBluetoothDelegate>(); return bluetooth_delegate_.get(); } content::UsbDelegate* ElectronBrowserClient::GetUsbDelegate() { if (!usb_delegate_) usb_delegate_ = std::make_unique<ElectronUsbDelegate>(); return usb_delegate_.get(); } void BindBadgeServiceForServiceWorker( const content::ServiceWorkerVersionBaseInfo& info, mojo::PendingReceiver<blink::mojom::BadgeService> receiver) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::RenderProcessHost* render_process_host = content::RenderProcessHost::FromID(info.process_id); if (!render_process_host) return; badging::BadgeManager::BindServiceWorkerReceiver( render_process_host, info.scope, std::move(receiver)); } void ElectronBrowserClient::RegisterBrowserInterfaceBindersForServiceWorker( content::BrowserContext* browser_context, const content::ServiceWorkerVersionBaseInfo& service_worker_version_info, mojo::BinderMapWithContext<const content::ServiceWorkerVersionBaseInfo&>* map) { map->Add<blink::mojom::BadgeService>( base::BindRepeating(&BindBadgeServiceForServiceWorker)); } #if BUILDFLAG(IS_MAC) device::GeolocationManager* ElectronBrowserClient::GetGeolocationManager() { return device::GeolocationManager::GetInstance(); } #endif content::HidDelegate* ElectronBrowserClient::GetHidDelegate() { if (!hid_delegate_) hid_delegate_ = std::make_unique<ElectronHidDelegate>(); return hid_delegate_.get(); } content::WebAuthenticationDelegate* ElectronBrowserClient::GetWebAuthenticationDelegate() { if (!web_authentication_delegate_) { web_authentication_delegate_ = std::make_unique<ElectronWebAuthenticationDelegate>(); } return web_authentication_delegate_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,439
Convert legacy IPC calls in extensions code to use mojo
https://chromium-review.googlesource.com/c/chromium/src/+/4995136 turned on the build flag to use the new mojo IPC pipe for messaging in extensions. In #40418 we turned this off because we have not converted our extensions code to use mojo. It appears that in chromium the follow CLs were landed to use mojo in extensions: - 4947890: [extensions] Convert Extension Messaging APIs over to mojo | https://chromium-review.googlesource.com/c/chromium/src/+/4947890 - 4950041: [extensions] Port Event Acks to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4950041 - 4902564: [extensions] Move WakeEventPage to mojom::RendererHost | https://chromium-review.googlesource.com/c/chromium/src/+/4902564 - 4956841: [extensions] Port GetMessageBundle over to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4956841 Once these changes have landed, the following flag override in build/args/all.gn should be removed: `enable_extensions_legacy_ipc = true`
https://github.com/electron/electron/issues/40439
https://github.com/electron/electron/pull/40511
088affd4a4311e03b8ed400cdf5d82f1db2125a4
371bca69b69351dc47d4b4dcfdf9a626f43b3b51
2023-11-02T18:50:40Z
c++
2023-11-15T14:30:47Z
shell/browser/electron_browser_client.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_ELECTRON_BROWSER_CLIENT_H_ #define ELECTRON_SHELL_BROWSER_ELECTRON_BROWSER_CLIENT_H_ #include <map> #include <memory> #include <set> #include <string> #include <vector> #include "base/files/file_path.h" #include "base/memory/raw_ptr.h" #include "base/synchronization/lock.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/render_process_host_observer.h" #include "content/public/browser/web_contents.h" #include "electron/buildflags/buildflags.h" #include "net/ssl/client_cert_identity.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "shell/browser/bluetooth/electron_bluetooth_delegate.h" #include "shell/browser/hid/electron_hid_delegate.h" #include "shell/browser/serial/electron_serial_delegate.h" #include "shell/browser/usb/electron_usb_delegate.h" #include "third_party/blink/public/mojom/badging/badging.mojom-forward.h" namespace content { class ClientCertificateDelegate; class QuotaPermissionContext; } // namespace content namespace net { class SSLCertRequestInfo; } namespace electron { class ElectronBrowserMainParts; class NotificationPresenter; class PlatformNotificationService; class ElectronWebAuthenticationDelegate; class ElectronBrowserClient : public content::ContentBrowserClient, public content::RenderProcessHostObserver { public: static ElectronBrowserClient* Get(); static void SetApplicationLocale(const std::string& locale); ElectronBrowserClient(); ~ElectronBrowserClient() override; // disable copy ElectronBrowserClient(const ElectronBrowserClient&) = delete; ElectronBrowserClient& operator=(const ElectronBrowserClient&) = delete; using Delegate = content::ContentBrowserClient; void set_delegate(Delegate* delegate) { delegate_ = delegate; } // Returns the WebContents for pending render processes. content::WebContents* GetWebContentsFromProcessID(int process_id); NotificationPresenter* GetNotificationPresenter(); void WebNotificationAllowed(content::RenderFrameHost* rfh, base::OnceCallback<void(bool, bool)> callback); // content::NavigatorDelegate std::vector<std::unique_ptr<content::NavigationThrottle>> CreateThrottlesForNavigation(content::NavigationHandle* handle) override; // content::ContentBrowserClient: std::string GetApplicationLocale() override; bool ShouldEnableStrictSiteIsolation() override; void BindHostReceiverForRenderer( content::RenderProcessHost* render_process_host, mojo::GenericPendingReceiver receiver) override; void ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) override; void RegisterBrowserInterfaceBindersForFrame( content::RenderFrameHost* render_frame_host, mojo::BinderMapWithContext<content::RenderFrameHost*>* map) override; void RegisterBrowserInterfaceBindersForServiceWorker( content::BrowserContext* browser_context, const content::ServiceWorkerVersionBaseInfo& service_worker_version_info, mojo::BinderMapWithContext<const content::ServiceWorkerVersionBaseInfo&>* map) override; #if BUILDFLAG(IS_LINUX) void GetAdditionalMappedFilesForChildProcess( const base::CommandLine& command_line, int child_process_id, content::PosixFileDescriptorInfo* mappings) override; #endif std::string GetUserAgent() override; void SetUserAgent(const std::string& user_agent); blink::UserAgentMetadata GetUserAgentMetadata() override; content::SerialDelegate* GetSerialDelegate() override; content::BluetoothDelegate* GetBluetoothDelegate() override; content::HidDelegate* GetHidDelegate() override; content::UsbDelegate* GetUsbDelegate() override; content::WebAuthenticationDelegate* GetWebAuthenticationDelegate() override; #if BUILDFLAG(IS_MAC) device::GeolocationManager* GetGeolocationManager() override; #endif content::PlatformNotificationService* GetPlatformNotificationService(); protected: void RenderProcessWillLaunch(content::RenderProcessHost* host) override; content::SpeechRecognitionManagerDelegate* CreateSpeechRecognitionManagerDelegate() override; content::TtsPlatform* GetTtsPlatform() override; void OverrideWebkitPrefs(content::WebContents* web_contents, blink::web_pref::WebPreferences* prefs) override; void RegisterPendingSiteInstance( content::RenderFrameHost* render_frame_host, content::SiteInstance* pending_site_instance) override; void AppendExtraCommandLineSwitches(base::CommandLine* command_line, int child_process_id) override; void DidCreatePpapiPlugin(content::BrowserPpapiHost* browser_host) override; std::string GetGeolocationApiKey() override; content::GeneratedCodeCacheSettings GetGeneratedCodeCacheSettings( content::BrowserContext* context) override; void AllowCertificateError( content::WebContents* web_contents, int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, bool is_main_frame_request, bool strict_enforcement, base::OnceCallback<void(content::CertificateRequestResultType)> callback) override; base::OnceClosure SelectClientCertificate( content::BrowserContext* browser_context, content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, net::ClientCertIdentityList client_certs, std::unique_ptr<content::ClientCertificateDelegate> delegate) override; bool CanCreateWindow(content::RenderFrameHost* opener, const GURL& opener_url, const GURL& opener_top_level_frame_url, const url::Origin& source_origin, content::mojom::WindowContainerType container_type, const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& features, const std::string& raw_features, const scoped_refptr<network::ResourceRequestBody>& body, bool user_gesture, bool opener_suppressed, bool* no_javascript_access) override; std::unique_ptr<content::VideoOverlayWindow> CreateWindowForVideoPictureInPicture( content::VideoPictureInPictureWindowController* controller) override; void GetAdditionalAllowedSchemesForFileSystem( std::vector<std::string>* additional_schemes) override; void GetAdditionalWebUISchemes( std::vector<std::string>* additional_schemes) override; std::unique_ptr<net::ClientCertStore> CreateClientCertStore( content::BrowserContext* browser_context) override; std::unique_ptr<device::LocationProvider> OverrideSystemLocationProvider() override; void ConfigureNetworkContextParams( content::BrowserContext* browser_context, bool in_memory, const base::FilePath& relative_partition_path, network::mojom::NetworkContextParams* network_context_params, cert_verifier::mojom::CertVerifierCreationParams* cert_verifier_creation_params) override; network::mojom::NetworkContext* GetSystemNetworkContext() override; content::MediaObserver* GetMediaObserver() override; std::unique_ptr<content::DevToolsManagerDelegate> CreateDevToolsManagerDelegate() override; std::unique_ptr<content::BrowserMainParts> CreateBrowserMainParts( bool /* is_integration_test */) override; base::FilePath GetDefaultDownloadDirectory() override; scoped_refptr<network::SharedURLLoaderFactory> GetSystemSharedURLLoaderFactory() override; void OnNetworkServiceCreated( network::mojom::NetworkService* network_service) override; std::vector<base::FilePath> GetNetworkContextsParentDirectory() override; std::string GetProduct() override; void RegisterNonNetworkNavigationURLLoaderFactories( int frame_tree_node_id, ukm::SourceIdObj ukm_source_id, NonNetworkURLLoaderFactoryMap* factories) override; void RegisterNonNetworkWorkerMainResourceURLLoaderFactories( content::BrowserContext* browser_context, NonNetworkURLLoaderFactoryMap* factories) override; void RegisterNonNetworkSubresourceURLLoaderFactories( int render_process_id, int render_frame_id, const absl::optional<url::Origin>& request_initiator_origin, NonNetworkURLLoaderFactoryMap* factories) override; void RegisterNonNetworkServiceWorkerUpdateURLLoaderFactories( content::BrowserContext* browser_context, NonNetworkURLLoaderFactoryMap* factories) override; void CreateWebSocket( content::RenderFrameHost* frame, WebSocketFactory factory, const GURL& url, const net::SiteForCookies& site_for_cookies, const absl::optional<std::string>& user_agent, mojo::PendingRemote<network::mojom::WebSocketHandshakeClient> handshake_client) override; bool WillInterceptWebSocket(content::RenderFrameHost*) override; bool WillCreateURLLoaderFactory( content::BrowserContext* browser_context, content::RenderFrameHost* frame, int render_process_id, URLLoaderFactoryType type, const url::Origin& request_initiator, absl::optional<int64_t> navigation_id, ukm::SourceIdObj ukm_source_id, mojo::PendingReceiver<network::mojom::URLLoaderFactory>* factory_receiver, mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>* header_client, bool* bypass_redirect_checks, bool* disable_secure_dns, network::mojom::URLLoaderFactoryOverridePtr* factory_override, scoped_refptr<base::SequencedTaskRunner> navigation_response_task_runner) override; std::vector<std::unique_ptr<content::URLLoaderRequestInterceptor>> WillCreateURLLoaderRequestInterceptors( content::NavigationUIData* navigation_ui_data, int frame_tree_node_id, int64_t navigation_id, scoped_refptr<base::SequencedTaskRunner> navigation_response_task_runner) override; bool ShouldTreatURLSchemeAsFirstPartyWhenTopLevel( base::StringPiece scheme, bool is_embedded_origin_secure) override; void OverrideURLLoaderFactoryParams( content::BrowserContext* browser_context, const url::Origin& origin, bool is_for_isolated_world, network::mojom::URLLoaderFactoryParams* factory_params) override; void RegisterAssociatedInterfaceBindersForRenderFrameHost( content::RenderFrameHost& render_frame_host, blink::AssociatedInterfaceRegistry& associated_registry) override; bool HandleExternalProtocol( const GURL& url, content::WebContents::Getter web_contents_getter, int frame_tree_node_id, content::NavigationUIData* navigation_data, bool is_primary_main_frame, bool is_in_fenced_frame_tree, network::mojom::WebSandboxFlags sandbox_flags, ui::PageTransition page_transition, bool has_user_gesture, const absl::optional<url::Origin>& initiating_origin, content::RenderFrameHost* initiator_document, mojo::PendingRemote<network::mojom::URLLoaderFactory>* out_factory) override; std::unique_ptr<content::LoginDelegate> CreateLoginDelegate( const net::AuthChallengeInfo& auth_info, content::WebContents* web_contents, const content::GlobalRequestID& request_id, bool is_main_frame, const GURL& url, scoped_refptr<net::HttpResponseHeaders> response_headers, bool first_auth_attempt, LoginAuthRequiredCallback auth_required_callback) override; void SiteInstanceGotProcess(content::SiteInstance* site_instance) override; std::vector<std::unique_ptr<blink::URLLoaderThrottle>> CreateURLLoaderThrottles( const network::ResourceRequest& request, content::BrowserContext* browser_context, const base::RepeatingCallback<content::WebContents*()>& wc_getter, content::NavigationUIData* navigation_ui_data, int frame_tree_node_id) override; base::flat_set<std::string> GetPluginMimeTypesWithExternalHandlers( content::BrowserContext* browser_context) override; bool IsSuitableHost(content::RenderProcessHost* process_host, const GURL& site_url) override; bool ShouldUseProcessPerSite(content::BrowserContext* browser_context, const GURL& effective_url) override; void GetMediaDeviceIDSalt( content::RenderFrameHost* rfh, const net::SiteForCookies& site_for_cookies, const blink::StorageKey& storage_key, base::OnceCallback<void(bool, const std::string&)> callback) override; base::FilePath GetLoggingFileName(const base::CommandLine& cmd_line) override; // content::RenderProcessHostObserver: void RenderProcessHostDestroyed(content::RenderProcessHost* host) override; void RenderProcessReady(content::RenderProcessHost* host) override; void RenderProcessExited( content::RenderProcessHost* host, const content::ChildProcessTerminationInfo& info) override; private: content::SiteInstance* GetSiteInstanceFromAffinity( content::BrowserContext* browser_context, const GURL& url, content::RenderFrameHost* rfh) const; bool IsRendererSubFrame(int process_id) const; // pending_render_process => web contents. std::map<int, content::WebContents*> pending_processes_; std::set<int> renderer_is_subframe_; std::unique_ptr<PlatformNotificationService> notification_service_; std::unique_ptr<NotificationPresenter> notification_presenter_; raw_ptr<Delegate> delegate_ = nullptr; std::string user_agent_override_ = ""; // Simple shared ID generator, used by ProxyingURLLoaderFactory and // ProxyingWebSocket classes. uint64_t next_id_ = 0; std::unique_ptr<ElectronSerialDelegate> serial_delegate_; std::unique_ptr<ElectronBluetoothDelegate> bluetooth_delegate_; std::unique_ptr<ElectronUsbDelegate> usb_delegate_; std::unique_ptr<ElectronHidDelegate> hid_delegate_; std::unique_ptr<ElectronWebAuthenticationDelegate> web_authentication_delegate_; #if BUILDFLAG(IS_MAC) raw_ptr<ElectronBrowserMainParts> browser_main_parts_ = nullptr; #endif }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_ELECTRON_BROWSER_CLIENT_H_
closed
electron/electron
https://github.com/electron/electron
40,439
Convert legacy IPC calls in extensions code to use mojo
https://chromium-review.googlesource.com/c/chromium/src/+/4995136 turned on the build flag to use the new mojo IPC pipe for messaging in extensions. In #40418 we turned this off because we have not converted our extensions code to use mojo. It appears that in chromium the follow CLs were landed to use mojo in extensions: - 4947890: [extensions] Convert Extension Messaging APIs over to mojo | https://chromium-review.googlesource.com/c/chromium/src/+/4947890 - 4950041: [extensions] Port Event Acks to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4950041 - 4902564: [extensions] Move WakeEventPage to mojom::RendererHost | https://chromium-review.googlesource.com/c/chromium/src/+/4902564 - 4956841: [extensions] Port GetMessageBundle over to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4956841 Once these changes have landed, the following flag override in build/args/all.gn should be removed: `enable_extensions_legacy_ipc = true`
https://github.com/electron/electron/issues/40439
https://github.com/electron/electron/pull/40511
088affd4a4311e03b8ed400cdf5d82f1db2125a4
371bca69b69351dc47d4b4dcfdf9a626f43b3b51
2023-11-02T18:50:40Z
c++
2023-11-15T14:30:47Z
shell/browser/electron_browser_context.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_context.h" #include <memory> #include <utility> #include "base/barrier_closure.h" #include "base/base_paths.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/strings/escape.h" #include "base/strings/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/prefs/json_pref_store.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/pref_service_factory.h" #include "components/prefs/value_map_pref_store.h" #include "components/proxy_config/pref_proxy_config_tracker_impl.h" #include "components/proxy_config/proxy_config_pref_names.h" #include "content/browser/blob_storage/chrome_blob_storage_context.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/cors_origin_pattern_setter.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents_media_capture_id.h" #include "media/audio/audio_device_description.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/network_context.mojom.h" #include "shell/browser/cookie_change_notifier.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_download_manager_delegate.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/net/resolve_proxy_helper.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/special_storage_policy.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/zoom_level_delegate.h" #include "shell/common/application_info.h" #include "shell/common/electron_constants.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/options_switches.h" #include "shell/common/thread_restrictions.h" #include "third_party/blink/public/mojom/media/capture_handle_config.mojom.h" #include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/browser/extension_pref_store.h" #include "extensions/browser/extension_pref_value_map_factory.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/pref_names.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/browser/extensions/electron_extension_system_factory.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "components/pref_registry/pref_registry_syncable.h" #include "components/user_prefs/user_prefs.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "base/i18n/rtl.h" #include "components/language/core/browser/language_prefs.h" #include "components/spellcheck/browser/pref_names.h" #include "components/spellcheck/common/spellcheck_common.h" #endif using content::BrowserThread; namespace electron { namespace { // Copied from chrome/browser/media/webrtc/desktop_capture_devices_util.cc. media::mojom::CaptureHandlePtr CreateCaptureHandle( content::WebContents* capturer, const url::Origin& capturer_origin, const content::DesktopMediaID& captured_id) { if (capturer_origin.opaque()) { return nullptr; } content::RenderFrameHost* const captured_rfh = content::RenderFrameHost::FromID( captured_id.web_contents_id.render_process_id, captured_id.web_contents_id.main_render_frame_id); if (!captured_rfh || !captured_rfh->IsActive()) { return nullptr; } content::WebContents* const captured = content::WebContents::FromRenderFrameHost(captured_rfh); if (!captured) { return nullptr; } const auto& captured_config = captured->GetCaptureHandleConfig(); if (!captured_config.all_origins_permitted && base::ranges::none_of( captured_config.permitted_origins, [capturer_origin](const url::Origin& permitted_origin) { return capturer_origin.IsSameOriginWith(permitted_origin); })) { return nullptr; } // Observing CaptureHandle when either the capturing or the captured party // is incognito is disallowed, except for self-capture. if (capturer->GetPrimaryMainFrame() != captured->GetPrimaryMainFrame()) { if (capturer->GetBrowserContext()->IsOffTheRecord() || captured->GetBrowserContext()->IsOffTheRecord()) { return nullptr; } } if (!captured_config.expose_origin && captured_config.capture_handle.empty()) { return nullptr; } auto result = media::mojom::CaptureHandle::New(); if (captured_config.expose_origin) { result->origin = captured->GetPrimaryMainFrame()->GetLastCommittedOrigin(); } result->capture_handle = captured_config.capture_handle; return result; } // Copied from chrome/browser/media/webrtc/desktop_capture_devices_util.cc. media::mojom::DisplayMediaInformationPtr DesktopMediaIDToDisplayMediaInformation( content::WebContents* capturer, const url::Origin& capturer_origin, const content::DesktopMediaID& media_id) { media::mojom::DisplayCaptureSurfaceType display_surface = media::mojom::DisplayCaptureSurfaceType::MONITOR; bool logical_surface = true; media::mojom::CursorCaptureType cursor = media::mojom::CursorCaptureType::NEVER; #if defined(USE_AURA) const bool uses_aura = media_id.window_id != content::DesktopMediaID::kNullId ? true : false; #else const bool uses_aura = false; #endif // defined(USE_AURA) media::mojom::CaptureHandlePtr capture_handle; switch (media_id.type) { case content::DesktopMediaID::TYPE_SCREEN: display_surface = media::mojom::DisplayCaptureSurfaceType::MONITOR; cursor = uses_aura ? media::mojom::CursorCaptureType::MOTION : media::mojom::CursorCaptureType::ALWAYS; break; case content::DesktopMediaID::TYPE_WINDOW: display_surface = media::mojom::DisplayCaptureSurfaceType::WINDOW; cursor = uses_aura ? media::mojom::CursorCaptureType::MOTION : media::mojom::CursorCaptureType::ALWAYS; break; case content::DesktopMediaID::TYPE_WEB_CONTENTS: display_surface = media::mojom::DisplayCaptureSurfaceType::BROWSER; cursor = media::mojom::CursorCaptureType::MOTION; capture_handle = CreateCaptureHandle(capturer, capturer_origin, media_id); break; case content::DesktopMediaID::TYPE_NONE: break; } return media::mojom::DisplayMediaInformation::New( display_surface, logical_surface, cursor, std::move(capture_handle)); } // Convert string to lower case and escape it. std::string MakePartitionName(const std::string& input) { return base::EscapePath(base::ToLowerASCII(input)); } } // namespace // static ElectronBrowserContext::BrowserContextMap& ElectronBrowserContext::browser_context_map() { static base::NoDestructor<ElectronBrowserContext::BrowserContextMap> browser_context_map; return *browser_context_map; } ElectronBrowserContext::ElectronBrowserContext( const PartitionOrPath partition_location, bool in_memory, base::Value::Dict options) : in_memory_pref_store_(new ValueMapPrefStore), storage_policy_(base::MakeRefCounted<SpecialStoragePolicy>()), protocol_registry_(base::WrapUnique(new ProtocolRegistry)), in_memory_(in_memory), ssl_config_(network::mojom::SSLConfig::New()) { // Read options. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); use_cache_ = !command_line->HasSwitch(switches::kDisableHttpCache); if (auto use_cache_opt = options.FindBool("cache")) { use_cache_ = use_cache_opt.value(); } base::StringToInt(command_line->GetSwitchValueASCII(switches::kDiskCacheSize), &max_cache_size_); if (auto* path_value = std::get_if<std::reference_wrapper<const std::string>>( &partition_location)) { base::PathService::Get(DIR_SESSION_DATA, &path_); const std::string& partition_loc = path_value->get(); if (!in_memory && !partition_loc.empty()) { path_ = path_.Append(FILE_PATH_LITERAL("Partitions")) .Append(base::FilePath::FromUTF8Unsafe( MakePartitionName(partition_loc))); } } else if (auto* filepath_partition = std::get_if<std::reference_wrapper<const base::FilePath>>( &partition_location)) { const base::FilePath& partition_path = filepath_partition->get(); path_ = std::move(partition_path); } BrowserContextDependencyManager::GetInstance()->MarkBrowserContextLive(this); // Initialize Pref Registry. InitPrefs(); cookie_change_notifier_ = std::make_unique<CookieChangeNotifier>(this); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServices(this); extension_system_ = static_cast<extensions::ElectronExtensionSystem*>( extensions::ExtensionSystem::Get(this)); extension_system_->InitForRegularProfile(true /* extensions_enabled */); extension_system_->FinishInitialization(); } #endif } ElectronBrowserContext::~ElectronBrowserContext() { DCHECK_CURRENTLY_ON(BrowserThread::UI); NotifyWillBeDestroyed(); // Notify any keyed services of browser context destruction. BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices( this); ShutdownStoragePartitions(); BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, std::move(resource_context_)); } void ElectronBrowserContext::InitPrefs() { auto prefs_path = GetPath().Append(FILE_PATH_LITERAL("Preferences")); ScopedAllowBlockingForElectron allow_blocking; PrefServiceFactory prefs_factory; scoped_refptr<JsonPrefStore> pref_store = base::MakeRefCounted<JsonPrefStore>(prefs_path); pref_store->ReadPrefs(); // Synchronous. prefs_factory.set_user_prefs(pref_store); prefs_factory.set_command_line_prefs(in_memory_pref_store()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { auto* ext_pref_store = new ExtensionPrefStore( ExtensionPrefValueMapFactory::GetForBrowserContext(this), IsOffTheRecord()); prefs_factory.set_extension_prefs(ext_pref_store); } #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) auto registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>(); #else auto registry = base::MakeRefCounted<PrefRegistrySimple>(); #endif registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory, base::FilePath()); base::FilePath download_dir; base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_dir); registry->RegisterFilePathPref(prefs::kDownloadDefaultDirectory, download_dir); registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths); InspectableWebContents::RegisterPrefs(registry.get()); MediaDeviceIDSalt::RegisterPrefs(registry.get()); ZoomLevelDelegate::RegisterPrefs(registry.get()); PrefProxyConfigTrackerImpl::RegisterPrefs(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) extensions::ExtensionPrefs::RegisterProfilePrefs(registry.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) BrowserContextDependencyManager::GetInstance() ->RegisterProfilePrefsForServices(registry.get()); language::LanguagePrefs::RegisterProfilePrefs(registry.get()); #endif prefs_ = prefs_factory.Create(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) user_prefs::UserPrefs::Set(this, prefs_.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) // No configured dictionaries, the default will be en-US if (prefs()->GetList(spellcheck::prefs::kSpellCheckDictionaries).empty()) { std::string default_code = spellcheck::GetCorrespondingSpellCheckLanguage( base::i18n::GetConfiguredLocale()); if (!default_code.empty()) { base::Value::List language_codes; language_codes.Append(default_code); prefs()->Set(spellcheck::prefs::kSpellCheckDictionaries, base::Value(std::move(language_codes))); } } #endif } void ElectronBrowserContext::SetUserAgent(const std::string& user_agent) { user_agent_ = user_agent; } base::FilePath ElectronBrowserContext::GetPath() { return path_; } bool ElectronBrowserContext::IsOffTheRecord() { return in_memory_; } bool ElectronBrowserContext::CanUseHttpCache() const { return use_cache_; } int ElectronBrowserContext::GetMaxCacheSize() const { return max_cache_size_; } content::ResourceContext* ElectronBrowserContext::GetResourceContext() { if (!resource_context_) resource_context_ = std::make_unique<content::ResourceContext>(); return resource_context_.get(); } std::string ElectronBrowserContext::GetMediaDeviceIDSalt() { if (!media_device_id_salt_.get()) media_device_id_salt_ = std::make_unique<MediaDeviceIDSalt>(prefs_.get()); return media_device_id_salt_->GetSalt(); } std::unique_ptr<content::ZoomLevelDelegate> ElectronBrowserContext::CreateZoomLevelDelegate( const base::FilePath& partition_path) { if (!IsOffTheRecord()) { return std::make_unique<ZoomLevelDelegate>(prefs(), partition_path); } return std::unique_ptr<content::ZoomLevelDelegate>(); } content::DownloadManagerDelegate* ElectronBrowserContext::GetDownloadManagerDelegate() { if (!download_manager_delegate_.get()) { auto* download_manager = this->GetDownloadManager(); download_manager_delegate_ = std::make_unique<ElectronDownloadManagerDelegate>(download_manager); } return download_manager_delegate_.get(); } content::BrowserPluginGuestManager* ElectronBrowserContext::GetGuestManager() { if (!guest_manager_) guest_manager_ = std::make_unique<WebViewManager>(); return guest_manager_.get(); } content::PlatformNotificationService* ElectronBrowserContext::GetPlatformNotificationService() { return ElectronBrowserClient::Get()->GetPlatformNotificationService(); } content::PermissionControllerDelegate* ElectronBrowserContext::GetPermissionControllerDelegate() { if (!permission_manager_.get()) permission_manager_ = std::make_unique<ElectronPermissionManager>(); return permission_manager_.get(); } storage::SpecialStoragePolicy* ElectronBrowserContext::GetSpecialStoragePolicy() { return storage_policy_.get(); } std::string ElectronBrowserContext::GetUserAgent() const { return user_agent_.value_or(ElectronBrowserClient::Get()->GetUserAgent()); } predictors::PreconnectManager* ElectronBrowserContext::GetPreconnectManager() { if (!preconnect_manager_.get()) { preconnect_manager_ = std::make_unique<predictors::PreconnectManager>(nullptr, this); } return preconnect_manager_.get(); } scoped_refptr<network::SharedURLLoaderFactory> ElectronBrowserContext::GetURLLoaderFactory() { if (url_loader_factory_) return url_loader_factory_; mojo::PendingRemote<network::mojom::URLLoaderFactory> network_factory_remote; mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver = network_factory_remote.InitWithNewPipeAndPassReceiver(); // Consult the embedder. mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient> header_client; static_cast<content::ContentBrowserClient*>(ElectronBrowserClient::Get()) ->WillCreateURLLoaderFactory( this, nullptr, -1, content::ContentBrowserClient::URLLoaderFactoryType::kNavigation, url::Origin(), absl::nullopt, ukm::kInvalidSourceIdObj, &factory_receiver, &header_client, nullptr, nullptr, nullptr, nullptr); network::mojom::URLLoaderFactoryParamsPtr params = network::mojom::URLLoaderFactoryParams::New(); params->header_client = std::move(header_client); params->process_id = network::mojom::kBrowserProcessId; params->is_trusted = true; params->is_corb_enabled = false; // The tests of net module would fail if this setting is true, it seems that // the non-NetworkService implementation always has web security enabled. params->disable_web_security = false; auto* storage_partition = GetDefaultStoragePartition(); storage_partition->GetNetworkContext()->CreateURLLoaderFactory( std::move(factory_receiver), std::move(params)); url_loader_factory_ = base::MakeRefCounted<network::WrapperSharedURLLoaderFactory>( std::move(network_factory_remote)); return url_loader_factory_; } content::PushMessagingService* ElectronBrowserContext::GetPushMessagingService() { return nullptr; } content::SSLHostStateDelegate* ElectronBrowserContext::GetSSLHostStateDelegate() { return nullptr; } content::BackgroundFetchDelegate* ElectronBrowserContext::GetBackgroundFetchDelegate() { return nullptr; } content::BackgroundSyncController* ElectronBrowserContext::GetBackgroundSyncController() { return nullptr; } content::BrowsingDataRemoverDelegate* ElectronBrowserContext::GetBrowsingDataRemoverDelegate() { return nullptr; } content::ClientHintsControllerDelegate* ElectronBrowserContext::GetClientHintsControllerDelegate() { return nullptr; } content::StorageNotificationService* ElectronBrowserContext::GetStorageNotificationService() { return nullptr; } content::ReduceAcceptLanguageControllerDelegate* ElectronBrowserContext::GetReduceAcceptLanguageControllerDelegate() { // Needs implementation // Refs https://chromium-review.googlesource.com/c/chromium/src/+/3687391 return nullptr; } ResolveProxyHelper* ElectronBrowserContext::GetResolveProxyHelper() { if (!resolve_proxy_helper_) { resolve_proxy_helper_ = base::MakeRefCounted<ResolveProxyHelper>(this); } return resolve_proxy_helper_.get(); } network::mojom::SSLConfigPtr ElectronBrowserContext::GetSSLConfig() { return ssl_config_.Clone(); } void ElectronBrowserContext::SetSSLConfig(network::mojom::SSLConfigPtr config) { ssl_config_ = std::move(config); if (ssl_config_client_) { ssl_config_client_->OnSSLConfigUpdated(ssl_config_.Clone()); } } void ElectronBrowserContext::SetSSLConfigClient( mojo::Remote<network::mojom::SSLConfigClient> client) { ssl_config_client_ = std::move(client); } void ElectronBrowserContext::SetDisplayMediaRequestHandler( DisplayMediaRequestHandler handler) { display_media_request_handler_ = handler; } void ElectronBrowserContext::DisplayMediaDeviceChosen( const content::MediaStreamRequest& request, content::MediaResponseCallback callback, gin::Arguments* args) { blink::mojom::StreamDevicesSetPtr stream_devices_set = blink::mojom::StreamDevicesSet::New(); v8::Local<v8::Value> result; if (!args->GetNext(&result) || result->IsNullOrUndefined()) { std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } gin_helper::Dictionary result_dict; if (!gin::ConvertFromV8(args->isolate(), result, &result_dict)) { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "Display Media Request streams callback must be called with null " "or a valid object"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } stream_devices_set->stream_devices.emplace_back( blink::mojom::StreamDevices::New()); blink::mojom::StreamDevices& devices = *stream_devices_set->stream_devices[0]; bool video_requested = request.video_type != blink::mojom::MediaStreamType::NO_SERVICE; bool audio_requested = request.audio_type != blink::mojom::MediaStreamType::NO_SERVICE; bool has_video = false; if (video_requested && result_dict.Has("video")) { gin_helper::Dictionary video_dict; std::string id; std::string name; content::RenderFrameHost* rfh; if (result_dict.Get("video", &video_dict) && video_dict.Get("id", &id) && video_dict.Get("name", &name)) { blink::MediaStreamDevice video_device(request.video_type, id, name); video_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( nullptr, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(video_device.id)); devices.video_device = video_device; } else if (result_dict.Get("video", &rfh)) { auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); blink::MediaStreamDevice video_device( request.video_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID()) .ToString(), base::UTF16ToUTF8(web_contents->GetTitle())); video_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( web_contents, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(video_device.id)); devices.video_device = video_device; } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "video must be a WebFrameMain or DesktopCapturerSource"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } has_video = true; } if (audio_requested && result_dict.Has("audio")) { gin_helper::Dictionary audio_dict; std::string id; std::string name; content::RenderFrameHost* rfh; // NB. this is not permitted by the documentation, but is left here as an // "escape hatch" for providing an arbitrary name/id if needed in the // future. if (result_dict.Get("audio", &audio_dict) && audio_dict.Get("id", &id) && audio_dict.Get("name", &name)) { blink::MediaStreamDevice audio_device(request.audio_type, id, name); audio_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( nullptr, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(request.requested_audio_device_id)); devices.audio_device = audio_device; } else if (result_dict.Get("audio", &rfh)) { bool enable_local_echo = false; result_dict.Get("enableLocalEcho", &enable_local_echo); bool disable_local_echo = !enable_local_echo; auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); blink::MediaStreamDevice audio_device( request.audio_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID(), disable_local_echo) .ToString(), "Tab audio"); audio_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( web_contents, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(request.requested_audio_device_id)); devices.audio_device = audio_device; } else if (result_dict.Get("audio", &id)) { blink::MediaStreamDevice audio_device(request.audio_type, id, "System audio"); audio_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( nullptr, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(request.requested_audio_device_id)); devices.audio_device = audio_device; } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "audio must be a WebFrameMain, \"loopback\" or " "\"loopbackWithMute\""); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } } if ((video_requested && !has_video)) { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "Video was requested, but no video stream was provided"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } std::move(callback).Run(*stream_devices_set, blink::mojom::MediaStreamRequestResult::OK, nullptr); } bool ElectronBrowserContext::ChooseDisplayMediaDevice( const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { if (!display_media_request_handler_) return false; DisplayMediaResponseCallbackJs callbackJs = base::BindOnce(&DisplayMediaDeviceChosen, request, std::move(callback)); display_media_request_handler_.Run(request, std::move(callbackJs)); return true; } void ElectronBrowserContext::GrantDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { granted_devices_[permission_type][origin].push_back( std::make_unique<base::Value>(device.Clone())); } void ElectronBrowserContext::RevokeDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return; for (auto it = origin_devices_it->second.begin(); it != origin_devices_it->second.end();) { if (DoesDeviceMatch(device, it->get(), permission_type)) { it = origin_devices_it->second.erase(it); } else { ++it; } } } bool ElectronBrowserContext::DoesDeviceMatch( const base::Value& device, const base::Value* device_to_compare, blink::PermissionType permission_type) { if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::HID) || permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::USB)) { if (device.GetDict().FindInt(kDeviceVendorIdKey) != device_to_compare->GetDict().FindInt(kDeviceVendorIdKey) || device.GetDict().FindInt(kDeviceProductIdKey) != device_to_compare->GetDict().FindInt(kDeviceProductIdKey)) { return false; } const auto* serial_number = device_to_compare->GetDict().FindString(kDeviceSerialNumberKey); const auto* device_serial_number = device.GetDict().FindString(kDeviceSerialNumberKey); if (serial_number && device_serial_number && *device_serial_number == *serial_number) return true; } else if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL)) { #if BUILDFLAG(IS_WIN) const auto* instance_id = device.GetDict().FindString(kDeviceInstanceIdKey); const auto* port_instance_id = device_to_compare->GetDict().FindString(kDeviceInstanceIdKey); if (instance_id && port_instance_id && *instance_id == *port_instance_id) return true; #else const auto* serial_number = device.GetDict().FindString(kSerialNumberKey); const auto* port_serial_number = device_to_compare->GetDict().FindString(kSerialNumberKey); if (device.GetDict().FindInt(kVendorIdKey) != device_to_compare->GetDict().FindInt(kVendorIdKey) || device.GetDict().FindInt(kProductIdKey) != device_to_compare->GetDict().FindInt(kProductIdKey) || (serial_number && port_serial_number && *port_serial_number != *serial_number)) { return false; } #if BUILDFLAG(IS_MAC) const auto* usb_driver_key = device.GetDict().FindString(kUsbDriverKey); const auto* port_usb_driver_key = device_to_compare->GetDict().FindString(kUsbDriverKey); if (usb_driver_key && port_usb_driver_key && *usb_driver_key != *port_usb_driver_key) { return false; } #endif // BUILDFLAG(IS_MAC) return true; #endif // BUILDFLAG(IS_WIN) } return false; } bool ElectronBrowserContext::CheckDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return false; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return false; for (const auto& device_to_compare : origin_devices_it->second) { if (DoesDeviceMatch(device, device_to_compare.get(), permission_type)) return true; } return false; } // static ElectronBrowserContext* ElectronBrowserContext::From( const std::string& partition, bool in_memory, base::Value::Dict options) { PartitionKey key(partition, in_memory); ElectronBrowserContext* browser_context = browser_context_map()[key].get(); if (browser_context) { return browser_context; } auto* new_context = new ElectronBrowserContext(std::cref(partition), in_memory, std::move(options)); browser_context_map()[key] = std::unique_ptr<ElectronBrowserContext>(new_context); return new_context; } ElectronBrowserContext* ElectronBrowserContext::FromPath( const base::FilePath& path, base::Value::Dict options) { PartitionKey key(path); ElectronBrowserContext* browser_context = browser_context_map()[key].get(); if (browser_context) { return browser_context; } auto* new_context = new ElectronBrowserContext(std::cref(path), false, std::move(options)); browser_context_map()[key] = std::unique_ptr<ElectronBrowserContext>(new_context); return new_context; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,439
Convert legacy IPC calls in extensions code to use mojo
https://chromium-review.googlesource.com/c/chromium/src/+/4995136 turned on the build flag to use the new mojo IPC pipe for messaging in extensions. In #40418 we turned this off because we have not converted our extensions code to use mojo. It appears that in chromium the follow CLs were landed to use mojo in extensions: - 4947890: [extensions] Convert Extension Messaging APIs over to mojo | https://chromium-review.googlesource.com/c/chromium/src/+/4947890 - 4950041: [extensions] Port Event Acks to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4950041 - 4902564: [extensions] Move WakeEventPage to mojom::RendererHost | https://chromium-review.googlesource.com/c/chromium/src/+/4902564 - 4956841: [extensions] Port GetMessageBundle over to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4956841 Once these changes have landed, the following flag override in build/args/all.gn should be removed: `enable_extensions_legacy_ipc = true`
https://github.com/electron/electron/issues/40439
https://github.com/electron/electron/pull/40511
088affd4a4311e03b8ed400cdf5d82f1db2125a4
371bca69b69351dc47d4b4dcfdf9a626f43b3b51
2023-11-02T18:50:40Z
c++
2023-11-15T14:30:47Z
shell/browser/extensions/electron_extension_message_filter.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/extensions/electron_extension_message_filter.h" #include <stdint.h> #include <memory> #include "base/files/file_path.h" #include "base/functional/bind.h" #include "base/functional/callback_helpers.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "base/task/thread_pool.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/render_process_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/l10n_file_util.h" #include "extensions/common/extension_messages.h" #include "extensions/common/extension_set.h" #include "extensions/common/manifest_handlers/default_locale_handler.h" #include "extensions/common/manifest_handlers/shared_module_info.h" #include "extensions/common/message_bundle.h" using content::BrowserThread; namespace electron { const uint32_t kExtensionFilteredMessageClasses[] = { ExtensionMsgStart, }; ElectronExtensionMessageFilter::ElectronExtensionMessageFilter( int render_process_id, content::BrowserContext* browser_context) : BrowserMessageFilter(kExtensionFilteredMessageClasses, std::size(kExtensionFilteredMessageClasses)), render_process_id_(render_process_id), browser_context_(browser_context) { DCHECK_CURRENTLY_ON(BrowserThread::UI); } ElectronExtensionMessageFilter::~ElectronExtensionMessageFilter() { DCHECK_CURRENTLY_ON(BrowserThread::UI); } bool ElectronExtensionMessageFilter::OnMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(ElectronExtensionMessageFilter, message) IPC_MESSAGE_HANDLER_DELAY_REPLY(ExtensionHostMsg_GetMessageBundle, OnGetExtMessageBundle) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void ElectronExtensionMessageFilter::OverrideThreadForMessage( const IPC::Message& message, BrowserThread::ID* thread) { switch (message.type()) { case ExtensionHostMsg_GetMessageBundle::ID: *thread = BrowserThread::UI; break; default: break; } } void ElectronExtensionMessageFilter::OnDestruct() const { if (BrowserThread::CurrentlyOn(BrowserThread::UI)) { delete this; } else { content::GetUIThreadTaskRunner({})->DeleteSoon(FROM_HERE, this); } } void ElectronExtensionMessageFilter::OnGetExtMessageBundle( const std::string& extension_id, IPC::Message* reply_msg) { DCHECK_CURRENTLY_ON(BrowserThread::UI); const extensions::ExtensionSet& extension_set = extensions::ExtensionRegistry::Get(browser_context_) ->enabled_extensions(); const extensions::Extension* extension = extension_set.GetByID(extension_id); if (!extension) { // The extension has gone. ExtensionHostMsg_GetMessageBundle::WriteReplyParams( reply_msg, extensions::MessageBundle::SubstitutionMap()); Send(reply_msg); return; } const std::string& default_locale = extensions::LocaleInfo::GetDefaultLocale(extension); if (default_locale.empty()) { // A little optimization: send the answer here to avoid an extra thread hop. std::unique_ptr<extensions::MessageBundle::SubstitutionMap> dictionary_map( extensions::l10n_file_util:: LoadNonLocalizedMessageBundleSubstitutionMap(extension_id)); ExtensionHostMsg_GetMessageBundle::WriteReplyParams(reply_msg, *dictionary_map); Send(reply_msg); return; } std::vector<base::FilePath> paths_to_load; paths_to_load.push_back(extension->path()); auto imports = extensions::SharedModuleInfo::GetImports(extension); // Iterate through the imports in reverse. This will allow later imported // modules to override earlier imported modules, as the list order is // maintained from the definition in manifest.json of the imports. for (auto it = imports.rbegin(); it != imports.rend(); ++it) { const extensions::Extension* imported_extension = extension_set.GetByID(it->extension_id); if (!imported_extension) { NOTREACHED() << "Missing shared module " << it->extension_id; continue; } paths_to_load.push_back(imported_extension->path()); } // This blocks tab loading. Priority is inherited from the calling context. base::ThreadPool::PostTask( FROM_HERE, {base::MayBlock()}, base::BindOnce( &ElectronExtensionMessageFilter::OnGetExtMessageBundleAsync, this, paths_to_load, extension_id, default_locale, extension_l10n_util::GetGzippedMessagesPermissionForExtension( extension), reply_msg)); } void ElectronExtensionMessageFilter::OnGetExtMessageBundleAsync( const std::vector<base::FilePath>& extension_paths, const std::string& main_extension_id, const std::string& default_locale, extension_l10n_util::GzippedMessagesPermission gzip_permission, IPC::Message* reply_msg) { std::unique_ptr<extensions::MessageBundle::SubstitutionMap> dictionary_map( extensions::l10n_file_util::LoadMessageBundleSubstitutionMapFromPaths( extension_paths, main_extension_id, default_locale, gzip_permission)); ExtensionHostMsg_GetMessageBundle::WriteReplyParams(reply_msg, *dictionary_map); Send(reply_msg); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,439
Convert legacy IPC calls in extensions code to use mojo
https://chromium-review.googlesource.com/c/chromium/src/+/4995136 turned on the build flag to use the new mojo IPC pipe for messaging in extensions. In #40418 we turned this off because we have not converted our extensions code to use mojo. It appears that in chromium the follow CLs were landed to use mojo in extensions: - 4947890: [extensions] Convert Extension Messaging APIs over to mojo | https://chromium-review.googlesource.com/c/chromium/src/+/4947890 - 4950041: [extensions] Port Event Acks to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4950041 - 4902564: [extensions] Move WakeEventPage to mojom::RendererHost | https://chromium-review.googlesource.com/c/chromium/src/+/4902564 - 4956841: [extensions] Port GetMessageBundle over to mojom | https://chromium-review.googlesource.com/c/chromium/src/+/4956841 Once these changes have landed, the following flag override in build/args/all.gn should be removed: `enable_extensions_legacy_ipc = true`
https://github.com/electron/electron/issues/40439
https://github.com/electron/electron/pull/40511
088affd4a4311e03b8ed400cdf5d82f1db2125a4
371bca69b69351dc47d4b4dcfdf9a626f43b3b51
2023-11-02T18:50:40Z
c++
2023-11-15T14:30:47Z
shell/browser/extensions/electron_extension_message_filter.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_EXTENSIONS_ELECTRON_EXTENSION_MESSAGE_FILTER_H_ #define ELECTRON_SHELL_BROWSER_EXTENSIONS_ELECTRON_EXTENSION_MESSAGE_FILTER_H_ #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "base/task/sequenced_task_runner_helpers.h" #include "content/public/browser/browser_message_filter.h" #include "content/public/browser/browser_thread.h" #include "extensions/common/extension_l10n_util.h" namespace content { class BrowserContext; } namespace extensions { struct Message; } namespace electron { // This class filters out incoming Electron-specific IPC messages from the // extension process on the IPC thread. class ElectronExtensionMessageFilter : public content::BrowserMessageFilter { public: ElectronExtensionMessageFilter(int render_process_id, content::BrowserContext* browser_context); // disable copy ElectronExtensionMessageFilter(const ElectronExtensionMessageFilter&) = delete; ElectronExtensionMessageFilter& operator=( const ElectronExtensionMessageFilter&) = delete; // content::BrowserMessageFilter methods: bool OnMessageReceived(const IPC::Message& message) override; void OverrideThreadForMessage(const IPC::Message& message, content::BrowserThread::ID* thread) override; void OnDestruct() const override; private: friend class content::BrowserThread; friend class base::DeleteHelper<ElectronExtensionMessageFilter>; ~ElectronExtensionMessageFilter() override; void OnGetExtMessageBundle(const std::string& extension_id, IPC::Message* reply_msg); void OnGetExtMessageBundleAsync( const std::vector<base::FilePath>& extension_paths, const std::string& main_extension_id, const std::string& default_locale, extension_l10n_util::GzippedMessagesPermission gzip_permission, IPC::Message* reply_msg); const int render_process_id_; // The BrowserContext associated with our renderer process. This should only // be accessed on the UI thread! Furthermore since this class is refcounted it // may outlive |browser_context_|, so make sure to nullptr check if in doubt; // async calls and the like. raw_ptr<content::BrowserContext> browser_context_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_EXTENSIONS_ELECTRON_EXTENSION_MESSAGE_FILTER_H_
closed
electron/electron
https://github.com/electron/electron
40,660
[Bug]: Can not open devtools after closing
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 28.0.0-beta.10 ### What operating system are you using? Windows ### Operating System Version 10.0.19042 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Devtools should open ### Actual Behavior After opening devtools and closing them, it is not possible to reopen the devtools ### Testcase Gist URL https://gist.github.com/t57ser/9ca91183cb53fd45eb6c73c42f92903e ### Additional Information _No response_
https://github.com/electron/electron/issues/40660
https://github.com/electron/electron/pull/40666
344b7f0d068ae7d20fdebafc2ebadcdc0b4f7f68
3609fc7402881b1d51f6c56249506d5dd3fcbe93
2023-11-30T12:43:35Z
c++
2023-12-01T19:37:52Z
shell/browser/ui/inspectable_web_contents.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "shell/browser/ui/inspectable_web_contents.h" #include <memory> #include <utility> #include "base/base64.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/json/string_escape.h" #include "base/memory/raw_ptr.h" #include "base/metrics/histogram.h" #include "base/stl_util.h" #include "base/strings/pattern.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/uuid.h" #include "base/values.h" #include "chrome/browser/devtools/devtools_contents_resizing_strategy.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/file_url_loader.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/user_agent.h" #include "ipc/ipc_channel.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" #include "services/network/public/cpp/simple_url_loader.h" #include "services/network/public/cpp/simple_url_loader_stream_consumer.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_window_views.h" #include "shell/browser/net/asar/asar_url_loader_factory.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/ui/inspectable_web_contents_delegate.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/inspectable_web_contents_view_delegate.h" #include "shell/common/application_info.h" #include "shell/common/platform_util.h" #include "third_party/blink/public/common/logging/logging_utils.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "v8/include/v8.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "chrome/common/extensions/chrome_manifest_url_handlers.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/render_process_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/permissions/permissions_data.h" #include "shell/browser/electron_browser_context.h" #endif namespace electron { namespace { const double kPresetZoomFactors[] = {0.25, 0.333, 0.5, 0.666, 0.75, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0}; const char kChromeUIDevToolsURL[] = "devtools://devtools/bundled/devtools_app.html?" "remoteBase=%s&" "can_dock=%s&" "toolbarColor=rgba(223,223,223,1)&" "textColor=rgba(0,0,0,1)&" "experiments=true"; const char kChromeUIDevToolsRemoteFrontendBase[] = "https://chrome-devtools-frontend.appspot.com/"; const char kChromeUIDevToolsRemoteFrontendPath[] = "serve_file"; const char kDevToolsBoundsPref[] = "electron.devtools.bounds"; const char kDevToolsZoomPref[] = "electron.devtools.zoom"; const char kDevToolsPreferences[] = "electron.devtools.preferences"; const char kFrontendHostId[] = "id"; const char kFrontendHostMethod[] = "method"; const char kFrontendHostParams[] = "params"; const char kTitleFormat[] = "Developer Tools - %s"; const size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4; base::Value::Dict RectToDictionary(const gfx::Rect& bounds) { return base::Value::Dict{} .Set("x", bounds.x()) .Set("y", bounds.y()) .Set("width", bounds.width()) .Set("height", bounds.height()); } gfx::Rect DictionaryToRect(const base::Value::Dict& dict) { const base::Value* found = dict.Find("x"); int x = found ? found->GetInt() : 0; found = dict.Find("y"); int y = found ? found->GetInt() : 0; found = dict.Find("width"); int width = found ? found->GetInt() : 800; found = dict.Find("height"); int height = found ? found->GetInt() : 600; return gfx::Rect(x, y, width, height); } bool IsPointInRect(const gfx::Point& point, const gfx::Rect& rect) { return point.x() > rect.x() && point.x() < (rect.width() + rect.x()) && point.y() > rect.y() && point.y() < (rect.height() + rect.y()); } bool IsPointInScreen(const gfx::Point& point) { for (const auto& display : display::Screen::GetScreen()->GetAllDisplays()) { if (IsPointInRect(point, display.bounds())) return true; } return false; } void SetZoomLevelForWebContents(content::WebContents* web_contents, double level) { content::HostZoomMap::SetZoomLevel(web_contents, level); } double GetNextZoomLevel(double level, bool out) { double factor = blink::PageZoomLevelToZoomFactor(level); size_t size = std::size(kPresetZoomFactors); for (size_t i = 0; i < size; ++i) { if (!blink::PageZoomValuesEqual(kPresetZoomFactors[i], factor)) continue; if (out && i > 0) return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i - 1]); if (!out && i != size - 1) return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i + 1]); } return level; } GURL GetRemoteBaseURL() { return GURL(base::StringPrintf("%s%s/%s/", kChromeUIDevToolsRemoteFrontendBase, kChromeUIDevToolsRemoteFrontendPath, content::GetChromiumGitRevision().c_str())); } GURL GetDevToolsURL(bool can_dock) { auto url_string = base::StringPrintf(kChromeUIDevToolsURL, GetRemoteBaseURL().spec().c_str(), can_dock ? "true" : ""); return GURL(url_string); } void OnOpenItemComplete(const base::FilePath& path, const std::string& result) { platform_util::ShowItemInFolder(path); } constexpr base::TimeDelta kInitialBackoffDelay = base::Milliseconds(250); constexpr base::TimeDelta kMaxBackoffDelay = base::Seconds(10); } // namespace class InspectableWebContents::NetworkResourceLoader : public network::SimpleURLLoaderStreamConsumer { public: class URLLoaderFactoryHolder { public: network::mojom::URLLoaderFactory* get() { return ptr_.get() ? ptr_.get() : refptr_.get(); } void operator=(std::unique_ptr<network::mojom::URLLoaderFactory>&& ptr) { ptr_ = std::move(ptr); } void operator=(scoped_refptr<network::SharedURLLoaderFactory>&& refptr) { refptr_ = std::move(refptr); } private: std::unique_ptr<network::mojom::URLLoaderFactory> ptr_; scoped_refptr<network::SharedURLLoaderFactory> refptr_; }; static void Create(int stream_id, InspectableWebContents* bindings, const network::ResourceRequest& resource_request, const net::NetworkTrafficAnnotationTag& traffic_annotation, URLLoaderFactoryHolder url_loader_factory, DispatchCallback callback, base::TimeDelta retry_delay = base::TimeDelta()) { auto resource_loader = std::make_unique<InspectableWebContents::NetworkResourceLoader>( stream_id, bindings, resource_request, traffic_annotation, std::move(url_loader_factory), std::move(callback), retry_delay); bindings->loaders_.insert(std::move(resource_loader)); } NetworkResourceLoader( int stream_id, InspectableWebContents* bindings, const network::ResourceRequest& resource_request, const net::NetworkTrafficAnnotationTag& traffic_annotation, URLLoaderFactoryHolder url_loader_factory, DispatchCallback callback, base::TimeDelta delay) : stream_id_(stream_id), bindings_(bindings), resource_request_(resource_request), traffic_annotation_(traffic_annotation), loader_(network::SimpleURLLoader::Create( std::make_unique<network::ResourceRequest>(resource_request), traffic_annotation)), url_loader_factory_(std::move(url_loader_factory)), callback_(std::move(callback)), retry_delay_(delay) { loader_->SetOnResponseStartedCallback(base::BindOnce( &NetworkResourceLoader::OnResponseStarted, base::Unretained(this))); timer_.Start(FROM_HERE, delay, base::BindRepeating(&NetworkResourceLoader::DownloadAsStream, base::Unretained(this))); } NetworkResourceLoader(const NetworkResourceLoader&) = delete; NetworkResourceLoader& operator=(const NetworkResourceLoader&) = delete; private: void DownloadAsStream() { loader_->DownloadAsStream(url_loader_factory_.get(), this); } base::TimeDelta GetNextExponentialBackoffDelay(const base::TimeDelta& delta) { if (delta.is_zero()) { return kInitialBackoffDelay; } else { return delta * 1.3; } } void OnResponseStarted(const GURL& final_url, const network::mojom::URLResponseHead& response_head) { response_headers_ = response_head.headers; } void OnDataReceived(base::StringPiece chunk, base::OnceClosure resume) override { base::Value chunkValue; bool encoded = !base::IsStringUTF8(chunk); if (encoded) { std::string encoded_string; base::Base64Encode(chunk, &encoded_string); chunkValue = base::Value(std::move(encoded_string)); } else { chunkValue = base::Value(chunk); } base::Value id(stream_id_); base::Value encodedValue(encoded); bindings_->CallClientFunction("DevToolsAPI", "streamWrite", std::move(id), std::move(chunkValue), std::move(encodedValue)); std::move(resume).Run(); } void OnComplete(bool success) override { if (!success && loader_->NetError() == net::ERR_INSUFFICIENT_RESOURCES && retry_delay_ < kMaxBackoffDelay) { const base::TimeDelta delay = GetNextExponentialBackoffDelay(retry_delay_); LOG(WARNING) << "InspectableWebContents::NetworkResourceLoader id = " << stream_id_ << " failed with insufficient resources, retrying in " << delay << "." << std::endl; NetworkResourceLoader::Create( stream_id_, bindings_, resource_request_, traffic_annotation_, std::move(url_loader_factory_), std::move(callback_), delay); } else { base::Value response(base::Value::Type::DICT); response.GetDict().Set( "statusCode", response_headers_ ? response_headers_->response_code() : net::HTTP_OK); base::Value::Dict headers; size_t iterator = 0; std::string name; std::string value; while (response_headers_ && response_headers_->EnumerateHeaderLines(&iterator, &name, &value)) headers.Set(name, value); response.GetDict().Set("headers", std::move(headers)); std::move(callback_).Run(&response); } bindings_->loaders_.erase(bindings_->loaders_.find(this)); } void OnRetry(base::OnceClosure start_retry) override {} const int stream_id_; raw_ptr<InspectableWebContents> const bindings_; const network::ResourceRequest resource_request_; const net::NetworkTrafficAnnotationTag traffic_annotation_; std::unique_ptr<network::SimpleURLLoader> loader_; URLLoaderFactoryHolder url_loader_factory_; DispatchCallback callback_; scoped_refptr<net::HttpResponseHeaders> response_headers_; base::OneShotTimer timer_; base::TimeDelta retry_delay_; }; // Implemented separately on each platform. InspectableWebContentsView* CreateInspectableContentsView( InspectableWebContents* inspectable_web_contents); // static // static void InspectableWebContents::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterDictionaryPref(kDevToolsBoundsPref, RectToDictionary(gfx::Rect{0, 0, 800, 600})); registry->RegisterDoublePref(kDevToolsZoomPref, 0.); registry->RegisterDictionaryPref(kDevToolsPreferences); } InspectableWebContents::InspectableWebContents( std::unique_ptr<content::WebContents> web_contents, PrefService* pref_service, bool is_guest) : pref_service_(pref_service), web_contents_(std::move(web_contents)), is_guest_(is_guest), view_(CreateInspectableContentsView(this)) { const base::Value* bounds_dict = &pref_service_->GetValue(kDevToolsBoundsPref); if (bounds_dict->is_dict()) { devtools_bounds_ = DictionaryToRect(bounds_dict->GetDict()); // Sometimes the devtools window is out of screen or has too small size. if (devtools_bounds_.height() < 100 || devtools_bounds_.width() < 100) { devtools_bounds_.set_height(600); devtools_bounds_.set_width(800); } if (!IsPointInScreen(devtools_bounds_.origin())) { gfx::Rect display; if (!is_guest && web_contents_->GetNativeView()) { display = display::Screen::GetScreen() ->GetDisplayNearestView(web_contents_->GetNativeView()) .bounds(); } else { display = display::Screen::GetScreen()->GetPrimaryDisplay().bounds(); } devtools_bounds_.set_x(display.x() + (display.width() - devtools_bounds_.width()) / 2); devtools_bounds_.set_y( display.y() + (display.height() - devtools_bounds_.height()) / 2); } } } InspectableWebContents::~InspectableWebContents() { // Unsubscribe from devtools and Clean up resources. if (GetDevToolsWebContents()) WebContentsDestroyed(); // Let destructor destroy managed_devtools_web_contents_. } InspectableWebContentsView* InspectableWebContents::GetView() const { return view_.get(); } content::WebContents* InspectableWebContents::GetWebContents() const { return web_contents_.get(); } content::WebContents* InspectableWebContents::GetDevToolsWebContents() const { if (external_devtools_web_contents_) return external_devtools_web_contents_; else return managed_devtools_web_contents_.get(); } void InspectableWebContents::InspectElement(int x, int y) { if (agent_host_) agent_host_->InspectElement(web_contents_->GetPrimaryMainFrame(), x, y); } void InspectableWebContents::SetDelegate( InspectableWebContentsDelegate* delegate) { delegate_ = delegate; } InspectableWebContentsDelegate* InspectableWebContents::GetDelegate() const { return delegate_; } bool InspectableWebContents::IsGuest() const { return is_guest_; } void InspectableWebContents::ReleaseWebContents() { web_contents_.release(); WebContentsDestroyed(); view_.reset(); } void InspectableWebContents::SetDockState(const std::string& state) { if (state == "detach") { can_dock_ = false; } else { can_dock_ = true; dock_state_ = state; } } void InspectableWebContents::SetDevToolsTitle(const std::u16string& title) { devtools_title_ = title; view_->SetTitle(devtools_title_); } void InspectableWebContents::SetDevToolsWebContents( content::WebContents* devtools) { if (!managed_devtools_web_contents_) external_devtools_web_contents_ = devtools; } void InspectableWebContents::ShowDevTools(bool activate) { if (embedder_message_dispatcher_) { if (managed_devtools_web_contents_) view_->ShowDevTools(activate); return; } activate_ = activate; // Show devtools only after it has done loading, this is to make sure the // SetIsDocked is called *BEFORE* ShowDevTools. embedder_message_dispatcher_ = DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this); if (!external_devtools_web_contents_) { // no external devtools managed_devtools_web_contents_ = content::WebContents::Create( content::WebContents::CreateParams(web_contents_->GetBrowserContext())); managed_devtools_web_contents_->SetDelegate(this); v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); api::WebContents::FromOrCreate(isolate, managed_devtools_web_contents_.get()); } Observe(GetDevToolsWebContents()); AttachTo(content::DevToolsAgentHost::GetOrCreateFor(web_contents_.get())); GetDevToolsWebContents()->GetController().LoadURL( GetDevToolsURL(can_dock_), content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); } void InspectableWebContents::CloseDevTools() { if (GetDevToolsWebContents()) { frontend_loaded_ = false; if (managed_devtools_web_contents_) { view_->CloseDevTools(); managed_devtools_web_contents_.reset(); } embedder_message_dispatcher_.reset(); if (!IsGuest()) web_contents_->Focus(); } } bool InspectableWebContents::IsDevToolsViewShowing() { return managed_devtools_web_contents_ && view_->IsDevToolsViewShowing(); } std::u16string InspectableWebContents::GetDevToolsTitle() { return view_->GetTitle(); } void InspectableWebContents::AttachTo( scoped_refptr<content::DevToolsAgentHost> host) { Detach(); agent_host_ = std::move(host); // We could use ForceAttachClient here if problem arises with // devtools multiple session support. agent_host_->AttachClient(this); } void InspectableWebContents::Detach() { if (agent_host_) agent_host_->DetachClient(this); agent_host_ = nullptr; } void InspectableWebContents::Reattach(DispatchCallback callback) { if (agent_host_) { agent_host_->DetachClient(this); agent_host_->AttachClient(this); } std::move(callback).Run(nullptr); } void InspectableWebContents::CallClientFunction( const std::string& object_name, const std::string& method_name, base::Value arg1, base::Value arg2, base::Value arg3, base::OnceCallback<void(base::Value)> cb) { if (!GetDevToolsWebContents()) return; base::Value::List arguments; if (!arg1.is_none()) { arguments.Append(std::move(arg1)); if (!arg2.is_none()) { arguments.Append(std::move(arg2)); if (!arg3.is_none()) { arguments.Append(std::move(arg3)); } } } GetDevToolsWebContents()->GetPrimaryMainFrame()->ExecuteJavaScriptMethod( base::ASCIIToUTF16(object_name), base::ASCIIToUTF16(method_name), std::move(arguments), std::move(cb)); } gfx::Rect InspectableWebContents::GetDevToolsBounds() const { return devtools_bounds_; } void InspectableWebContents::SaveDevToolsBounds(const gfx::Rect& bounds) { pref_service_->Set(kDevToolsBoundsPref, base::Value{RectToDictionary(bounds)}); devtools_bounds_ = bounds; } double InspectableWebContents::GetDevToolsZoomLevel() const { return pref_service_->GetDouble(kDevToolsZoomPref); } void InspectableWebContents::UpdateDevToolsZoomLevel(double level) { pref_service_->SetDouble(kDevToolsZoomPref, level); } void InspectableWebContents::ActivateWindow() { // Set the zoom level. SetZoomLevelForWebContents(GetDevToolsWebContents(), GetDevToolsZoomLevel()); } void InspectableWebContents::CloseWindow() { GetDevToolsWebContents()->DispatchBeforeUnload(false /* auto_cancel */); } void InspectableWebContents::LoadCompleted() { frontend_loaded_ = true; if (managed_devtools_web_contents_) view_->ShowDevTools(activate_); // If the devtools can dock, "SetIsDocked" will be called by devtools itself. if (!can_dock_) { SetIsDocked(DispatchCallback(), false); if (!devtools_title_.empty()) { view_->SetTitle(devtools_title_); } } else { if (dock_state_.empty()) { const base::Value::Dict& prefs = pref_service_->GetDict(kDevToolsPreferences); const std::string* current_dock_state = prefs.FindString("currentDockState"); base::RemoveChars(*current_dock_state, "\"", &dock_state_); } #if BUILDFLAG(IS_WIN) auto* api_web_contents = api::WebContents::From(GetWebContents()); if (api_web_contents) { auto* win = static_cast<NativeWindowViews*>(api_web_contents->owner_window()); // When WCO is enabled, undock the devtools if the current dock // position overlaps with the position of window controls to avoid // broken layout. if (win && win->IsWindowControlsOverlayEnabled()) { if (IsAppRTL() && dock_state_ == "left") { dock_state_ = "undocked"; } else if (dock_state_ == "right") { dock_state_ = "undocked"; } } } #endif std::u16string javascript = base::UTF8ToUTF16( "EUI.DockController.DockController.instance().setDockSide(\"" + dock_state_ + "\");"); GetDevToolsWebContents()->GetPrimaryMainFrame()->ExecuteJavaScript( javascript, base::NullCallback()); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) AddDevToolsExtensionsToClient(); #endif if (view_->GetDelegate()) view_->GetDelegate()->DevToolsOpened(); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void InspectableWebContents::AddDevToolsExtensionsToClient() { // get main browser context auto* browser_context = web_contents_->GetBrowserContext(); const extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); if (!registry) return; base::Value::List results; for (auto& extension : registry->enabled_extensions()) { auto devtools_page_url = extensions::chrome_manifest_urls::GetDevToolsPage(extension.get()); if (devtools_page_url.is_empty()) continue; // Each devtools extension will need to be able to run in the devtools // process. Grant the devtools process the ability to request URLs from the // extension. content::ChildProcessSecurityPolicy::GetInstance()->GrantRequestOrigin( web_contents_->GetPrimaryMainFrame()->GetProcess()->GetID(), url::Origin::Create(extension->url())); base::Value::Dict extension_info; extension_info.Set("startPage", devtools_page_url.spec()); extension_info.Set("name", extension->name()); extension_info.Set("exposeExperimentalAPIs", extension->permissions_data()->HasAPIPermission( extensions::mojom::APIPermissionID::kExperimental)); extension_info.Set("allowFileAccess", (extension->creation_flags() & extensions::Extension::ALLOW_FILE_ACCESS) != 0); results.Append(std::move(extension_info)); } CallClientFunction("DevToolsAPI", "addExtensions", base::Value(std::move(results))); } #endif void InspectableWebContents::SetInspectedPageBounds(const gfx::Rect& rect) { if (managed_devtools_web_contents_) view_->SetContentsResizingStrategy(DevToolsContentsResizingStrategy{rect}); } void InspectableWebContents::InspectElementCompleted() {} void InspectableWebContents::InspectedURLChanged(const std::string& url) { if (managed_devtools_web_contents_) { if (devtools_title_.empty()) { view_->SetTitle( base::UTF8ToUTF16(base::StringPrintf(kTitleFormat, url.c_str()))); } } } void InspectableWebContents::LoadNetworkResource(DispatchCallback callback, const std::string& url, const std::string& headers, int stream_id) { GURL gurl(url); if (!gurl.is_valid()) { base::Value response(base::Value::Type::DICT); response.GetDict().Set("statusCode", net::HTTP_NOT_FOUND); std::move(callback).Run(&response); return; } // Create traffic annotation tag. net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("devtools_network_resource", R"( semantics { sender: "Developer Tools" description: "When user opens Developer Tools, the browser may fetch additional " "resources from the network to enrich the debugging experience " "(e.g. source map resources)." trigger: "User opens Developer Tools to debug a web page." data: "Any resources requested by Developer Tools." destination: WEBSITE } policy { cookies_allowed: YES cookies_store: "user" setting: "It's not possible to disable this feature from settings." })"); network::ResourceRequest resource_request; resource_request.url = gurl; resource_request.site_for_cookies = net::SiteForCookies::FromUrl(gurl); resource_request.headers.AddHeadersFromString(headers); auto* protocol_registry = ProtocolRegistry::FromBrowserContext( GetDevToolsWebContents()->GetBrowserContext()); NetworkResourceLoader::URLLoaderFactoryHolder url_loader_factory; if (gurl.SchemeIsFile()) { mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = AsarURLLoaderFactory::Create(); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else if (protocol_registry->IsProtocolRegistered(gurl.scheme())) { auto& protocol_handler = protocol_registry->handlers().at(gurl.scheme()); mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = ElectronURLLoaderFactory::Create(protocol_handler.first, protocol_handler.second); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else { auto* partition = GetDevToolsWebContents() ->GetBrowserContext() ->GetDefaultStoragePartition(); url_loader_factory = partition->GetURLLoaderFactoryForBrowserProcess(); } NetworkResourceLoader::Create( stream_id, this, resource_request, traffic_annotation, std::move(url_loader_factory), std::move(callback)); } void InspectableWebContents::SetIsDocked(DispatchCallback callback, bool docked) { if (managed_devtools_web_contents_) view_->SetIsDocked(docked, activate_); if (!callback.is_null()) std::move(callback).Run(nullptr); } void InspectableWebContents::OpenInNewTab(const std::string& url) { if (delegate_) delegate_->DevToolsOpenInNewTab(url); } void InspectableWebContents::ShowItemInFolder( const std::string& file_system_path) { if (file_system_path.empty()) return; base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path); platform_util::OpenPath(path.DirName(), base::BindOnce(&OnOpenItemComplete, path)); } void InspectableWebContents::SaveToFile(const std::string& url, const std::string& content, bool save_as) { if (delegate_) delegate_->DevToolsSaveToFile(url, content, save_as); } void InspectableWebContents::AppendToFile(const std::string& url, const std::string& content) { if (delegate_) delegate_->DevToolsAppendToFile(url, content); } void InspectableWebContents::RequestFileSystems() { if (delegate_) delegate_->DevToolsRequestFileSystems(); } void InspectableWebContents::AddFileSystem(const std::string& type) { if (delegate_) delegate_->DevToolsAddFileSystem(type, base::FilePath()); } void InspectableWebContents::RemoveFileSystem( const std::string& file_system_path) { if (delegate_) delegate_->DevToolsRemoveFileSystem( base::FilePath::FromUTF8Unsafe(file_system_path)); } void InspectableWebContents::UpgradeDraggedFileSystemPermissions( const std::string& file_system_url) {} void InspectableWebContents::IndexPath(int request_id, const std::string& file_system_path, const std::string& excluded_folders) { if (delegate_) delegate_->DevToolsIndexPath(request_id, file_system_path, excluded_folders); } void InspectableWebContents::StopIndexing(int request_id) { if (delegate_) delegate_->DevToolsStopIndexing(request_id); } void InspectableWebContents::SearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (delegate_) delegate_->DevToolsSearchInPath(request_id, file_system_path, query); } void InspectableWebContents::SetWhitelistedShortcuts( const std::string& message) {} void InspectableWebContents::SetEyeDropperActive(bool active) { if (delegate_) delegate_->DevToolsSetEyeDropperActive(active); } void InspectableWebContents::ShowCertificateViewer( const std::string& cert_chain) {} void InspectableWebContents::ZoomIn() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), false); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); UpdateDevToolsZoomLevel(new_level); } void InspectableWebContents::ZoomOut() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), true); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); UpdateDevToolsZoomLevel(new_level); } void InspectableWebContents::ResetZoom() { SetZoomLevelForWebContents(GetDevToolsWebContents(), 0.); UpdateDevToolsZoomLevel(0.); } void InspectableWebContents::SetDevicesDiscoveryConfig( bool discover_usb_devices, bool port_forwarding_enabled, const std::string& port_forwarding_config, bool network_discovery_enabled, const std::string& network_discovery_config) {} void InspectableWebContents::SetDevicesUpdatesEnabled(bool enabled) {} void InspectableWebContents::PerformActionOnRemotePage( const std::string& page_id, const std::string& action) {} void InspectableWebContents::OpenRemotePage(const std::string& browser_id, const std::string& url) {} void InspectableWebContents::OpenNodeFrontend() {} void InspectableWebContents::DispatchProtocolMessageFromDevToolsFrontend( const std::string& message) { // If the devtools wants to reload the page, hijack the message and handle it // to the delegate. if (base::MatchPattern(message, "{\"id\":*," "\"method\":\"Page.reload\"," "\"params\":*}")) { if (delegate_) delegate_->DevToolsReloadPage(); return; } if (agent_host_) agent_host_->DispatchProtocolMessage( this, base::as_bytes(base::make_span(message))); } void InspectableWebContents::SendJsonRequest(DispatchCallback callback, const std::string& browser_id, const std::string& url) { std::move(callback).Run(nullptr); } void InspectableWebContents::GetPreferences(DispatchCallback callback) { const base::Value& prefs = pref_service_->GetValue(kDevToolsPreferences); std::move(callback).Run(&prefs); } void InspectableWebContents::GetPreference(DispatchCallback callback, const std::string& name) { if (auto* pref = pref_service_->GetDict(kDevToolsPreferences).Find(name)) { std::move(callback).Run(pref); return; } // Pref wasn't found, return an empty value base::Value no_pref; std::move(callback).Run(&no_pref); } void InspectableWebContents::SetPreference(const std::string& name, const std::string& value) { ScopedDictPrefUpdate update(pref_service_, kDevToolsPreferences); update->Set(name, base::Value(value)); } void InspectableWebContents::RemovePreference(const std::string& name) { ScopedDictPrefUpdate update(pref_service_, kDevToolsPreferences); update->Remove(name); } void InspectableWebContents::ClearPreferences() { ScopedDictPrefUpdate unsynced_update(pref_service_, kDevToolsPreferences); unsynced_update->clear(); } void InspectableWebContents::GetSyncInformation(DispatchCallback callback) { base::Value result(base::Value::Type::DICT); result.GetDict().Set("isSyncActive", false); std::move(callback).Run(&result); } void InspectableWebContents::ConnectionReady() {} void InspectableWebContents::RegisterExtensionsAPI(const std::string& origin, const std::string& script) { extensions_api_[origin + "/"] = script; } void InspectableWebContents::HandleMessageFromDevToolsFrontend( base::Value::Dict message) { // TODO(alexeykuzmin): Should we expect it to exist? if (!embedder_message_dispatcher_) { return; } const std::string* method = message.FindString(kFrontendHostMethod); base::Value* params = message.Find(kFrontendHostParams); if (!method || (params && !params->is_list())) { LOG(ERROR) << "Invalid message was sent to embedder: " << message; return; } const base::Value::List no_params; const base::Value::List& params_list = params != nullptr && params->is_list() ? params->GetList() : no_params; const int id = message.FindInt(kFrontendHostId).value_or(0); embedder_message_dispatcher_->Dispatch( base::BindRepeating(&InspectableWebContents::SendMessageAck, weak_factory_.GetWeakPtr(), id), *method, params_list); } void InspectableWebContents::DispatchProtocolMessage( content::DevToolsAgentHost* agent_host, base::span<const uint8_t> message) { if (!frontend_loaded_) return; base::StringPiece str_message(reinterpret_cast<const char*>(message.data()), message.size()); if (str_message.length() < kMaxMessageChunkSize) { CallClientFunction("DevToolsAPI", "dispatchMessage", base::Value(std::string(str_message))); } else { size_t total_size = str_message.length(); for (size_t pos = 0; pos < str_message.length(); pos += kMaxMessageChunkSize) { base::StringPiece str_message_chunk = str_message.substr(pos, kMaxMessageChunkSize); CallClientFunction( "DevToolsAPI", "dispatchMessageChunk", base::Value(std::string(str_message_chunk)), base::Value(base::NumberToString(pos ? 0 : total_size))); } } } void InspectableWebContents::AgentHostClosed( content::DevToolsAgentHost* agent_host) {} void InspectableWebContents::RenderFrameHostChanged( content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { if (new_host->GetParent()) return; frontend_host_ = content::DevToolsFrontendHost::Create( new_host, base::BindRepeating( &InspectableWebContents::HandleMessageFromDevToolsFrontend, weak_factory_.GetWeakPtr())); } void InspectableWebContents::WebContentsDestroyed() { if (managed_devtools_web_contents_) managed_devtools_web_contents_->SetDelegate(nullptr); frontend_loaded_ = false; external_devtools_web_contents_ = nullptr; Observe(nullptr); Detach(); embedder_message_dispatcher_.reset(); if (view_ && view_->GetDelegate()) view_->GetDelegate()->DevToolsClosed(); } bool InspectableWebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { auto* delegate = web_contents_->GetDelegate(); return !delegate || delegate->HandleKeyboardEvent(source, event); } void InspectableWebContents::CloseContents(content::WebContents* source) { // This is where the devtools closes itself (by clicking the x button). CloseDevTools(); } void InspectableWebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { auto* delegate = web_contents_->GetDelegate(); if (delegate) delegate->RunFileChooser(render_frame_host, std::move(listener), params); } void InspectableWebContents::EnumerateDirectory( content::WebContents* source, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { auto* delegate = web_contents_->GetDelegate(); if (delegate) delegate->EnumerateDirectory(source, std::move(listener), path); } void InspectableWebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { #if defined(TOOLKIT_VIEWS) if (view_->GetDelegate()) view_->GetDelegate()->DevToolsFocused(); #endif } void InspectableWebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame()) { if (navigation_handle->GetRenderFrameHost() == GetDevToolsWebContents()->GetPrimaryMainFrame() && frontend_host_) { return; } frontend_host_ = content::DevToolsFrontendHost::Create( web_contents()->GetPrimaryMainFrame(), base::BindRepeating( &InspectableWebContents::HandleMessageFromDevToolsFrontend, base::Unretained(this))); return; } } void InspectableWebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame() || !navigation_handle->GetURL().SchemeIs("chrome-extension") || !navigation_handle->HasCommitted()) return; content::RenderFrameHost* frame = navigation_handle->GetRenderFrameHost(); auto origin = navigation_handle->GetURL().DeprecatedGetOriginAsURL().spec(); auto it = extensions_api_.find(origin); if (it == extensions_api_.end()) return; // Injected Script from devtools frontend doesn't expose chrome, // most likely bug in chromium. base::ReplaceFirstSubstringAfterOffset(&it->second, 0, "var chrome", "var chrome = window.chrome "); auto script = base::StringPrintf( "%s(\"%s\")", it->second.c_str(), base::Uuid::GenerateRandomV4().AsLowercaseString().c_str()); // Invoking content::DevToolsFrontendHost::SetupExtensionsAPI(frame, script); // should be enough, but it seems to be a noop currently. frame->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script), base::NullCallback()); } void InspectableWebContents::SendMessageAck(int request_id, const base::Value* arg) { if (arg) { CallClientFunction("DevToolsAPI", "embedderMessageAck", base::Value(request_id), arg->Clone()); } else { CallClientFunction("DevToolsAPI", "embedderMessageAck", base::Value(request_id)); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,660
[Bug]: Can not open devtools after closing
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 28.0.0-beta.10 ### What operating system are you using? Windows ### Operating System Version 10.0.19042 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Devtools should open ### Actual Behavior After opening devtools and closing them, it is not possible to reopen the devtools ### Testcase Gist URL https://gist.github.com/t57ser/9ca91183cb53fd45eb6c73c42f92903e ### Additional Information _No response_
https://github.com/electron/electron/issues/40660
https://github.com/electron/electron/pull/40666
344b7f0d068ae7d20fdebafc2ebadcdc0b4f7f68
3609fc7402881b1d51f6c56249506d5dd3fcbe93
2023-11-30T12:43:35Z
c++
2023-12-01T19:37:52Z
spec/api-web-contents-spec.ts
import { expect } from 'chai'; import { AddressInfo } from 'node:net'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as http from 'node:http'; import { BrowserWindow, ipcMain, webContents, session, app, BrowserView, WebContents } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import { ifdescribe, defer, waitUntil, listen, ifit } from './lib/spec-helpers'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; const pdfjs = require('pdfjs-dist'); const fixturesPath = path.resolve(__dirname, 'fixtures'); const mainFixturesPath = path.resolve(__dirname, 'fixtures'); const features = process._linkedBinding('electron_common_features'); describe('webContents module', () => { describe('getAllWebContents() API', () => { afterEach(closeAllWindows); it('returns an array of web contents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html')); await once(w.webContents, 'did-attach-webview') as [any, WebContents]; w.webContents.openDevTools(); await once(w.webContents, 'devtools-opened'); const all = webContents.getAllWebContents().sort((a, b) => { return a.id - b.id; }); expect(all).to.have.length(3); expect(all[0].getType()).to.equal('window'); expect(all[all.length - 2].getType()).to.equal('webview'); expect(all[all.length - 1].getType()).to.equal('remote'); }); }); describe('fromId()', () => { it('returns undefined for an unknown id', () => { expect(webContents.fromId(12345)).to.be.undefined(); }); }); describe('fromFrame()', () => { it('returns WebContents for mainFrame', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); expect(webContents.fromFrame(contents.mainFrame)).to.equal(contents); }); it('returns undefined for disposed frame', async () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); const { mainFrame } = contents; contents.destroy(); await waitUntil(() => typeof webContents.fromFrame(mainFrame) === 'undefined'); }); it('throws when passing invalid argument', async () => { let errored = false; try { webContents.fromFrame({} as any); } catch { errored = true; } expect(errored).to.be.true(); }); }); describe('fromDevToolsTargetId()', () => { it('returns WebContents for attached DevTools target', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); try { await w.webContents.debugger.attach('1.3'); const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo'); expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents); } finally { await w.webContents.debugger.detach(); } }); it('returns undefined for an unknown id', () => { expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined(); }); }); describe('will-prevent-unload event', function () { afterEach(closeAllWindows); it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('does not emit if beforeunload returns undefined in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); view.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits if beforeunload returns false in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, 'will-prevent-unload'); }); it('emits if beforeunload returns false in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(view.webContents, 'will-prevent-unload'); }); it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', event => event.preventDefault()); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); const wait = once(w, 'closed'); w.close(); await wait; }); }); describe('webContents.send(channel, args...)', () => { afterEach(closeAllWindows); it('throws an error when the channel is missing', () => { const w = new BrowserWindow({ show: false }); expect(() => { (w.webContents.send as any)(); }).to.throw('Missing required channel argument'); expect(() => { w.webContents.send(null as any); }).to.throw('Missing required channel argument'); }); it('does not block node async APIs when sent before document is ready', (done) => { // Please reference https://github.com/electron/electron/issues/19368 if // this test fails. ipcMain.once('async-node-api-done', () => { done(); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, sandbox: false, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html')); setTimeout(50).then(() => { w.webContents.send('test'); }); }); }); ifdescribe(features.isPrintingEnabled())('webContents.print()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('throws when invalid settings are passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print(true); }).to.throw('webContents.print(): Invalid print settings specified.'); }); it('throws when an invalid pageSize is passed', () => { const badSize = 5; expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({ pageSize: badSize }); }).to.throw(`Unsupported pageSize: ${badSize}`); }); it('throws when an invalid callback is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({}, true); }).to.throw('webContents.print(): Invalid optional callback provided.'); }); it('fails when an invalid deviceName is passed', (done) => { w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => { expect(success).to.equal(false); expect(reason).to.match(/Invalid deviceName provided/); done(); }); }); it('throws when an invalid pageSize is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {}); }).to.throw('Unsupported pageSize: i-am-a-bad-pagesize'); }); it('throws when an invalid custom pageSize is passed', () => { expect(() => { w.webContents.print({ pageSize: { width: 100, height: 200 } }); }).to.throw('height and width properties must be minimum 352 microns.'); }); it('does not crash with custom margins', () => { expect(() => { w.webContents.print({ silent: true, margins: { marginType: 'custom', top: 1, bottom: 1, left: 1, right: 1 } }); }).to.not.throw(); }); }); describe('webContents.executeJavaScript', () => { describe('in about:blank', () => { const expected = 'hello, world!'; const expectedErrorMsg = 'woops!'; const code = `(() => "${expected}")()`; const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`; const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`; const errorTypes = new Set([ Error, ReferenceError, EvalError, RangeError, SyntaxError, TypeError, URIError ]); let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } }); await w.loadURL('about:blank'); }); after(closeAllWindows); it('resolves the returned promise with the result', async () => { const result = await w.webContents.executeJavaScript(code); expect(result).to.equal(expected); }); it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => { const result = await w.webContents.executeJavaScript(asyncCode); expect(result).to.equal(expected); }); it('rejects the returned promise if an async error is thrown', async () => { await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg); }); it('rejects the returned promise with an error if an Error.prototype is thrown', async () => { for (const error of errorTypes) { await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`)) .to.eventually.be.rejectedWith(error); } }); }); describe('on a real page', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('works after page load and during subframe load', async () => { await w.loadURL(serverUrl); // initiate a sub-frame load, then try and execute script during it await w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/slow' document.body.appendChild(iframe) null // don't return the iframe `); await w.webContents.executeJavaScript('console.log(\'hello\')'); }); it('executes after page load', async () => { const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()'); w.loadURL(serverUrl); const result = await executeJavaScript; expect(result).to.equal('test'); }); }); }); describe('webContents.executeJavaScriptInIsolatedWorld', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadURL('about:blank'); }); it('resolves the returned promise with the result', async () => { await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]); const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]); const mainWorldResult = await w.webContents.executeJavaScript('window.X'); expect(isolatedResult).to.equal(123); expect(mainWorldResult).to.equal(undefined); }); }); describe('loadURL() promise API', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('resolves when done loading', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('resolves when done loading a file URL', async () => { await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled(); }); it('resolves when navigating within the page', async () => { await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await setTimeout(); await expect(w.loadURL(w.getURL() + '#foo')).to.eventually.be.fulfilled(); }); it('resolves after browser initiated navigation', async () => { let finishedLoading = false; w.webContents.on('did-finish-load', function () { finishedLoading = true; }); await w.loadFile(path.join(fixturesPath, 'pages', 'navigate_in_page_and_wait.html')); expect(finishedLoading).to.be.true(); }); it('rejects when failing to load a file URL', async () => { await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FILE_NOT_FOUND'); }); // FIXME: Temporarily disable on WOA until // https://github.com/electron/electron/issues/20008 is resolved ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('rejects when loading fails due to DNS not resolved', async () => { await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected() .and.have.property('code', 'ERR_NAME_NOT_RESOLVED'); }); it('rejects when navigation is cancelled due to a bad scheme', async () => { await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FAILED'); }); it('does not crash when loading a new URL with emulation settings set', async () => { const setEmulation = async () => { if (w.webContents) { w.webContents.debugger.attach('1.3'); const deviceMetrics = { width: 700, height: 600, deviceScaleFactor: 2, mobile: true, dontSetVisibleSize: true }; await w.webContents.debugger.sendCommand( 'Emulation.setDeviceMetricsOverride', deviceMetrics ); } }; try { await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await setEmulation(); await w.loadURL('data:text/html,<h1>HELLO</h1>'); await setEmulation(); } catch (e) { expect((e as Error).message).to.match(/Debugger is already attached to the target/); } }); it('fails if loadURL is called inside a non-reentrant critical section', (done) => { w.webContents.once('did-fail-load', (_event, _errorCode, _errorDescription, validatedURL) => { expect(validatedURL).to.contain('blank.html'); done(); }); w.webContents.once('did-start-loading', () => { w.loadURL(`file://${fixturesPath}/pages/blank.html`); }); w.loadURL('data:text/html,<h1>HELLO</h1>'); }); it('sets appropriate error information on rejection', async () => { let err: any; try { await w.loadURL('file:non-existent'); } catch (e) { err = e; } expect(err).not.to.be.null(); expect(err.code).to.eql('ERR_FILE_NOT_FOUND'); expect(err.errno).to.eql(-6); expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent'); }); it('rejects if the load is aborted', async () => { const s = http.createServer(() => { /* never complete the request */ }); const { port } = await listen(s); const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/); // load a different file before the first load completes, causing the // first load to be aborted. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await p; s.close(); }); it("doesn't reject when a subframe fails to load", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="http://err.name.not.resolved"></iframe>'); resp = res; // don't end the response yet }); const { port } = await listen(s); const p = new Promise<void>(resolve => { w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.end(); await main; s.close(); }); it("doesn't resolve when a subframe loads", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="about:blank"></iframe>'); resp = res; // don't end the response yet }); const { port } = await listen(s); const p = new Promise<void>(resolve => { w.webContents.on('did-frame-finish-load', (event, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.destroy(); // cause the main request to fail await expect(main).to.eventually.be.rejected() .and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING s.close(); }); }); describe('getFocusedWebContents() API', () => { afterEach(closeAllWindows); // FIXME ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('returns the focused web contents', async () => { const w = new BrowserWindow({ show: true }); await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id); const devToolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools(); await devToolsOpened; expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.devToolsWebContents!.id); const devToolsClosed = once(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id); }); it('does not crash when called on a detached dev tools window', async () => { const w = new BrowserWindow({ show: true }); w.webContents.openDevTools({ mode: 'detach' }); w.webContents.inspectElement(100, 100); // For some reason we have to wait for two focused events...? await once(w.webContents, 'devtools-focused'); expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); // Work around https://github.com/electron/electron/issues/19985 await setTimeout(); const devToolsClosed = once(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); }); }); describe('setDevToolsWebContents() API', () => { afterEach(closeAllWindows); it('sets arbitrary webContents as devtools', async () => { const w = new BrowserWindow({ show: false }); const devtools = new BrowserWindow({ show: false }); const promise = once(devtools.webContents, 'dom-ready'); w.webContents.setDevToolsWebContents(devtools.webContents); w.webContents.openDevTools(); await promise; expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true(); const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name'); expect(result).to.equal('InspectorFrontendHostImpl'); devtools.destroy(); }); }); describe('isFocused() API', () => { it('returns false when the window is hidden', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(w.isVisible()).to.be.false(); expect(w.webContents.isFocused()).to.be.false(); }); }); describe('isCurrentlyAudible() API', () => { afterEach(closeAllWindows); it('returns whether audio is playing', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript(` window.context = new AudioContext // Start in suspended state, because of the // new web audio api policy. context.suspend() window.oscillator = context.createOscillator() oscillator.connect(context.destination) oscillator.start() `); let p = once(w.webContents, 'audio-state-changed'); w.webContents.executeJavaScript('context.resume()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.true(); p = once(w.webContents, 'audio-state-changed'); w.webContents.executeJavaScript('oscillator.stop()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.false(); }); }); describe('openDevTools() API', () => { afterEach(closeAllWindows); it('can show window with activation', async () => { const w = new BrowserWindow({ show: false }); const focused = once(w, 'focus'); w.show(); await focused; expect(w.isFocused()).to.be.true(); const blurred = once(w, 'blur'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await Promise.all([ once(w.webContents, 'devtools-opened'), once(w.webContents, 'devtools-focused') ]); await blurred; expect(w.isFocused()).to.be.false(); }); it('can show window without activation', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); }); it('can show a DevTools window with custom title', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false, title: 'myTitle' }); await devtoolsOpened; expect(w.webContents.getDevToolsTitle()).to.equal('myTitle'); }); }); describe('setDevToolsTitle() API', () => { afterEach(closeAllWindows); it('can set devtools title with function', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); w.webContents.setDevToolsTitle('newTitle'); expect(w.webContents.getDevToolsTitle()).to.equal('newTitle'); }); }); describe('before-input-event event', () => { afterEach(closeAllWindows); it('can prevent document keyboard events', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); const keyDown = new Promise(resolve => { ipcMain.once('keydown', (event, key) => resolve(key)); }); w.webContents.once('before-input-event', (event, input) => { if (input.key === 'a') event.preventDefault(); }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' }); expect(await keyDown).to.equal('b'); }); it('has the correct properties', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testBeforeInput = async (opts: any) => { const modifiers = []; if (opts.shift) modifiers.push('shift'); if (opts.control) modifiers.push('control'); if (opts.alt) modifiers.push('alt'); if (opts.meta) modifiers.push('meta'); if (opts.isAutoRepeat) modifiers.push('isAutoRepeat'); const p = once(w.webContents, 'before-input-event') as Promise<[any, Electron.Input]>; w.webContents.sendInputEvent({ type: opts.type, keyCode: opts.keyCode, modifiers: modifiers as any }); const [, input] = await p; expect(input.type).to.equal(opts.type); expect(input.key).to.equal(opts.key); expect(input.code).to.equal(opts.code); expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat); expect(input.shift).to.equal(opts.shift); expect(input.control).to.equal(opts.control); expect(input.alt).to.equal(opts.alt); expect(input.meta).to.equal(opts.meta); }; await testBeforeInput({ type: 'keyDown', key: 'A', code: 'KeyA', keyCode: 'a', shift: true, control: true, alt: true, meta: true, isAutoRepeat: true }); await testBeforeInput({ type: 'keyUp', key: '.', code: 'Period', keyCode: '.', shift: false, control: true, alt: true, meta: false, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: '!', code: 'Digit1', keyCode: '1', shift: true, control: false, alt: false, meta: true, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: 'Tab', code: 'Tab', keyCode: 'Tab', shift: false, control: true, alt: false, meta: false, isAutoRepeat: true }); }); }); // On Mac, zooming isn't done with the mouse wheel. ifdescribe(process.platform !== 'darwin')('zoom-changed', () => { afterEach(closeAllWindows); it('is emitted with the correct zoom-in info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: 1, wheelTicksX: 0, wheelTicksY: 1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string]; expect(zoomDirection).to.equal('in'); }; await testZoomChanged(); }); it('is emitted with the correct zoom-out info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: -1, wheelTicksX: 0, wheelTicksY: -1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string]; expect(zoomDirection).to.equal('out'); }; await testZoomChanged(); }); }); describe('sendInputEvent(event)', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); }); afterEach(closeAllWindows); it('can send keydown events', async () => { const keydown = once(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send keydown events with modifiers', async () => { const keydown = once(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); it('can send keydown events with special keys', async () => { const keydown = once(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Tab'); expect(code).to.equal('Tab'); expect(keyCode).to.equal(9); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.true(); }); it('can send char events', async () => { const keypress = once(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can correctly convert accelerators to key codes', async () => { const keyup = once(ipcMain, 'keyup'); w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'keyUp' }); await keyup; const inputText = await w.webContents.executeJavaScript('document.getElementById("input").value'); expect(inputText).to.equal('+ + +'); }); it('can send char events with modifiers', async () => { const keypress = once(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); }); describe('insertCSS', () => { afterEach(closeAllWindows); it('supports inserting CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.webContents.insertCSS('body { background-repeat: round; }'); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('round'); }); it('supports removing inserted CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const key = await w.webContents.insertCSS('body { background-repeat: round; }'); await w.webContents.removeInsertedCSS(key); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('repeat'); }); }); describe('inspectElement()', () => { afterEach(closeAllWindows); it('supports inspecting an element in the devtools', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const event = once(w.webContents, 'devtools-opened'); w.webContents.inspectElement(10, 10); await event; }); }); describe('startDrag({file, icon})', () => { it('throws errors for a missing file or a missing/empty icon', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any); }).to.throw('Must specify either \'file\' or \'files\' option'); expect(() => { w.webContents.startDrag({ file: __filename } as any); }).to.throw('\'icon\' parameter is required'); expect(() => { w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') }); }).to.throw(/Failed to load image from path (.+)/); }); }); describe('focus APIs', () => { describe('focus()', () => { afterEach(closeAllWindows); it('does not blur the focused window when the web contents is hidden', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.show(); await w.loadURL('about:blank'); w.focus(); const child = new BrowserWindow({ show: false }); child.loadURL('about:blank'); child.webContents.focus(); const currentFocused = w.isFocused(); const childFocused = child.isFocused(); child.close(); expect(currentFocused).to.be.true(); expect(childFocused).to.be.false(); }); }); const moveFocusToDevTools = async (win: BrowserWindow) => { const devToolsOpened = once(win.webContents, 'devtools-opened'); win.webContents.openDevTools({ mode: 'right' }); await devToolsOpened; win.webContents.devToolsWebContents!.focus(); }; describe('focus event', () => { afterEach(closeAllWindows); it('is triggered when web contents is focused', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await moveFocusToDevTools(w); const focusPromise = once(w.webContents, 'focus'); w.webContents.focus(); await expect(focusPromise).to.eventually.be.fulfilled(); }); }); describe('blur event', () => { afterEach(closeAllWindows); it('is triggered when web contents is blurred', async () => { const w = new BrowserWindow({ show: true }); await w.loadURL('about:blank'); w.webContents.focus(); const blurPromise = once(w.webContents, 'blur'); await moveFocusToDevTools(w); await expect(blurPromise).to.eventually.be.fulfilled(); }); }); }); describe('getOSProcessId()', () => { afterEach(closeAllWindows); it('returns a valid process id', async () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getOSProcessId()).to.equal(0); await w.loadURL('about:blank'); expect(w.webContents.getOSProcessId()).to.be.above(0); }); }); describe('getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns a valid stream id', () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty(); }); }); describe('userAgent APIs', () => { it('is not empty by default', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); expect(userAgent).to.be.a('string').that.is.not.empty(); }); it('can set the user agent (functions)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); w.webContents.setUserAgent('my-user-agent'); expect(w.webContents.getUserAgent()).to.equal('my-user-agent'); w.webContents.setUserAgent(userAgent); expect(w.webContents.getUserAgent()).to.equal(userAgent); }); it('can set the user agent (properties)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.userAgent; w.webContents.userAgent = 'my-user-agent'; expect(w.webContents.userAgent).to.equal('my-user-agent'); w.webContents.userAgent = userAgent; expect(w.webContents.userAgent).to.equal(userAgent); }); }); describe('audioMuted APIs', () => { it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.setAudioMuted(true); expect(w.webContents.isAudioMuted()).to.be.true(); w.webContents.setAudioMuted(false); expect(w.webContents.isAudioMuted()).to.be.false(); }); it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.audioMuted = true; expect(w.webContents.audioMuted).to.be.true(); w.webContents.audioMuted = false; expect(w.webContents.audioMuted).to.be.false(); }); }); describe('zoom api', () => { const hostZoomMap: Record<string, number> = { host1: 0.3, host2: 0.7, host3: 0.2 }; before(() => { const protocol = session.defaultSession.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { const response = `<script> const {ipcRenderer} = require('electron') ipcRenderer.send('set-zoom', window.location.hostname) ipcRenderer.on(window.location.hostname + '-zoom-set', () => { ipcRenderer.send(window.location.hostname + '-zoom-level') }) </script>`; callback({ data: response, mimeType: 'text/html' }); }); }); after(() => { const protocol = session.defaultSession.protocol; protocol.unregisterProtocol(standardScheme); }); afterEach(closeAllWindows); it('throws on an invalid zoomFactor', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { w.webContents.setZoomFactor(0.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); expect(() => { w.webContents.setZoomFactor(-2.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); }); it('can set the correct zoom level (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.getZoomLevel(); expect(zoomLevel).to.eql(0.0); w.webContents.setZoomLevel(0.5); const newZoomLevel = w.webContents.getZoomLevel(); expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.setZoomLevel(0); } }); it('can set the correct zoom level (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.eql(0.0); w.webContents.zoomLevel = 0.5; const newZoomLevel = w.webContents.zoomLevel; expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.zoomLevel = 0; } }); it('can set the correct zoom factor (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.getZoomFactor(); expect(zoomFactor).to.eql(1.0); w.webContents.setZoomFactor(0.5); const newZoomFactor = w.webContents.getZoomFactor(); expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.setZoomFactor(1.0); } }); it('can set the correct zoom factor (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.zoomFactor; expect(zoomFactor).to.eql(1.0); w.webContents.zoomFactor = 0.5; const newZoomFactor = w.webContents.zoomFactor; expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.zoomFactor = 1.0; } }); it('can persist zoom level across navigation', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let finalNavigation = false; ipcMain.on('set-zoom', (e, host) => { const zoomLevel = hostZoomMap[host]; if (!finalNavigation) w.webContents.zoomLevel = zoomLevel; e.sender.send(`${host}-zoom-set`); }); ipcMain.on('host1-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host1; expect(zoomLevel).to.equal(expectedZoomLevel); if (finalNavigation) { done(); } else { w.loadURL(`${standardScheme}://host2`); } } catch (e) { done(e); } }); ipcMain.once('host2-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host2; expect(zoomLevel).to.equal(expectedZoomLevel); finalNavigation = true; w.webContents.goBack(); } catch (e) { done(e); } }); w.loadURL(`${standardScheme}://host1`); }); it('can propagate zoom level across same session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false }); defer(() => { w2.setClosable(true); w2.close(); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel1).to.equal(zoomLevel2); }); it('cannot propagate zoom level across different session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false, webPreferences: { partition: 'temp' } }); const protocol = w2.webContents.session.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { callback('hello'); }); defer(() => { w2.setClosable(true); w2.close(); protocol.unregisterProtocol(standardScheme); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); it('can persist when it contains iframe', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { setTimeout(200).then(() => { res.end(); }); }); listen(server).then(({ url }) => { const content = `<iframe src=${url}></iframe>`; w.webContents.on('did-frame-finish-load', (e, isMainFrame) => { if (!isMainFrame) { try { const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(2.0); w.webContents.zoomLevel = 0; done(); } catch (e) { done(e); } finally { server.close(); } } }); w.webContents.on('dom-ready', () => { w.webContents.zoomLevel = 2.0; }); w.loadURL(`data:text/html,${content}`); }); }); it('cannot propagate when used with webframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const w2 = new BrowserWindow({ show: false }); const temporaryZoomSet = once(ipcMain, 'temporary-zoom-set'); w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html')); await temporaryZoomSet; const finalZoomLevel = w.webContents.getZoomLevel(); await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html')); const zoomLevel1 = w.webContents.zoomLevel; const zoomLevel2 = w2.webContents.zoomLevel; w2.setClosable(true); w2.close(); expect(zoomLevel1).to.equal(finalZoomLevel); expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); describe('with unique domains', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before(async () => { server = http.createServer((req, res) => { setTimeout().then(() => res.end('hey')); }); serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); after(() => { server.close(); }); it('cannot persist zoom level after navigation with webFrame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const source = ` const {ipcRenderer, webFrame} = require('electron') webFrame.setZoomLevel(0.6) ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel()) `; const zoomLevelPromise = once(ipcMain, 'zoom-level-set'); await w.loadURL(serverUrl); await w.webContents.executeJavaScript(source); let [, zoomLevel] = await zoomLevelPromise; expect(zoomLevel).to.equal(0.6); const loadPromise = once(w.webContents, 'did-finish-load'); await w.loadURL(crossSiteUrl); await loadPromise; zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(0); }); }); }); describe('webrtc ip policy api', () => { afterEach(closeAllWindows); it('can set and get webrtc ip policies', () => { const w = new BrowserWindow({ show: false }); const policies = [ 'default', 'default_public_interface_only', 'default_public_and_private_interfaces', 'disable_non_proxied_udp' ] as const; for (const policy of policies) { w.webContents.setWebRTCIPHandlingPolicy(policy); expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy); } }); }); describe('webrtc udp port range policy api', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('check default webrtc udp port range is { min: 0, max: 0 }', () => { const settings = w.webContents.getWebRTCUDPPortRange(); expect(settings).to.deep.equal({ min: 0, max: 0 }); }); it('can set and get webrtc udp port range policy with correct arguments', () => { w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 }); const settings = w.webContents.getWebRTCUDPPortRange(); expect(settings).to.deep.equal({ min: 1, max: 65535 }); }); it('can not set webrtc udp port range policy with invalid arguments', () => { expect(() => { w.webContents.setWebRTCUDPPortRange({ min: 0, max: 65535 }); }).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]"); expect(() => { w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65536 }); }).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]"); expect(() => { w.webContents.setWebRTCUDPPortRange({ min: 60000, max: 56789 }); }).to.throw("'max' must be greater than or equal to 'min'"); }); it('can reset webrtc udp port range policy to default with { min: 0, max: 0 }', () => { w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 }); const settings = w.webContents.getWebRTCUDPPortRange(); expect(settings).to.deep.equal({ min: 1, max: 65535 }); w.webContents.setWebRTCUDPPortRange({ min: 0, max: 0 }); const defaultSetting = w.webContents.getWebRTCUDPPortRange(); expect(defaultSetting).to.deep.equal({ min: 0, max: 0 }); }); }); describe('opener api', () => { afterEach(closeAllWindows); it('can get opener with window.open()', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>; w.webContents.executeJavaScript('window.open("about:blank")', true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame); }); it('has no opener when using "noopener"', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>; w.webContents.executeJavaScript('window.open("about:blank", undefined, "noopener")', true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.be.null(); }); it('can get opener with a[target=_blank][rel=opener]', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>; w.webContents.executeJavaScript(`(function() { const a = document.createElement('a'); a.target = '_blank'; a.rel = 'opener'; a.href = 'about:blank'; a.click(); }())`, true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame); }); it('has no opener with a[target=_blank][rel=noopener]', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>; w.webContents.executeJavaScript(`(function() { const a = document.createElement('a'); a.target = '_blank'; a.rel = 'noopener'; a.href = 'about:blank'; a.click(); }())`, true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.be.null(); }); }); describe('render view deleted events', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before(async () => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${crossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else if (req.url === '/first-window-open') { res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`); } else if (req.url === '/second-window-open') { res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>'); } else { res.end(); } }; setTimeout().then(respond); }); serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); after(() => { server.close(); }); afterEach(closeAllWindows); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); w.webContents.on('did-finish-load', () => { w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted'); }); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const parentWindow = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; let childWindow: BrowserWindow | null = null; const destroyed = once(parentWindow.webContents, 'destroyed'); const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; const childWindowCreated = new Promise<void>((resolve) => { app.once('browser-window-created', (event, window) => { childWindow = window; window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); resolve(); }); }); parentWindow.loadURL(`${serverUrl}/first-window-open`); await childWindowCreated; childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); parentWindow.close(); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed'); }); it('emits current-render-view-deleted if the current RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; w.webContents.on('current-render-view-deleted' as any, () => { currentRenderViewDeletedEmitted = true; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted'); }); it('emits render-view-deleted if any RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let rvhDeletedCount = 0; w.webContents.on('render-view-deleted' as any, () => { rvhDeletedCount++; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; const expectedRenderViewDeletedEventCount = 1; expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times'); }); }); describe('setIgnoreMenuShortcuts(ignore)', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.setIgnoreMenuShortcuts(true); w.webContents.setIgnoreMenuShortcuts(false); }).to.not.throw(); }); }); const crashPrefs = [ { nodeIntegration: true }, { sandbox: true } ]; const nicePrefs = (o: any) => { let s = ''; for (const key of Object.keys(o)) { s += `${key}=${o[key]}, `; } return `(${s.slice(0, s.length - 2)})`; }; for (const prefs of crashPrefs) { describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('isCrashed() is false by default', () => { expect(w.webContents.isCrashed()).to.equal(false); }); it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => { expect(w.webContents.isCrashed()).to.equal(false); const crashEvent = once(w.webContents, 'render-process-gone') as Promise<[any, Electron.RenderProcessGoneDetails]>; w.webContents.forcefullyCrashRenderer(); const [, details] = await crashEvent; expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed'); expect(w.webContents.isCrashed()).to.equal(true); }); it('a crashed process is recoverable with reload()', async () => { expect(w.webContents.isCrashed()).to.equal(false); w.webContents.forcefullyCrashRenderer(); w.webContents.reload(); expect(w.webContents.isCrashed()).to.equal(false); }); }); } // Destroying webContents in its event listener is going to crash when // Electron is built in Debug mode. describe('destroy()', () => { let server: http.Server; let serverUrl: string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/200': response.end(); break; default: done(new Error('unsupported endpoint')); } }); listen(server).then(({ url }) => { serverUrl = url; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', url: '/200' }, { name: 'dom-ready', url: '/200' }, { name: 'did-stop-loading', url: '/200' }, { name: 'did-finish-load', url: '/200' }, // FIXME: Multiple Emit calls inside an observer assume that object // will be alive till end of the observer. Synchronous `destroy` api // violates this contract and crashes. { name: 'did-frame-finish-load', url: '/200' }, { name: 'did-fail-load', url: '/net-error' } ]; for (const e of events) { it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () { // This test is flaky on Windows CI and we don't know why, but the // purpose of this test is to make sure Electron does not crash so it // is fine to retry this test for a few times. this.retries(3); const contents = (webContents as typeof ElectronInternal.WebContents).create(); const originalEmit = contents.emit.bind(contents); contents.emit = (...args) => { return originalEmit(...args); }; contents.once(e.name as any, () => contents.destroy()); const destroyed = once(contents, 'destroyed'); contents.loadURL(serverUrl + e.url); await destroyed; }); } }); describe('did-change-theme-color event', () => { afterEach(closeAllWindows); it('is triggered with correct theme color', (done) => { const w = new BrowserWindow({ show: true }); let count = 0; w.webContents.on('did-change-theme-color', (e, color) => { try { if (count === 0) { count += 1; expect(color).to.equal('#FFEEDD'); w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); } else if (count === 1) { expect(color).to.be.null(); done(); } } catch (e) { done(e); } }); w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html')); }); }); describe('console-message event', () => { afterEach(closeAllWindows); it('is triggered with correct log message', (done) => { const w = new BrowserWindow({ show: true }); w.webContents.on('console-message', (e, level, message) => { // Don't just assert as Chromium might emit other logs that we should ignore. if (message === 'a') { done(); } }); w.loadFile(path.join(fixturesPath, 'pages', 'a.html')); }); }); describe('ipc-message event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends an asynchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); w.webContents.executeJavaScript(` require('electron').ipcRenderer.send('message', 'Hello World!') `); const [, channel, message] = await once(w.webContents, 'ipc-message'); expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); }); }); describe('ipc-message-sync event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends a synchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); const promise: Promise<[string, string]> = new Promise(resolve => { w.webContents.once('ipc-message-sync', (event, channel, arg) => { event.returnValue = 'foobar'; resolve([channel, arg]); }); }); const result = await w.webContents.executeJavaScript(` require('electron').ipcRenderer.sendSync('message', 'Hello World!') `); const [channel, message] = await promise; expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); expect(result).to.equal('foobar'); }); }); describe('referrer', () => { afterEach(closeAllWindows); it('propagates referrer information to new target=_blank windows', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } finally { server.close(); } } res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>'); }); listen(server).then(({ url }) => { w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url + '/'); expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin'); return { action: 'allow' }; }); w.webContents.executeJavaScript('a.click()'); }); w.loadURL(url); }); }); it('propagates referrer information to windows opened with window.open', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } } res.end(''); }); listen(server).then(({ url }) => { w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url + '/'); expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin'); return { action: 'allow' }; }); w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")'); }); w.loadURL(url); }); }); }); describe('webframe messages in sandboxed contents', () => { afterEach(closeAllWindows); it('responds to executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const result = await w.webContents.executeJavaScript('37 + 5'); expect(result).to.equal(42); }); }); describe('preload-error event', () => { afterEach(closeAllWindows); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('is triggered when unhandled exception is thrown', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>; w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('Hello World!'); }); it('is triggered on syntax errors', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>; w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('foobar is not defined'); }); it('is triggered when preload script loading fails', async () => { const preload = path.join(fixturesPath, 'module', 'preload-invalid.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>; w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.contain('preload-invalid.js'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('takeHeapSnapshot()', () => { afterEach(closeAllWindows); it('works with sandboxed renderers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); const cleanup = () => { try { fs.unlinkSync(filePath); } catch { // ignore error } }; try { await w.webContents.takeHeapSnapshot(filePath); const stats = fs.statSync(filePath); expect(stats.size).not.to.be.equal(0); } finally { cleanup(); } }); it('fails with invalid file path', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const badPath = path.join('i', 'am', 'a', 'super', 'bad', 'path'); const promise = w.webContents.takeHeapSnapshot(badPath); return expect(promise).to.be.eventually.rejectedWith(Error, `Failed to take heap snapshot with invalid file path ${badPath}`); }); it('fails with invalid render process', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); w.webContents.destroy(); const promise = w.webContents.takeHeapSnapshot(filePath); return expect(promise).to.be.eventually.rejectedWith(Error, 'Failed to take heap snapshot with nonexistent render frame'); }); }); describe('setBackgroundThrottling()', () => { afterEach(closeAllWindows); it('does not crash when allowing', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(true); }); it('does not crash when called via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); w.setBackgroundThrottling(true); }); it('does not crash when disallowing', () => { const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } }); w.webContents.setBackgroundThrottling(false); }); }); describe('getBackgroundThrottling()', () => { afterEach(closeAllWindows); it('works via getter', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); expect(w.webContents.getBackgroundThrottling()).to.equal(false); w.webContents.setBackgroundThrottling(true); expect(w.webContents.getBackgroundThrottling()).to.equal(true); }); it('works via property', () => { const w = new BrowserWindow({ show: false }); w.webContents.backgroundThrottling = false; expect(w.webContents.backgroundThrottling).to.equal(false); w.webContents.backgroundThrottling = true; expect(w.webContents.backgroundThrottling).to.equal(true); }); it('works via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); w.setBackgroundThrottling(false); expect(w.getBackgroundThrottling()).to.equal(false); w.setBackgroundThrottling(true); expect(w.getBackgroundThrottling()).to.equal(true); }); }); ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = await w.webContents.getPrintersAsync(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('printToPDF()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); afterEach(closeAllWindows); it('rejects on incorrectly typed parameters', async () => { const badTypes = { landscape: [], displayHeaderFooter: '123', printBackground: 2, scale: 'not-a-number', pageSize: 'IAmAPageSize', margins: 'terrible', pageRanges: { oops: 'im-not-the-right-key' }, headerTemplate: [1, 2, 3], footerTemplate: [4, 5, 6], preferCSSPageSize: 'no' }; await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); // These will hard crash in Chromium unless we type-check for (const [key, value] of Object.entries(badTypes)) { const param = { [key]: value }; await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected(); } }); it('does not crash when called multiple times in parallel', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); const promises = []; for (let i = 0; i < 3; i++) { promises.push(w.webContents.printToPDF({})); } const results = await Promise.all(promises); for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); it('does not crash when called multiple times in sequence', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); const results = []; for (let i = 0; i < 3; i++) { const result = await w.webContents.printToPDF({}); results.push(result); } for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); it('can print a PDF with default settings', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); const data = await w.webContents.printToPDF({}); expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); }); type PageSizeString = Exclude<Required<Electron.PrintToPDFOptions>['pageSize'], Electron.Size>; it('with custom page sizes', async () => { const paperFormats: Record<PageSizeString, ElectronInternal.PageSize> = { Letter: { width: 8.5, height: 11 }, Legal: { width: 8.5, height: 14 }, Tabloid: { width: 11, height: 17 }, Ledger: { width: 17, height: 11 }, A0: { width: 33.1, height: 46.8 }, A1: { width: 23.4, height: 33.1 }, A2: { width: 16.54, height: 23.4 }, A3: { width: 11.7, height: 16.54 }, A4: { width: 8.27, height: 11.7 }, A5: { width: 5.83, height: 8.27 }, A6: { width: 4.13, height: 5.83 } }; await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); for (const format of Object.keys(paperFormats) as PageSizeString[]) { const data = await w.webContents.printToPDF({ pageSize: format }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); // page.view is [top, left, width, height]. const width = page.view[2] / 72; const height = page.view[3] / 72; const approxEq = (a: number, b: number, epsilon = 0.01) => Math.abs(a - b) <= epsilon; expect(approxEq(width, paperFormats[format].width)).to.be.true(); expect(approxEq(height, paperFormats[format].height)).to.be.true(); } }); it('with custom header and footer', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ displayHeaderFooter: true, headerTemplate: '<div>I\'m a PDF header</div>', footerTemplate: '<div>I\'m a PDF footer</div>' }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); const { items } = await page.getTextContent(); // Check that generated PDF contains a header. const containsText = (text: RegExp) => items.some(({ str }: { str: string }) => str.match(text)); expect(containsText(/I'm a PDF header/)).to.be.true(); expect(containsText(/I'm a PDF footer/)).to.be.true(); }); it('in landscape mode', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ landscape: true }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); // page.view is [top, left, width, height]. const width = page.view[2]; const height = page.view[3]; expect(width).to.be.greaterThan(height); }); it('with custom page ranges', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-large.html')); const data = await w.webContents.printToPDF({ pageRanges: '1-3', landscape: true }); const doc = await pdfjs.getDocument(data).promise; // Check that correct # of pages are rendered. expect(doc.numPages).to.equal(3); }); it('does not tag PDFs by default', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({}); const doc = await pdfjs.getDocument(data).promise; const markInfo = await doc.getMarkInfo(); expect(markInfo).to.be.null(); }); it('can generate tag data for PDFs', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ generateTaggedPDF: true }); const doc = await pdfjs.getDocument(data).promise; const markInfo = await doc.getMarkInfo(); expect(markInfo).to.deep.equal({ Marked: true, UserProperties: false, Suspects: false }); }); }); describe('PictureInPicture video', () => { afterEach(closeAllWindows); it('works as expected', async function () { const w = new BrowserWindow({ webPreferences: { sandbox: true } }); // TODO(codebytere): figure out why this workaround is needed and remove. // It is not germane to the actual test. await w.loadFile(path.join(fixturesPath, 'blank.html')); await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html')); await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')', true); const result = await w.webContents.executeJavaScript('runTest(true)', true); expect(result).to.be.true(); }); }); describe('Shared Workers', () => { afterEach(closeAllWindows); it('can get multiple shared workers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = once(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); expect(sharedWorkers).to.have.lengthOf(2); expect(sharedWorkers[0].url).to.contain('shared-worker'); expect(sharedWorkers[1].url).to.contain('shared-worker'); }); it('can inspect a specific shared worker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = once(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.inspectSharedWorkerById(sharedWorkers[0].id); await devtoolsOpened; const devtoolsClosed = once(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devtoolsClosed; }); }); describe('login event', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; let serverPort: number; let proxyServer: http.Server; let proxyServerPort: number; before(async () => { server = http.createServer((request, response) => { if (request.url === '/no-auth') { return response.end('ok'); } if (request.headers.authorization) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers.authorization); } response .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }) .end('401'); }); ({ port: serverPort, url: serverUrl } = await listen(server)); }); before(async () => { proxyServer = http.createServer((request, response) => { if (request.headers['proxy-authorization']) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers['proxy-authorization']); } response .writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }) .end(); }); proxyServerPort = (await listen(proxyServer)).port; }); afterEach(async () => { await session.defaultSession.clearAuthCache(); }); after(() => { server.close(); proxyServer.close(); }); it('is emitted when navigating', async () => { const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(serverUrl + '/'); expect(eventAuthInfo.isProxy).to.be.false(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(serverPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('is emitted when a proxy requests authorization', async () => { const customSession = session.fromPartition(`${Math.random()}`); await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' }); const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(`${serverUrl}/no-auth`); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`); expect(eventAuthInfo.isProxy).to.be.true(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(proxyServerPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('cancels authentication when callback is called with no arguments', async () => { const w = new BrowserWindow({ show: false }); w.webContents.on('login', (event, request, authInfo, cb) => { event.preventDefault(); cb(); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal('401'); }); }); describe('page-title-updated event', () => { afterEach(closeAllWindows); it('is emitted with a full title for pages with no navigation', async () => { const bw = new BrowserWindow({ show: false }); await bw.loadURL('about:blank'); bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null'); const [, child] = await once(app, 'web-contents-created') as [any, WebContents]; bw.webContents.executeJavaScript('child.document.title = "new title"'); const [, title] = await once(child, 'page-title-updated') as [any, string]; expect(title).to.equal('new title'); }); }); describe('context-menu event', () => { afterEach(closeAllWindows); it('emits when right-clicked in page', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const promise = once(w.webContents, 'context-menu') as Promise<[any, Electron.ContextMenuParams]>; // Simulate right-click to create context-menu event. const opts = { x: 0, y: 0, button: 'right' as const }; w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' }); w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' }); const [, params] = await promise; expect(params.pageURL).to.equal(w.webContents.getURL()); expect(params.frame).to.be.an('object'); expect(params.x).to.be.a('number'); expect(params.y).to.be.a('number'); }); }); describe('close() method', () => { afterEach(closeAllWindows); it('closes when close() is called', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('closes when close() is called after loading a page', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('can be GCed before loading a page', async () => { const v8Util = process._linkedBinding('electron_common_v8_util'); let registry: FinalizationRegistry<unknown> | null = null; const cleanedUp = new Promise<number>(resolve => { registry = new FinalizationRegistry(resolve as any); }); (() => { const w = (webContents as typeof ElectronInternal.WebContents).create(); registry!.register(w, 42); })(); const i = setInterval(() => v8Util.requestGarbageCollectionForTesting(), 100); defer(() => clearInterval(i)); expect(await cleanedUp).to.equal(42); }); it('causes its parent browserwindow to be closed', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const closed = once(w, 'closed'); w.webContents.close(); await closed; expect(w.isDestroyed()).to.be.true(); }); it('ignores beforeunload if waitForBeforeUnload not specified', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.on('will-prevent-unload', () => { throw new Error('unexpected will-prevent-unload'); }); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('runs beforeunload if waitForBeforeUnload is specified', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); const willPreventUnload = once(w, 'will-prevent-unload'); w.close({ waitForBeforeUnload: true }); await willPreventUnload; expect(w.isDestroyed()).to.be.false(); }); it('overriding beforeunload prevention results in webcontents close', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.once('will-prevent-unload', e => e.preventDefault()); const destroyed = once(w, 'destroyed'); w.close({ waitForBeforeUnload: true }); await destroyed; expect(w.isDestroyed()).to.be.true(); }); }); describe('content-bounds-updated event', () => { afterEach(closeAllWindows); it('emits when moveTo is called', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.moveTo(100, 100)', true); const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle]; const { width, height } = w.getBounds(); expect(rect).to.deep.equal({ x: 100, y: 100, width, height }); await new Promise(setImmediate); expect(w.getBounds().x).to.equal(100); expect(w.getBounds().y).to.equal(100); }); it('emits when resizeTo is called', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.resizeTo(100, 100)', true); const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle]; const { x, y } = w.getBounds(); expect(rect).to.deep.equal({ x, y, width: 100, height: 100 }); await new Promise(setImmediate); expect({ width: w.getBounds().width, height: w.getBounds().height }).to.deep.equal(process.platform === 'win32' ? { // The width is reported as being larger on Windows? I'm not sure why // this is. width: 136, height: 100 } : { width: 100, height: 100 }); }); it('does not change window bounds if cancelled', async () => { const w = new BrowserWindow({ show: false }); const { width, height } = w.getBounds(); w.loadURL('about:blank'); w.webContents.once('content-bounds-updated', e => e.preventDefault()); await w.webContents.executeJavaScript('window.resizeTo(100, 100)', true); await new Promise(setImmediate); expect(w.getBounds().width).to.equal(width); expect(w.getBounds().height).to.equal(height); }); }); });
closed
electron/electron
https://github.com/electron/electron
40,660
[Bug]: Can not open devtools after closing
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 28.0.0-beta.10 ### What operating system are you using? Windows ### Operating System Version 10.0.19042 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Devtools should open ### Actual Behavior After opening devtools and closing them, it is not possible to reopen the devtools ### Testcase Gist URL https://gist.github.com/t57ser/9ca91183cb53fd45eb6c73c42f92903e ### Additional Information _No response_
https://github.com/electron/electron/issues/40660
https://github.com/electron/electron/pull/40666
344b7f0d068ae7d20fdebafc2ebadcdc0b4f7f68
3609fc7402881b1d51f6c56249506d5dd3fcbe93
2023-11-30T12:43:35Z
c++
2023-12-01T19:37:52Z
shell/browser/ui/inspectable_web_contents.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "shell/browser/ui/inspectable_web_contents.h" #include <memory> #include <utility> #include "base/base64.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/json/string_escape.h" #include "base/memory/raw_ptr.h" #include "base/metrics/histogram.h" #include "base/stl_util.h" #include "base/strings/pattern.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/uuid.h" #include "base/values.h" #include "chrome/browser/devtools/devtools_contents_resizing_strategy.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/file_url_loader.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/user_agent.h" #include "ipc/ipc_channel.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" #include "services/network/public/cpp/simple_url_loader.h" #include "services/network/public/cpp/simple_url_loader_stream_consumer.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_window_views.h" #include "shell/browser/net/asar/asar_url_loader_factory.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/ui/inspectable_web_contents_delegate.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/inspectable_web_contents_view_delegate.h" #include "shell/common/application_info.h" #include "shell/common/platform_util.h" #include "third_party/blink/public/common/logging/logging_utils.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "v8/include/v8.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "chrome/common/extensions/chrome_manifest_url_handlers.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/render_process_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/permissions/permissions_data.h" #include "shell/browser/electron_browser_context.h" #endif namespace electron { namespace { const double kPresetZoomFactors[] = {0.25, 0.333, 0.5, 0.666, 0.75, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0}; const char kChromeUIDevToolsURL[] = "devtools://devtools/bundled/devtools_app.html?" "remoteBase=%s&" "can_dock=%s&" "toolbarColor=rgba(223,223,223,1)&" "textColor=rgba(0,0,0,1)&" "experiments=true"; const char kChromeUIDevToolsRemoteFrontendBase[] = "https://chrome-devtools-frontend.appspot.com/"; const char kChromeUIDevToolsRemoteFrontendPath[] = "serve_file"; const char kDevToolsBoundsPref[] = "electron.devtools.bounds"; const char kDevToolsZoomPref[] = "electron.devtools.zoom"; const char kDevToolsPreferences[] = "electron.devtools.preferences"; const char kFrontendHostId[] = "id"; const char kFrontendHostMethod[] = "method"; const char kFrontendHostParams[] = "params"; const char kTitleFormat[] = "Developer Tools - %s"; const size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4; base::Value::Dict RectToDictionary(const gfx::Rect& bounds) { return base::Value::Dict{} .Set("x", bounds.x()) .Set("y", bounds.y()) .Set("width", bounds.width()) .Set("height", bounds.height()); } gfx::Rect DictionaryToRect(const base::Value::Dict& dict) { const base::Value* found = dict.Find("x"); int x = found ? found->GetInt() : 0; found = dict.Find("y"); int y = found ? found->GetInt() : 0; found = dict.Find("width"); int width = found ? found->GetInt() : 800; found = dict.Find("height"); int height = found ? found->GetInt() : 600; return gfx::Rect(x, y, width, height); } bool IsPointInRect(const gfx::Point& point, const gfx::Rect& rect) { return point.x() > rect.x() && point.x() < (rect.width() + rect.x()) && point.y() > rect.y() && point.y() < (rect.height() + rect.y()); } bool IsPointInScreen(const gfx::Point& point) { for (const auto& display : display::Screen::GetScreen()->GetAllDisplays()) { if (IsPointInRect(point, display.bounds())) return true; } return false; } void SetZoomLevelForWebContents(content::WebContents* web_contents, double level) { content::HostZoomMap::SetZoomLevel(web_contents, level); } double GetNextZoomLevel(double level, bool out) { double factor = blink::PageZoomLevelToZoomFactor(level); size_t size = std::size(kPresetZoomFactors); for (size_t i = 0; i < size; ++i) { if (!blink::PageZoomValuesEqual(kPresetZoomFactors[i], factor)) continue; if (out && i > 0) return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i - 1]); if (!out && i != size - 1) return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i + 1]); } return level; } GURL GetRemoteBaseURL() { return GURL(base::StringPrintf("%s%s/%s/", kChromeUIDevToolsRemoteFrontendBase, kChromeUIDevToolsRemoteFrontendPath, content::GetChromiumGitRevision().c_str())); } GURL GetDevToolsURL(bool can_dock) { auto url_string = base::StringPrintf(kChromeUIDevToolsURL, GetRemoteBaseURL().spec().c_str(), can_dock ? "true" : ""); return GURL(url_string); } void OnOpenItemComplete(const base::FilePath& path, const std::string& result) { platform_util::ShowItemInFolder(path); } constexpr base::TimeDelta kInitialBackoffDelay = base::Milliseconds(250); constexpr base::TimeDelta kMaxBackoffDelay = base::Seconds(10); } // namespace class InspectableWebContents::NetworkResourceLoader : public network::SimpleURLLoaderStreamConsumer { public: class URLLoaderFactoryHolder { public: network::mojom::URLLoaderFactory* get() { return ptr_.get() ? ptr_.get() : refptr_.get(); } void operator=(std::unique_ptr<network::mojom::URLLoaderFactory>&& ptr) { ptr_ = std::move(ptr); } void operator=(scoped_refptr<network::SharedURLLoaderFactory>&& refptr) { refptr_ = std::move(refptr); } private: std::unique_ptr<network::mojom::URLLoaderFactory> ptr_; scoped_refptr<network::SharedURLLoaderFactory> refptr_; }; static void Create(int stream_id, InspectableWebContents* bindings, const network::ResourceRequest& resource_request, const net::NetworkTrafficAnnotationTag& traffic_annotation, URLLoaderFactoryHolder url_loader_factory, DispatchCallback callback, base::TimeDelta retry_delay = base::TimeDelta()) { auto resource_loader = std::make_unique<InspectableWebContents::NetworkResourceLoader>( stream_id, bindings, resource_request, traffic_annotation, std::move(url_loader_factory), std::move(callback), retry_delay); bindings->loaders_.insert(std::move(resource_loader)); } NetworkResourceLoader( int stream_id, InspectableWebContents* bindings, const network::ResourceRequest& resource_request, const net::NetworkTrafficAnnotationTag& traffic_annotation, URLLoaderFactoryHolder url_loader_factory, DispatchCallback callback, base::TimeDelta delay) : stream_id_(stream_id), bindings_(bindings), resource_request_(resource_request), traffic_annotation_(traffic_annotation), loader_(network::SimpleURLLoader::Create( std::make_unique<network::ResourceRequest>(resource_request), traffic_annotation)), url_loader_factory_(std::move(url_loader_factory)), callback_(std::move(callback)), retry_delay_(delay) { loader_->SetOnResponseStartedCallback(base::BindOnce( &NetworkResourceLoader::OnResponseStarted, base::Unretained(this))); timer_.Start(FROM_HERE, delay, base::BindRepeating(&NetworkResourceLoader::DownloadAsStream, base::Unretained(this))); } NetworkResourceLoader(const NetworkResourceLoader&) = delete; NetworkResourceLoader& operator=(const NetworkResourceLoader&) = delete; private: void DownloadAsStream() { loader_->DownloadAsStream(url_loader_factory_.get(), this); } base::TimeDelta GetNextExponentialBackoffDelay(const base::TimeDelta& delta) { if (delta.is_zero()) { return kInitialBackoffDelay; } else { return delta * 1.3; } } void OnResponseStarted(const GURL& final_url, const network::mojom::URLResponseHead& response_head) { response_headers_ = response_head.headers; } void OnDataReceived(base::StringPiece chunk, base::OnceClosure resume) override { base::Value chunkValue; bool encoded = !base::IsStringUTF8(chunk); if (encoded) { std::string encoded_string; base::Base64Encode(chunk, &encoded_string); chunkValue = base::Value(std::move(encoded_string)); } else { chunkValue = base::Value(chunk); } base::Value id(stream_id_); base::Value encodedValue(encoded); bindings_->CallClientFunction("DevToolsAPI", "streamWrite", std::move(id), std::move(chunkValue), std::move(encodedValue)); std::move(resume).Run(); } void OnComplete(bool success) override { if (!success && loader_->NetError() == net::ERR_INSUFFICIENT_RESOURCES && retry_delay_ < kMaxBackoffDelay) { const base::TimeDelta delay = GetNextExponentialBackoffDelay(retry_delay_); LOG(WARNING) << "InspectableWebContents::NetworkResourceLoader id = " << stream_id_ << " failed with insufficient resources, retrying in " << delay << "." << std::endl; NetworkResourceLoader::Create( stream_id_, bindings_, resource_request_, traffic_annotation_, std::move(url_loader_factory_), std::move(callback_), delay); } else { base::Value response(base::Value::Type::DICT); response.GetDict().Set( "statusCode", response_headers_ ? response_headers_->response_code() : net::HTTP_OK); base::Value::Dict headers; size_t iterator = 0; std::string name; std::string value; while (response_headers_ && response_headers_->EnumerateHeaderLines(&iterator, &name, &value)) headers.Set(name, value); response.GetDict().Set("headers", std::move(headers)); std::move(callback_).Run(&response); } bindings_->loaders_.erase(bindings_->loaders_.find(this)); } void OnRetry(base::OnceClosure start_retry) override {} const int stream_id_; raw_ptr<InspectableWebContents> const bindings_; const network::ResourceRequest resource_request_; const net::NetworkTrafficAnnotationTag traffic_annotation_; std::unique_ptr<network::SimpleURLLoader> loader_; URLLoaderFactoryHolder url_loader_factory_; DispatchCallback callback_; scoped_refptr<net::HttpResponseHeaders> response_headers_; base::OneShotTimer timer_; base::TimeDelta retry_delay_; }; // Implemented separately on each platform. InspectableWebContentsView* CreateInspectableContentsView( InspectableWebContents* inspectable_web_contents); // static // static void InspectableWebContents::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterDictionaryPref(kDevToolsBoundsPref, RectToDictionary(gfx::Rect{0, 0, 800, 600})); registry->RegisterDoublePref(kDevToolsZoomPref, 0.); registry->RegisterDictionaryPref(kDevToolsPreferences); } InspectableWebContents::InspectableWebContents( std::unique_ptr<content::WebContents> web_contents, PrefService* pref_service, bool is_guest) : pref_service_(pref_service), web_contents_(std::move(web_contents)), is_guest_(is_guest), view_(CreateInspectableContentsView(this)) { const base::Value* bounds_dict = &pref_service_->GetValue(kDevToolsBoundsPref); if (bounds_dict->is_dict()) { devtools_bounds_ = DictionaryToRect(bounds_dict->GetDict()); // Sometimes the devtools window is out of screen or has too small size. if (devtools_bounds_.height() < 100 || devtools_bounds_.width() < 100) { devtools_bounds_.set_height(600); devtools_bounds_.set_width(800); } if (!IsPointInScreen(devtools_bounds_.origin())) { gfx::Rect display; if (!is_guest && web_contents_->GetNativeView()) { display = display::Screen::GetScreen() ->GetDisplayNearestView(web_contents_->GetNativeView()) .bounds(); } else { display = display::Screen::GetScreen()->GetPrimaryDisplay().bounds(); } devtools_bounds_.set_x(display.x() + (display.width() - devtools_bounds_.width()) / 2); devtools_bounds_.set_y( display.y() + (display.height() - devtools_bounds_.height()) / 2); } } } InspectableWebContents::~InspectableWebContents() { // Unsubscribe from devtools and Clean up resources. if (GetDevToolsWebContents()) WebContentsDestroyed(); // Let destructor destroy managed_devtools_web_contents_. } InspectableWebContentsView* InspectableWebContents::GetView() const { return view_.get(); } content::WebContents* InspectableWebContents::GetWebContents() const { return web_contents_.get(); } content::WebContents* InspectableWebContents::GetDevToolsWebContents() const { if (external_devtools_web_contents_) return external_devtools_web_contents_; else return managed_devtools_web_contents_.get(); } void InspectableWebContents::InspectElement(int x, int y) { if (agent_host_) agent_host_->InspectElement(web_contents_->GetPrimaryMainFrame(), x, y); } void InspectableWebContents::SetDelegate( InspectableWebContentsDelegate* delegate) { delegate_ = delegate; } InspectableWebContentsDelegate* InspectableWebContents::GetDelegate() const { return delegate_; } bool InspectableWebContents::IsGuest() const { return is_guest_; } void InspectableWebContents::ReleaseWebContents() { web_contents_.release(); WebContentsDestroyed(); view_.reset(); } void InspectableWebContents::SetDockState(const std::string& state) { if (state == "detach") { can_dock_ = false; } else { can_dock_ = true; dock_state_ = state; } } void InspectableWebContents::SetDevToolsTitle(const std::u16string& title) { devtools_title_ = title; view_->SetTitle(devtools_title_); } void InspectableWebContents::SetDevToolsWebContents( content::WebContents* devtools) { if (!managed_devtools_web_contents_) external_devtools_web_contents_ = devtools; } void InspectableWebContents::ShowDevTools(bool activate) { if (embedder_message_dispatcher_) { if (managed_devtools_web_contents_) view_->ShowDevTools(activate); return; } activate_ = activate; // Show devtools only after it has done loading, this is to make sure the // SetIsDocked is called *BEFORE* ShowDevTools. embedder_message_dispatcher_ = DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this); if (!external_devtools_web_contents_) { // no external devtools managed_devtools_web_contents_ = content::WebContents::Create( content::WebContents::CreateParams(web_contents_->GetBrowserContext())); managed_devtools_web_contents_->SetDelegate(this); v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); api::WebContents::FromOrCreate(isolate, managed_devtools_web_contents_.get()); } Observe(GetDevToolsWebContents()); AttachTo(content::DevToolsAgentHost::GetOrCreateFor(web_contents_.get())); GetDevToolsWebContents()->GetController().LoadURL( GetDevToolsURL(can_dock_), content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); } void InspectableWebContents::CloseDevTools() { if (GetDevToolsWebContents()) { frontend_loaded_ = false; if (managed_devtools_web_contents_) { view_->CloseDevTools(); managed_devtools_web_contents_.reset(); } embedder_message_dispatcher_.reset(); if (!IsGuest()) web_contents_->Focus(); } } bool InspectableWebContents::IsDevToolsViewShowing() { return managed_devtools_web_contents_ && view_->IsDevToolsViewShowing(); } std::u16string InspectableWebContents::GetDevToolsTitle() { return view_->GetTitle(); } void InspectableWebContents::AttachTo( scoped_refptr<content::DevToolsAgentHost> host) { Detach(); agent_host_ = std::move(host); // We could use ForceAttachClient here if problem arises with // devtools multiple session support. agent_host_->AttachClient(this); } void InspectableWebContents::Detach() { if (agent_host_) agent_host_->DetachClient(this); agent_host_ = nullptr; } void InspectableWebContents::Reattach(DispatchCallback callback) { if (agent_host_) { agent_host_->DetachClient(this); agent_host_->AttachClient(this); } std::move(callback).Run(nullptr); } void InspectableWebContents::CallClientFunction( const std::string& object_name, const std::string& method_name, base::Value arg1, base::Value arg2, base::Value arg3, base::OnceCallback<void(base::Value)> cb) { if (!GetDevToolsWebContents()) return; base::Value::List arguments; if (!arg1.is_none()) { arguments.Append(std::move(arg1)); if (!arg2.is_none()) { arguments.Append(std::move(arg2)); if (!arg3.is_none()) { arguments.Append(std::move(arg3)); } } } GetDevToolsWebContents()->GetPrimaryMainFrame()->ExecuteJavaScriptMethod( base::ASCIIToUTF16(object_name), base::ASCIIToUTF16(method_name), std::move(arguments), std::move(cb)); } gfx::Rect InspectableWebContents::GetDevToolsBounds() const { return devtools_bounds_; } void InspectableWebContents::SaveDevToolsBounds(const gfx::Rect& bounds) { pref_service_->Set(kDevToolsBoundsPref, base::Value{RectToDictionary(bounds)}); devtools_bounds_ = bounds; } double InspectableWebContents::GetDevToolsZoomLevel() const { return pref_service_->GetDouble(kDevToolsZoomPref); } void InspectableWebContents::UpdateDevToolsZoomLevel(double level) { pref_service_->SetDouble(kDevToolsZoomPref, level); } void InspectableWebContents::ActivateWindow() { // Set the zoom level. SetZoomLevelForWebContents(GetDevToolsWebContents(), GetDevToolsZoomLevel()); } void InspectableWebContents::CloseWindow() { GetDevToolsWebContents()->DispatchBeforeUnload(false /* auto_cancel */); } void InspectableWebContents::LoadCompleted() { frontend_loaded_ = true; if (managed_devtools_web_contents_) view_->ShowDevTools(activate_); // If the devtools can dock, "SetIsDocked" will be called by devtools itself. if (!can_dock_) { SetIsDocked(DispatchCallback(), false); if (!devtools_title_.empty()) { view_->SetTitle(devtools_title_); } } else { if (dock_state_.empty()) { const base::Value::Dict& prefs = pref_service_->GetDict(kDevToolsPreferences); const std::string* current_dock_state = prefs.FindString("currentDockState"); base::RemoveChars(*current_dock_state, "\"", &dock_state_); } #if BUILDFLAG(IS_WIN) auto* api_web_contents = api::WebContents::From(GetWebContents()); if (api_web_contents) { auto* win = static_cast<NativeWindowViews*>(api_web_contents->owner_window()); // When WCO is enabled, undock the devtools if the current dock // position overlaps with the position of window controls to avoid // broken layout. if (win && win->IsWindowControlsOverlayEnabled()) { if (IsAppRTL() && dock_state_ == "left") { dock_state_ = "undocked"; } else if (dock_state_ == "right") { dock_state_ = "undocked"; } } } #endif std::u16string javascript = base::UTF8ToUTF16( "EUI.DockController.DockController.instance().setDockSide(\"" + dock_state_ + "\");"); GetDevToolsWebContents()->GetPrimaryMainFrame()->ExecuteJavaScript( javascript, base::NullCallback()); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) AddDevToolsExtensionsToClient(); #endif if (view_->GetDelegate()) view_->GetDelegate()->DevToolsOpened(); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void InspectableWebContents::AddDevToolsExtensionsToClient() { // get main browser context auto* browser_context = web_contents_->GetBrowserContext(); const extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); if (!registry) return; base::Value::List results; for (auto& extension : registry->enabled_extensions()) { auto devtools_page_url = extensions::chrome_manifest_urls::GetDevToolsPage(extension.get()); if (devtools_page_url.is_empty()) continue; // Each devtools extension will need to be able to run in the devtools // process. Grant the devtools process the ability to request URLs from the // extension. content::ChildProcessSecurityPolicy::GetInstance()->GrantRequestOrigin( web_contents_->GetPrimaryMainFrame()->GetProcess()->GetID(), url::Origin::Create(extension->url())); base::Value::Dict extension_info; extension_info.Set("startPage", devtools_page_url.spec()); extension_info.Set("name", extension->name()); extension_info.Set("exposeExperimentalAPIs", extension->permissions_data()->HasAPIPermission( extensions::mojom::APIPermissionID::kExperimental)); extension_info.Set("allowFileAccess", (extension->creation_flags() & extensions::Extension::ALLOW_FILE_ACCESS) != 0); results.Append(std::move(extension_info)); } CallClientFunction("DevToolsAPI", "addExtensions", base::Value(std::move(results))); } #endif void InspectableWebContents::SetInspectedPageBounds(const gfx::Rect& rect) { if (managed_devtools_web_contents_) view_->SetContentsResizingStrategy(DevToolsContentsResizingStrategy{rect}); } void InspectableWebContents::InspectElementCompleted() {} void InspectableWebContents::InspectedURLChanged(const std::string& url) { if (managed_devtools_web_contents_) { if (devtools_title_.empty()) { view_->SetTitle( base::UTF8ToUTF16(base::StringPrintf(kTitleFormat, url.c_str()))); } } } void InspectableWebContents::LoadNetworkResource(DispatchCallback callback, const std::string& url, const std::string& headers, int stream_id) { GURL gurl(url); if (!gurl.is_valid()) { base::Value response(base::Value::Type::DICT); response.GetDict().Set("statusCode", net::HTTP_NOT_FOUND); std::move(callback).Run(&response); return; } // Create traffic annotation tag. net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("devtools_network_resource", R"( semantics { sender: "Developer Tools" description: "When user opens Developer Tools, the browser may fetch additional " "resources from the network to enrich the debugging experience " "(e.g. source map resources)." trigger: "User opens Developer Tools to debug a web page." data: "Any resources requested by Developer Tools." destination: WEBSITE } policy { cookies_allowed: YES cookies_store: "user" setting: "It's not possible to disable this feature from settings." })"); network::ResourceRequest resource_request; resource_request.url = gurl; resource_request.site_for_cookies = net::SiteForCookies::FromUrl(gurl); resource_request.headers.AddHeadersFromString(headers); auto* protocol_registry = ProtocolRegistry::FromBrowserContext( GetDevToolsWebContents()->GetBrowserContext()); NetworkResourceLoader::URLLoaderFactoryHolder url_loader_factory; if (gurl.SchemeIsFile()) { mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = AsarURLLoaderFactory::Create(); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else if (protocol_registry->IsProtocolRegistered(gurl.scheme())) { auto& protocol_handler = protocol_registry->handlers().at(gurl.scheme()); mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = ElectronURLLoaderFactory::Create(protocol_handler.first, protocol_handler.second); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else { auto* partition = GetDevToolsWebContents() ->GetBrowserContext() ->GetDefaultStoragePartition(); url_loader_factory = partition->GetURLLoaderFactoryForBrowserProcess(); } NetworkResourceLoader::Create( stream_id, this, resource_request, traffic_annotation, std::move(url_loader_factory), std::move(callback)); } void InspectableWebContents::SetIsDocked(DispatchCallback callback, bool docked) { if (managed_devtools_web_contents_) view_->SetIsDocked(docked, activate_); if (!callback.is_null()) std::move(callback).Run(nullptr); } void InspectableWebContents::OpenInNewTab(const std::string& url) { if (delegate_) delegate_->DevToolsOpenInNewTab(url); } void InspectableWebContents::ShowItemInFolder( const std::string& file_system_path) { if (file_system_path.empty()) return; base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path); platform_util::OpenPath(path.DirName(), base::BindOnce(&OnOpenItemComplete, path)); } void InspectableWebContents::SaveToFile(const std::string& url, const std::string& content, bool save_as) { if (delegate_) delegate_->DevToolsSaveToFile(url, content, save_as); } void InspectableWebContents::AppendToFile(const std::string& url, const std::string& content) { if (delegate_) delegate_->DevToolsAppendToFile(url, content); } void InspectableWebContents::RequestFileSystems() { if (delegate_) delegate_->DevToolsRequestFileSystems(); } void InspectableWebContents::AddFileSystem(const std::string& type) { if (delegate_) delegate_->DevToolsAddFileSystem(type, base::FilePath()); } void InspectableWebContents::RemoveFileSystem( const std::string& file_system_path) { if (delegate_) delegate_->DevToolsRemoveFileSystem( base::FilePath::FromUTF8Unsafe(file_system_path)); } void InspectableWebContents::UpgradeDraggedFileSystemPermissions( const std::string& file_system_url) {} void InspectableWebContents::IndexPath(int request_id, const std::string& file_system_path, const std::string& excluded_folders) { if (delegate_) delegate_->DevToolsIndexPath(request_id, file_system_path, excluded_folders); } void InspectableWebContents::StopIndexing(int request_id) { if (delegate_) delegate_->DevToolsStopIndexing(request_id); } void InspectableWebContents::SearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (delegate_) delegate_->DevToolsSearchInPath(request_id, file_system_path, query); } void InspectableWebContents::SetWhitelistedShortcuts( const std::string& message) {} void InspectableWebContents::SetEyeDropperActive(bool active) { if (delegate_) delegate_->DevToolsSetEyeDropperActive(active); } void InspectableWebContents::ShowCertificateViewer( const std::string& cert_chain) {} void InspectableWebContents::ZoomIn() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), false); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); UpdateDevToolsZoomLevel(new_level); } void InspectableWebContents::ZoomOut() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), true); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); UpdateDevToolsZoomLevel(new_level); } void InspectableWebContents::ResetZoom() { SetZoomLevelForWebContents(GetDevToolsWebContents(), 0.); UpdateDevToolsZoomLevel(0.); } void InspectableWebContents::SetDevicesDiscoveryConfig( bool discover_usb_devices, bool port_forwarding_enabled, const std::string& port_forwarding_config, bool network_discovery_enabled, const std::string& network_discovery_config) {} void InspectableWebContents::SetDevicesUpdatesEnabled(bool enabled) {} void InspectableWebContents::PerformActionOnRemotePage( const std::string& page_id, const std::string& action) {} void InspectableWebContents::OpenRemotePage(const std::string& browser_id, const std::string& url) {} void InspectableWebContents::OpenNodeFrontend() {} void InspectableWebContents::DispatchProtocolMessageFromDevToolsFrontend( const std::string& message) { // If the devtools wants to reload the page, hijack the message and handle it // to the delegate. if (base::MatchPattern(message, "{\"id\":*," "\"method\":\"Page.reload\"," "\"params\":*}")) { if (delegate_) delegate_->DevToolsReloadPage(); return; } if (agent_host_) agent_host_->DispatchProtocolMessage( this, base::as_bytes(base::make_span(message))); } void InspectableWebContents::SendJsonRequest(DispatchCallback callback, const std::string& browser_id, const std::string& url) { std::move(callback).Run(nullptr); } void InspectableWebContents::GetPreferences(DispatchCallback callback) { const base::Value& prefs = pref_service_->GetValue(kDevToolsPreferences); std::move(callback).Run(&prefs); } void InspectableWebContents::GetPreference(DispatchCallback callback, const std::string& name) { if (auto* pref = pref_service_->GetDict(kDevToolsPreferences).Find(name)) { std::move(callback).Run(pref); return; } // Pref wasn't found, return an empty value base::Value no_pref; std::move(callback).Run(&no_pref); } void InspectableWebContents::SetPreference(const std::string& name, const std::string& value) { ScopedDictPrefUpdate update(pref_service_, kDevToolsPreferences); update->Set(name, base::Value(value)); } void InspectableWebContents::RemovePreference(const std::string& name) { ScopedDictPrefUpdate update(pref_service_, kDevToolsPreferences); update->Remove(name); } void InspectableWebContents::ClearPreferences() { ScopedDictPrefUpdate unsynced_update(pref_service_, kDevToolsPreferences); unsynced_update->clear(); } void InspectableWebContents::GetSyncInformation(DispatchCallback callback) { base::Value result(base::Value::Type::DICT); result.GetDict().Set("isSyncActive", false); std::move(callback).Run(&result); } void InspectableWebContents::ConnectionReady() {} void InspectableWebContents::RegisterExtensionsAPI(const std::string& origin, const std::string& script) { extensions_api_[origin + "/"] = script; } void InspectableWebContents::HandleMessageFromDevToolsFrontend( base::Value::Dict message) { // TODO(alexeykuzmin): Should we expect it to exist? if (!embedder_message_dispatcher_) { return; } const std::string* method = message.FindString(kFrontendHostMethod); base::Value* params = message.Find(kFrontendHostParams); if (!method || (params && !params->is_list())) { LOG(ERROR) << "Invalid message was sent to embedder: " << message; return; } const base::Value::List no_params; const base::Value::List& params_list = params != nullptr && params->is_list() ? params->GetList() : no_params; const int id = message.FindInt(kFrontendHostId).value_or(0); embedder_message_dispatcher_->Dispatch( base::BindRepeating(&InspectableWebContents::SendMessageAck, weak_factory_.GetWeakPtr(), id), *method, params_list); } void InspectableWebContents::DispatchProtocolMessage( content::DevToolsAgentHost* agent_host, base::span<const uint8_t> message) { if (!frontend_loaded_) return; base::StringPiece str_message(reinterpret_cast<const char*>(message.data()), message.size()); if (str_message.length() < kMaxMessageChunkSize) { CallClientFunction("DevToolsAPI", "dispatchMessage", base::Value(std::string(str_message))); } else { size_t total_size = str_message.length(); for (size_t pos = 0; pos < str_message.length(); pos += kMaxMessageChunkSize) { base::StringPiece str_message_chunk = str_message.substr(pos, kMaxMessageChunkSize); CallClientFunction( "DevToolsAPI", "dispatchMessageChunk", base::Value(std::string(str_message_chunk)), base::Value(base::NumberToString(pos ? 0 : total_size))); } } } void InspectableWebContents::AgentHostClosed( content::DevToolsAgentHost* agent_host) {} void InspectableWebContents::RenderFrameHostChanged( content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { if (new_host->GetParent()) return; frontend_host_ = content::DevToolsFrontendHost::Create( new_host, base::BindRepeating( &InspectableWebContents::HandleMessageFromDevToolsFrontend, weak_factory_.GetWeakPtr())); } void InspectableWebContents::WebContentsDestroyed() { if (managed_devtools_web_contents_) managed_devtools_web_contents_->SetDelegate(nullptr); frontend_loaded_ = false; external_devtools_web_contents_ = nullptr; Observe(nullptr); Detach(); embedder_message_dispatcher_.reset(); if (view_ && view_->GetDelegate()) view_->GetDelegate()->DevToolsClosed(); } bool InspectableWebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { auto* delegate = web_contents_->GetDelegate(); return !delegate || delegate->HandleKeyboardEvent(source, event); } void InspectableWebContents::CloseContents(content::WebContents* source) { // This is where the devtools closes itself (by clicking the x button). CloseDevTools(); } void InspectableWebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { auto* delegate = web_contents_->GetDelegate(); if (delegate) delegate->RunFileChooser(render_frame_host, std::move(listener), params); } void InspectableWebContents::EnumerateDirectory( content::WebContents* source, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { auto* delegate = web_contents_->GetDelegate(); if (delegate) delegate->EnumerateDirectory(source, std::move(listener), path); } void InspectableWebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { #if defined(TOOLKIT_VIEWS) if (view_->GetDelegate()) view_->GetDelegate()->DevToolsFocused(); #endif } void InspectableWebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame()) { if (navigation_handle->GetRenderFrameHost() == GetDevToolsWebContents()->GetPrimaryMainFrame() && frontend_host_) { return; } frontend_host_ = content::DevToolsFrontendHost::Create( web_contents()->GetPrimaryMainFrame(), base::BindRepeating( &InspectableWebContents::HandleMessageFromDevToolsFrontend, base::Unretained(this))); return; } } void InspectableWebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame() || !navigation_handle->GetURL().SchemeIs("chrome-extension") || !navigation_handle->HasCommitted()) return; content::RenderFrameHost* frame = navigation_handle->GetRenderFrameHost(); auto origin = navigation_handle->GetURL().DeprecatedGetOriginAsURL().spec(); auto it = extensions_api_.find(origin); if (it == extensions_api_.end()) return; // Injected Script from devtools frontend doesn't expose chrome, // most likely bug in chromium. base::ReplaceFirstSubstringAfterOffset(&it->second, 0, "var chrome", "var chrome = window.chrome "); auto script = base::StringPrintf( "%s(\"%s\")", it->second.c_str(), base::Uuid::GenerateRandomV4().AsLowercaseString().c_str()); // Invoking content::DevToolsFrontendHost::SetupExtensionsAPI(frame, script); // should be enough, but it seems to be a noop currently. frame->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script), base::NullCallback()); } void InspectableWebContents::SendMessageAck(int request_id, const base::Value* arg) { if (arg) { CallClientFunction("DevToolsAPI", "embedderMessageAck", base::Value(request_id), arg->Clone()); } else { CallClientFunction("DevToolsAPI", "embedderMessageAck", base::Value(request_id)); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,660
[Bug]: Can not open devtools after closing
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 28.0.0-beta.10 ### What operating system are you using? Windows ### Operating System Version 10.0.19042 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Devtools should open ### Actual Behavior After opening devtools and closing them, it is not possible to reopen the devtools ### Testcase Gist URL https://gist.github.com/t57ser/9ca91183cb53fd45eb6c73c42f92903e ### Additional Information _No response_
https://github.com/electron/electron/issues/40660
https://github.com/electron/electron/pull/40666
344b7f0d068ae7d20fdebafc2ebadcdc0b4f7f68
3609fc7402881b1d51f6c56249506d5dd3fcbe93
2023-11-30T12:43:35Z
c++
2023-12-01T19:37:52Z
spec/api-web-contents-spec.ts
import { expect } from 'chai'; import { AddressInfo } from 'node:net'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as http from 'node:http'; import { BrowserWindow, ipcMain, webContents, session, app, BrowserView, WebContents } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import { ifdescribe, defer, waitUntil, listen, ifit } from './lib/spec-helpers'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; const pdfjs = require('pdfjs-dist'); const fixturesPath = path.resolve(__dirname, 'fixtures'); const mainFixturesPath = path.resolve(__dirname, 'fixtures'); const features = process._linkedBinding('electron_common_features'); describe('webContents module', () => { describe('getAllWebContents() API', () => { afterEach(closeAllWindows); it('returns an array of web contents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html')); await once(w.webContents, 'did-attach-webview') as [any, WebContents]; w.webContents.openDevTools(); await once(w.webContents, 'devtools-opened'); const all = webContents.getAllWebContents().sort((a, b) => { return a.id - b.id; }); expect(all).to.have.length(3); expect(all[0].getType()).to.equal('window'); expect(all[all.length - 2].getType()).to.equal('webview'); expect(all[all.length - 1].getType()).to.equal('remote'); }); }); describe('fromId()', () => { it('returns undefined for an unknown id', () => { expect(webContents.fromId(12345)).to.be.undefined(); }); }); describe('fromFrame()', () => { it('returns WebContents for mainFrame', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); expect(webContents.fromFrame(contents.mainFrame)).to.equal(contents); }); it('returns undefined for disposed frame', async () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); const { mainFrame } = contents; contents.destroy(); await waitUntil(() => typeof webContents.fromFrame(mainFrame) === 'undefined'); }); it('throws when passing invalid argument', async () => { let errored = false; try { webContents.fromFrame({} as any); } catch { errored = true; } expect(errored).to.be.true(); }); }); describe('fromDevToolsTargetId()', () => { it('returns WebContents for attached DevTools target', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); try { await w.webContents.debugger.attach('1.3'); const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo'); expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents); } finally { await w.webContents.debugger.detach(); } }); it('returns undefined for an unknown id', () => { expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined(); }); }); describe('will-prevent-unload event', function () { afterEach(closeAllWindows); it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('does not emit if beforeunload returns undefined in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); view.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits if beforeunload returns false in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, 'will-prevent-unload'); }); it('emits if beforeunload returns false in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(view.webContents, 'will-prevent-unload'); }); it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', event => event.preventDefault()); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); const wait = once(w, 'closed'); w.close(); await wait; }); }); describe('webContents.send(channel, args...)', () => { afterEach(closeAllWindows); it('throws an error when the channel is missing', () => { const w = new BrowserWindow({ show: false }); expect(() => { (w.webContents.send as any)(); }).to.throw('Missing required channel argument'); expect(() => { w.webContents.send(null as any); }).to.throw('Missing required channel argument'); }); it('does not block node async APIs when sent before document is ready', (done) => { // Please reference https://github.com/electron/electron/issues/19368 if // this test fails. ipcMain.once('async-node-api-done', () => { done(); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, sandbox: false, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html')); setTimeout(50).then(() => { w.webContents.send('test'); }); }); }); ifdescribe(features.isPrintingEnabled())('webContents.print()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('throws when invalid settings are passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print(true); }).to.throw('webContents.print(): Invalid print settings specified.'); }); it('throws when an invalid pageSize is passed', () => { const badSize = 5; expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({ pageSize: badSize }); }).to.throw(`Unsupported pageSize: ${badSize}`); }); it('throws when an invalid callback is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({}, true); }).to.throw('webContents.print(): Invalid optional callback provided.'); }); it('fails when an invalid deviceName is passed', (done) => { w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => { expect(success).to.equal(false); expect(reason).to.match(/Invalid deviceName provided/); done(); }); }); it('throws when an invalid pageSize is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {}); }).to.throw('Unsupported pageSize: i-am-a-bad-pagesize'); }); it('throws when an invalid custom pageSize is passed', () => { expect(() => { w.webContents.print({ pageSize: { width: 100, height: 200 } }); }).to.throw('height and width properties must be minimum 352 microns.'); }); it('does not crash with custom margins', () => { expect(() => { w.webContents.print({ silent: true, margins: { marginType: 'custom', top: 1, bottom: 1, left: 1, right: 1 } }); }).to.not.throw(); }); }); describe('webContents.executeJavaScript', () => { describe('in about:blank', () => { const expected = 'hello, world!'; const expectedErrorMsg = 'woops!'; const code = `(() => "${expected}")()`; const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`; const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`; const errorTypes = new Set([ Error, ReferenceError, EvalError, RangeError, SyntaxError, TypeError, URIError ]); let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } }); await w.loadURL('about:blank'); }); after(closeAllWindows); it('resolves the returned promise with the result', async () => { const result = await w.webContents.executeJavaScript(code); expect(result).to.equal(expected); }); it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => { const result = await w.webContents.executeJavaScript(asyncCode); expect(result).to.equal(expected); }); it('rejects the returned promise if an async error is thrown', async () => { await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg); }); it('rejects the returned promise with an error if an Error.prototype is thrown', async () => { for (const error of errorTypes) { await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`)) .to.eventually.be.rejectedWith(error); } }); }); describe('on a real page', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('works after page load and during subframe load', async () => { await w.loadURL(serverUrl); // initiate a sub-frame load, then try and execute script during it await w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/slow' document.body.appendChild(iframe) null // don't return the iframe `); await w.webContents.executeJavaScript('console.log(\'hello\')'); }); it('executes after page load', async () => { const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()'); w.loadURL(serverUrl); const result = await executeJavaScript; expect(result).to.equal('test'); }); }); }); describe('webContents.executeJavaScriptInIsolatedWorld', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadURL('about:blank'); }); it('resolves the returned promise with the result', async () => { await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]); const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]); const mainWorldResult = await w.webContents.executeJavaScript('window.X'); expect(isolatedResult).to.equal(123); expect(mainWorldResult).to.equal(undefined); }); }); describe('loadURL() promise API', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('resolves when done loading', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('resolves when done loading a file URL', async () => { await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled(); }); it('resolves when navigating within the page', async () => { await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await setTimeout(); await expect(w.loadURL(w.getURL() + '#foo')).to.eventually.be.fulfilled(); }); it('resolves after browser initiated navigation', async () => { let finishedLoading = false; w.webContents.on('did-finish-load', function () { finishedLoading = true; }); await w.loadFile(path.join(fixturesPath, 'pages', 'navigate_in_page_and_wait.html')); expect(finishedLoading).to.be.true(); }); it('rejects when failing to load a file URL', async () => { await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FILE_NOT_FOUND'); }); // FIXME: Temporarily disable on WOA until // https://github.com/electron/electron/issues/20008 is resolved ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('rejects when loading fails due to DNS not resolved', async () => { await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected() .and.have.property('code', 'ERR_NAME_NOT_RESOLVED'); }); it('rejects when navigation is cancelled due to a bad scheme', async () => { await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FAILED'); }); it('does not crash when loading a new URL with emulation settings set', async () => { const setEmulation = async () => { if (w.webContents) { w.webContents.debugger.attach('1.3'); const deviceMetrics = { width: 700, height: 600, deviceScaleFactor: 2, mobile: true, dontSetVisibleSize: true }; await w.webContents.debugger.sendCommand( 'Emulation.setDeviceMetricsOverride', deviceMetrics ); } }; try { await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await setEmulation(); await w.loadURL('data:text/html,<h1>HELLO</h1>'); await setEmulation(); } catch (e) { expect((e as Error).message).to.match(/Debugger is already attached to the target/); } }); it('fails if loadURL is called inside a non-reentrant critical section', (done) => { w.webContents.once('did-fail-load', (_event, _errorCode, _errorDescription, validatedURL) => { expect(validatedURL).to.contain('blank.html'); done(); }); w.webContents.once('did-start-loading', () => { w.loadURL(`file://${fixturesPath}/pages/blank.html`); }); w.loadURL('data:text/html,<h1>HELLO</h1>'); }); it('sets appropriate error information on rejection', async () => { let err: any; try { await w.loadURL('file:non-existent'); } catch (e) { err = e; } expect(err).not.to.be.null(); expect(err.code).to.eql('ERR_FILE_NOT_FOUND'); expect(err.errno).to.eql(-6); expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent'); }); it('rejects if the load is aborted', async () => { const s = http.createServer(() => { /* never complete the request */ }); const { port } = await listen(s); const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/); // load a different file before the first load completes, causing the // first load to be aborted. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await p; s.close(); }); it("doesn't reject when a subframe fails to load", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="http://err.name.not.resolved"></iframe>'); resp = res; // don't end the response yet }); const { port } = await listen(s); const p = new Promise<void>(resolve => { w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.end(); await main; s.close(); }); it("doesn't resolve when a subframe loads", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="about:blank"></iframe>'); resp = res; // don't end the response yet }); const { port } = await listen(s); const p = new Promise<void>(resolve => { w.webContents.on('did-frame-finish-load', (event, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.destroy(); // cause the main request to fail await expect(main).to.eventually.be.rejected() .and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING s.close(); }); }); describe('getFocusedWebContents() API', () => { afterEach(closeAllWindows); // FIXME ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('returns the focused web contents', async () => { const w = new BrowserWindow({ show: true }); await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id); const devToolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools(); await devToolsOpened; expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.devToolsWebContents!.id); const devToolsClosed = once(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id); }); it('does not crash when called on a detached dev tools window', async () => { const w = new BrowserWindow({ show: true }); w.webContents.openDevTools({ mode: 'detach' }); w.webContents.inspectElement(100, 100); // For some reason we have to wait for two focused events...? await once(w.webContents, 'devtools-focused'); expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); // Work around https://github.com/electron/electron/issues/19985 await setTimeout(); const devToolsClosed = once(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); }); }); describe('setDevToolsWebContents() API', () => { afterEach(closeAllWindows); it('sets arbitrary webContents as devtools', async () => { const w = new BrowserWindow({ show: false }); const devtools = new BrowserWindow({ show: false }); const promise = once(devtools.webContents, 'dom-ready'); w.webContents.setDevToolsWebContents(devtools.webContents); w.webContents.openDevTools(); await promise; expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true(); const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name'); expect(result).to.equal('InspectorFrontendHostImpl'); devtools.destroy(); }); }); describe('isFocused() API', () => { it('returns false when the window is hidden', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(w.isVisible()).to.be.false(); expect(w.webContents.isFocused()).to.be.false(); }); }); describe('isCurrentlyAudible() API', () => { afterEach(closeAllWindows); it('returns whether audio is playing', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript(` window.context = new AudioContext // Start in suspended state, because of the // new web audio api policy. context.suspend() window.oscillator = context.createOscillator() oscillator.connect(context.destination) oscillator.start() `); let p = once(w.webContents, 'audio-state-changed'); w.webContents.executeJavaScript('context.resume()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.true(); p = once(w.webContents, 'audio-state-changed'); w.webContents.executeJavaScript('oscillator.stop()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.false(); }); }); describe('openDevTools() API', () => { afterEach(closeAllWindows); it('can show window with activation', async () => { const w = new BrowserWindow({ show: false }); const focused = once(w, 'focus'); w.show(); await focused; expect(w.isFocused()).to.be.true(); const blurred = once(w, 'blur'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await Promise.all([ once(w.webContents, 'devtools-opened'), once(w.webContents, 'devtools-focused') ]); await blurred; expect(w.isFocused()).to.be.false(); }); it('can show window without activation', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); }); it('can show a DevTools window with custom title', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false, title: 'myTitle' }); await devtoolsOpened; expect(w.webContents.getDevToolsTitle()).to.equal('myTitle'); }); }); describe('setDevToolsTitle() API', () => { afterEach(closeAllWindows); it('can set devtools title with function', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); w.webContents.setDevToolsTitle('newTitle'); expect(w.webContents.getDevToolsTitle()).to.equal('newTitle'); }); }); describe('before-input-event event', () => { afterEach(closeAllWindows); it('can prevent document keyboard events', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); const keyDown = new Promise(resolve => { ipcMain.once('keydown', (event, key) => resolve(key)); }); w.webContents.once('before-input-event', (event, input) => { if (input.key === 'a') event.preventDefault(); }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' }); expect(await keyDown).to.equal('b'); }); it('has the correct properties', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testBeforeInput = async (opts: any) => { const modifiers = []; if (opts.shift) modifiers.push('shift'); if (opts.control) modifiers.push('control'); if (opts.alt) modifiers.push('alt'); if (opts.meta) modifiers.push('meta'); if (opts.isAutoRepeat) modifiers.push('isAutoRepeat'); const p = once(w.webContents, 'before-input-event') as Promise<[any, Electron.Input]>; w.webContents.sendInputEvent({ type: opts.type, keyCode: opts.keyCode, modifiers: modifiers as any }); const [, input] = await p; expect(input.type).to.equal(opts.type); expect(input.key).to.equal(opts.key); expect(input.code).to.equal(opts.code); expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat); expect(input.shift).to.equal(opts.shift); expect(input.control).to.equal(opts.control); expect(input.alt).to.equal(opts.alt); expect(input.meta).to.equal(opts.meta); }; await testBeforeInput({ type: 'keyDown', key: 'A', code: 'KeyA', keyCode: 'a', shift: true, control: true, alt: true, meta: true, isAutoRepeat: true }); await testBeforeInput({ type: 'keyUp', key: '.', code: 'Period', keyCode: '.', shift: false, control: true, alt: true, meta: false, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: '!', code: 'Digit1', keyCode: '1', shift: true, control: false, alt: false, meta: true, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: 'Tab', code: 'Tab', keyCode: 'Tab', shift: false, control: true, alt: false, meta: false, isAutoRepeat: true }); }); }); // On Mac, zooming isn't done with the mouse wheel. ifdescribe(process.platform !== 'darwin')('zoom-changed', () => { afterEach(closeAllWindows); it('is emitted with the correct zoom-in info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: 1, wheelTicksX: 0, wheelTicksY: 1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string]; expect(zoomDirection).to.equal('in'); }; await testZoomChanged(); }); it('is emitted with the correct zoom-out info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: -1, wheelTicksX: 0, wheelTicksY: -1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string]; expect(zoomDirection).to.equal('out'); }; await testZoomChanged(); }); }); describe('sendInputEvent(event)', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); }); afterEach(closeAllWindows); it('can send keydown events', async () => { const keydown = once(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send keydown events with modifiers', async () => { const keydown = once(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); it('can send keydown events with special keys', async () => { const keydown = once(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Tab'); expect(code).to.equal('Tab'); expect(keyCode).to.equal(9); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.true(); }); it('can send char events', async () => { const keypress = once(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can correctly convert accelerators to key codes', async () => { const keyup = once(ipcMain, 'keyup'); w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'keyUp' }); await keyup; const inputText = await w.webContents.executeJavaScript('document.getElementById("input").value'); expect(inputText).to.equal('+ + +'); }); it('can send char events with modifiers', async () => { const keypress = once(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); }); describe('insertCSS', () => { afterEach(closeAllWindows); it('supports inserting CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.webContents.insertCSS('body { background-repeat: round; }'); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('round'); }); it('supports removing inserted CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const key = await w.webContents.insertCSS('body { background-repeat: round; }'); await w.webContents.removeInsertedCSS(key); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('repeat'); }); }); describe('inspectElement()', () => { afterEach(closeAllWindows); it('supports inspecting an element in the devtools', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const event = once(w.webContents, 'devtools-opened'); w.webContents.inspectElement(10, 10); await event; }); }); describe('startDrag({file, icon})', () => { it('throws errors for a missing file or a missing/empty icon', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any); }).to.throw('Must specify either \'file\' or \'files\' option'); expect(() => { w.webContents.startDrag({ file: __filename } as any); }).to.throw('\'icon\' parameter is required'); expect(() => { w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') }); }).to.throw(/Failed to load image from path (.+)/); }); }); describe('focus APIs', () => { describe('focus()', () => { afterEach(closeAllWindows); it('does not blur the focused window when the web contents is hidden', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.show(); await w.loadURL('about:blank'); w.focus(); const child = new BrowserWindow({ show: false }); child.loadURL('about:blank'); child.webContents.focus(); const currentFocused = w.isFocused(); const childFocused = child.isFocused(); child.close(); expect(currentFocused).to.be.true(); expect(childFocused).to.be.false(); }); }); const moveFocusToDevTools = async (win: BrowserWindow) => { const devToolsOpened = once(win.webContents, 'devtools-opened'); win.webContents.openDevTools({ mode: 'right' }); await devToolsOpened; win.webContents.devToolsWebContents!.focus(); }; describe('focus event', () => { afterEach(closeAllWindows); it('is triggered when web contents is focused', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await moveFocusToDevTools(w); const focusPromise = once(w.webContents, 'focus'); w.webContents.focus(); await expect(focusPromise).to.eventually.be.fulfilled(); }); }); describe('blur event', () => { afterEach(closeAllWindows); it('is triggered when web contents is blurred', async () => { const w = new BrowserWindow({ show: true }); await w.loadURL('about:blank'); w.webContents.focus(); const blurPromise = once(w.webContents, 'blur'); await moveFocusToDevTools(w); await expect(blurPromise).to.eventually.be.fulfilled(); }); }); }); describe('getOSProcessId()', () => { afterEach(closeAllWindows); it('returns a valid process id', async () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getOSProcessId()).to.equal(0); await w.loadURL('about:blank'); expect(w.webContents.getOSProcessId()).to.be.above(0); }); }); describe('getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns a valid stream id', () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty(); }); }); describe('userAgent APIs', () => { it('is not empty by default', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); expect(userAgent).to.be.a('string').that.is.not.empty(); }); it('can set the user agent (functions)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); w.webContents.setUserAgent('my-user-agent'); expect(w.webContents.getUserAgent()).to.equal('my-user-agent'); w.webContents.setUserAgent(userAgent); expect(w.webContents.getUserAgent()).to.equal(userAgent); }); it('can set the user agent (properties)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.userAgent; w.webContents.userAgent = 'my-user-agent'; expect(w.webContents.userAgent).to.equal('my-user-agent'); w.webContents.userAgent = userAgent; expect(w.webContents.userAgent).to.equal(userAgent); }); }); describe('audioMuted APIs', () => { it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.setAudioMuted(true); expect(w.webContents.isAudioMuted()).to.be.true(); w.webContents.setAudioMuted(false); expect(w.webContents.isAudioMuted()).to.be.false(); }); it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.audioMuted = true; expect(w.webContents.audioMuted).to.be.true(); w.webContents.audioMuted = false; expect(w.webContents.audioMuted).to.be.false(); }); }); describe('zoom api', () => { const hostZoomMap: Record<string, number> = { host1: 0.3, host2: 0.7, host3: 0.2 }; before(() => { const protocol = session.defaultSession.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { const response = `<script> const {ipcRenderer} = require('electron') ipcRenderer.send('set-zoom', window.location.hostname) ipcRenderer.on(window.location.hostname + '-zoom-set', () => { ipcRenderer.send(window.location.hostname + '-zoom-level') }) </script>`; callback({ data: response, mimeType: 'text/html' }); }); }); after(() => { const protocol = session.defaultSession.protocol; protocol.unregisterProtocol(standardScheme); }); afterEach(closeAllWindows); it('throws on an invalid zoomFactor', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { w.webContents.setZoomFactor(0.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); expect(() => { w.webContents.setZoomFactor(-2.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); }); it('can set the correct zoom level (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.getZoomLevel(); expect(zoomLevel).to.eql(0.0); w.webContents.setZoomLevel(0.5); const newZoomLevel = w.webContents.getZoomLevel(); expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.setZoomLevel(0); } }); it('can set the correct zoom level (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.eql(0.0); w.webContents.zoomLevel = 0.5; const newZoomLevel = w.webContents.zoomLevel; expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.zoomLevel = 0; } }); it('can set the correct zoom factor (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.getZoomFactor(); expect(zoomFactor).to.eql(1.0); w.webContents.setZoomFactor(0.5); const newZoomFactor = w.webContents.getZoomFactor(); expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.setZoomFactor(1.0); } }); it('can set the correct zoom factor (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.zoomFactor; expect(zoomFactor).to.eql(1.0); w.webContents.zoomFactor = 0.5; const newZoomFactor = w.webContents.zoomFactor; expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.zoomFactor = 1.0; } }); it('can persist zoom level across navigation', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let finalNavigation = false; ipcMain.on('set-zoom', (e, host) => { const zoomLevel = hostZoomMap[host]; if (!finalNavigation) w.webContents.zoomLevel = zoomLevel; e.sender.send(`${host}-zoom-set`); }); ipcMain.on('host1-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host1; expect(zoomLevel).to.equal(expectedZoomLevel); if (finalNavigation) { done(); } else { w.loadURL(`${standardScheme}://host2`); } } catch (e) { done(e); } }); ipcMain.once('host2-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host2; expect(zoomLevel).to.equal(expectedZoomLevel); finalNavigation = true; w.webContents.goBack(); } catch (e) { done(e); } }); w.loadURL(`${standardScheme}://host1`); }); it('can propagate zoom level across same session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false }); defer(() => { w2.setClosable(true); w2.close(); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel1).to.equal(zoomLevel2); }); it('cannot propagate zoom level across different session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false, webPreferences: { partition: 'temp' } }); const protocol = w2.webContents.session.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { callback('hello'); }); defer(() => { w2.setClosable(true); w2.close(); protocol.unregisterProtocol(standardScheme); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); it('can persist when it contains iframe', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { setTimeout(200).then(() => { res.end(); }); }); listen(server).then(({ url }) => { const content = `<iframe src=${url}></iframe>`; w.webContents.on('did-frame-finish-load', (e, isMainFrame) => { if (!isMainFrame) { try { const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(2.0); w.webContents.zoomLevel = 0; done(); } catch (e) { done(e); } finally { server.close(); } } }); w.webContents.on('dom-ready', () => { w.webContents.zoomLevel = 2.0; }); w.loadURL(`data:text/html,${content}`); }); }); it('cannot propagate when used with webframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const w2 = new BrowserWindow({ show: false }); const temporaryZoomSet = once(ipcMain, 'temporary-zoom-set'); w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html')); await temporaryZoomSet; const finalZoomLevel = w.webContents.getZoomLevel(); await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html')); const zoomLevel1 = w.webContents.zoomLevel; const zoomLevel2 = w2.webContents.zoomLevel; w2.setClosable(true); w2.close(); expect(zoomLevel1).to.equal(finalZoomLevel); expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); describe('with unique domains', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before(async () => { server = http.createServer((req, res) => { setTimeout().then(() => res.end('hey')); }); serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); after(() => { server.close(); }); it('cannot persist zoom level after navigation with webFrame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const source = ` const {ipcRenderer, webFrame} = require('electron') webFrame.setZoomLevel(0.6) ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel()) `; const zoomLevelPromise = once(ipcMain, 'zoom-level-set'); await w.loadURL(serverUrl); await w.webContents.executeJavaScript(source); let [, zoomLevel] = await zoomLevelPromise; expect(zoomLevel).to.equal(0.6); const loadPromise = once(w.webContents, 'did-finish-load'); await w.loadURL(crossSiteUrl); await loadPromise; zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(0); }); }); }); describe('webrtc ip policy api', () => { afterEach(closeAllWindows); it('can set and get webrtc ip policies', () => { const w = new BrowserWindow({ show: false }); const policies = [ 'default', 'default_public_interface_only', 'default_public_and_private_interfaces', 'disable_non_proxied_udp' ] as const; for (const policy of policies) { w.webContents.setWebRTCIPHandlingPolicy(policy); expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy); } }); }); describe('webrtc udp port range policy api', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('check default webrtc udp port range is { min: 0, max: 0 }', () => { const settings = w.webContents.getWebRTCUDPPortRange(); expect(settings).to.deep.equal({ min: 0, max: 0 }); }); it('can set and get webrtc udp port range policy with correct arguments', () => { w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 }); const settings = w.webContents.getWebRTCUDPPortRange(); expect(settings).to.deep.equal({ min: 1, max: 65535 }); }); it('can not set webrtc udp port range policy with invalid arguments', () => { expect(() => { w.webContents.setWebRTCUDPPortRange({ min: 0, max: 65535 }); }).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]"); expect(() => { w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65536 }); }).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]"); expect(() => { w.webContents.setWebRTCUDPPortRange({ min: 60000, max: 56789 }); }).to.throw("'max' must be greater than or equal to 'min'"); }); it('can reset webrtc udp port range policy to default with { min: 0, max: 0 }', () => { w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 }); const settings = w.webContents.getWebRTCUDPPortRange(); expect(settings).to.deep.equal({ min: 1, max: 65535 }); w.webContents.setWebRTCUDPPortRange({ min: 0, max: 0 }); const defaultSetting = w.webContents.getWebRTCUDPPortRange(); expect(defaultSetting).to.deep.equal({ min: 0, max: 0 }); }); }); describe('opener api', () => { afterEach(closeAllWindows); it('can get opener with window.open()', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>; w.webContents.executeJavaScript('window.open("about:blank")', true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame); }); it('has no opener when using "noopener"', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>; w.webContents.executeJavaScript('window.open("about:blank", undefined, "noopener")', true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.be.null(); }); it('can get opener with a[target=_blank][rel=opener]', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>; w.webContents.executeJavaScript(`(function() { const a = document.createElement('a'); a.target = '_blank'; a.rel = 'opener'; a.href = 'about:blank'; a.click(); }())`, true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame); }); it('has no opener with a[target=_blank][rel=noopener]', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>; w.webContents.executeJavaScript(`(function() { const a = document.createElement('a'); a.target = '_blank'; a.rel = 'noopener'; a.href = 'about:blank'; a.click(); }())`, true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.be.null(); }); }); describe('render view deleted events', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before(async () => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${crossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else if (req.url === '/first-window-open') { res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`); } else if (req.url === '/second-window-open') { res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>'); } else { res.end(); } }; setTimeout().then(respond); }); serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); after(() => { server.close(); }); afterEach(closeAllWindows); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); w.webContents.on('did-finish-load', () => { w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted'); }); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const parentWindow = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; let childWindow: BrowserWindow | null = null; const destroyed = once(parentWindow.webContents, 'destroyed'); const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; const childWindowCreated = new Promise<void>((resolve) => { app.once('browser-window-created', (event, window) => { childWindow = window; window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); resolve(); }); }); parentWindow.loadURL(`${serverUrl}/first-window-open`); await childWindowCreated; childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); parentWindow.close(); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed'); }); it('emits current-render-view-deleted if the current RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; w.webContents.on('current-render-view-deleted' as any, () => { currentRenderViewDeletedEmitted = true; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted'); }); it('emits render-view-deleted if any RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let rvhDeletedCount = 0; w.webContents.on('render-view-deleted' as any, () => { rvhDeletedCount++; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; const expectedRenderViewDeletedEventCount = 1; expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times'); }); }); describe('setIgnoreMenuShortcuts(ignore)', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.setIgnoreMenuShortcuts(true); w.webContents.setIgnoreMenuShortcuts(false); }).to.not.throw(); }); }); const crashPrefs = [ { nodeIntegration: true }, { sandbox: true } ]; const nicePrefs = (o: any) => { let s = ''; for (const key of Object.keys(o)) { s += `${key}=${o[key]}, `; } return `(${s.slice(0, s.length - 2)})`; }; for (const prefs of crashPrefs) { describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('isCrashed() is false by default', () => { expect(w.webContents.isCrashed()).to.equal(false); }); it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => { expect(w.webContents.isCrashed()).to.equal(false); const crashEvent = once(w.webContents, 'render-process-gone') as Promise<[any, Electron.RenderProcessGoneDetails]>; w.webContents.forcefullyCrashRenderer(); const [, details] = await crashEvent; expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed'); expect(w.webContents.isCrashed()).to.equal(true); }); it('a crashed process is recoverable with reload()', async () => { expect(w.webContents.isCrashed()).to.equal(false); w.webContents.forcefullyCrashRenderer(); w.webContents.reload(); expect(w.webContents.isCrashed()).to.equal(false); }); }); } // Destroying webContents in its event listener is going to crash when // Electron is built in Debug mode. describe('destroy()', () => { let server: http.Server; let serverUrl: string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/200': response.end(); break; default: done(new Error('unsupported endpoint')); } }); listen(server).then(({ url }) => { serverUrl = url; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', url: '/200' }, { name: 'dom-ready', url: '/200' }, { name: 'did-stop-loading', url: '/200' }, { name: 'did-finish-load', url: '/200' }, // FIXME: Multiple Emit calls inside an observer assume that object // will be alive till end of the observer. Synchronous `destroy` api // violates this contract and crashes. { name: 'did-frame-finish-load', url: '/200' }, { name: 'did-fail-load', url: '/net-error' } ]; for (const e of events) { it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () { // This test is flaky on Windows CI and we don't know why, but the // purpose of this test is to make sure Electron does not crash so it // is fine to retry this test for a few times. this.retries(3); const contents = (webContents as typeof ElectronInternal.WebContents).create(); const originalEmit = contents.emit.bind(contents); contents.emit = (...args) => { return originalEmit(...args); }; contents.once(e.name as any, () => contents.destroy()); const destroyed = once(contents, 'destroyed'); contents.loadURL(serverUrl + e.url); await destroyed; }); } }); describe('did-change-theme-color event', () => { afterEach(closeAllWindows); it('is triggered with correct theme color', (done) => { const w = new BrowserWindow({ show: true }); let count = 0; w.webContents.on('did-change-theme-color', (e, color) => { try { if (count === 0) { count += 1; expect(color).to.equal('#FFEEDD'); w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); } else if (count === 1) { expect(color).to.be.null(); done(); } } catch (e) { done(e); } }); w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html')); }); }); describe('console-message event', () => { afterEach(closeAllWindows); it('is triggered with correct log message', (done) => { const w = new BrowserWindow({ show: true }); w.webContents.on('console-message', (e, level, message) => { // Don't just assert as Chromium might emit other logs that we should ignore. if (message === 'a') { done(); } }); w.loadFile(path.join(fixturesPath, 'pages', 'a.html')); }); }); describe('ipc-message event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends an asynchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); w.webContents.executeJavaScript(` require('electron').ipcRenderer.send('message', 'Hello World!') `); const [, channel, message] = await once(w.webContents, 'ipc-message'); expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); }); }); describe('ipc-message-sync event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends a synchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); const promise: Promise<[string, string]> = new Promise(resolve => { w.webContents.once('ipc-message-sync', (event, channel, arg) => { event.returnValue = 'foobar'; resolve([channel, arg]); }); }); const result = await w.webContents.executeJavaScript(` require('electron').ipcRenderer.sendSync('message', 'Hello World!') `); const [channel, message] = await promise; expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); expect(result).to.equal('foobar'); }); }); describe('referrer', () => { afterEach(closeAllWindows); it('propagates referrer information to new target=_blank windows', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } finally { server.close(); } } res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>'); }); listen(server).then(({ url }) => { w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url + '/'); expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin'); return { action: 'allow' }; }); w.webContents.executeJavaScript('a.click()'); }); w.loadURL(url); }); }); it('propagates referrer information to windows opened with window.open', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } } res.end(''); }); listen(server).then(({ url }) => { w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url + '/'); expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin'); return { action: 'allow' }; }); w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")'); }); w.loadURL(url); }); }); }); describe('webframe messages in sandboxed contents', () => { afterEach(closeAllWindows); it('responds to executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const result = await w.webContents.executeJavaScript('37 + 5'); expect(result).to.equal(42); }); }); describe('preload-error event', () => { afterEach(closeAllWindows); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('is triggered when unhandled exception is thrown', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>; w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('Hello World!'); }); it('is triggered on syntax errors', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>; w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('foobar is not defined'); }); it('is triggered when preload script loading fails', async () => { const preload = path.join(fixturesPath, 'module', 'preload-invalid.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>; w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.contain('preload-invalid.js'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('takeHeapSnapshot()', () => { afterEach(closeAllWindows); it('works with sandboxed renderers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); const cleanup = () => { try { fs.unlinkSync(filePath); } catch { // ignore error } }; try { await w.webContents.takeHeapSnapshot(filePath); const stats = fs.statSync(filePath); expect(stats.size).not.to.be.equal(0); } finally { cleanup(); } }); it('fails with invalid file path', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const badPath = path.join('i', 'am', 'a', 'super', 'bad', 'path'); const promise = w.webContents.takeHeapSnapshot(badPath); return expect(promise).to.be.eventually.rejectedWith(Error, `Failed to take heap snapshot with invalid file path ${badPath}`); }); it('fails with invalid render process', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); w.webContents.destroy(); const promise = w.webContents.takeHeapSnapshot(filePath); return expect(promise).to.be.eventually.rejectedWith(Error, 'Failed to take heap snapshot with nonexistent render frame'); }); }); describe('setBackgroundThrottling()', () => { afterEach(closeAllWindows); it('does not crash when allowing', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(true); }); it('does not crash when called via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); w.setBackgroundThrottling(true); }); it('does not crash when disallowing', () => { const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } }); w.webContents.setBackgroundThrottling(false); }); }); describe('getBackgroundThrottling()', () => { afterEach(closeAllWindows); it('works via getter', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); expect(w.webContents.getBackgroundThrottling()).to.equal(false); w.webContents.setBackgroundThrottling(true); expect(w.webContents.getBackgroundThrottling()).to.equal(true); }); it('works via property', () => { const w = new BrowserWindow({ show: false }); w.webContents.backgroundThrottling = false; expect(w.webContents.backgroundThrottling).to.equal(false); w.webContents.backgroundThrottling = true; expect(w.webContents.backgroundThrottling).to.equal(true); }); it('works via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); w.setBackgroundThrottling(false); expect(w.getBackgroundThrottling()).to.equal(false); w.setBackgroundThrottling(true); expect(w.getBackgroundThrottling()).to.equal(true); }); }); ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = await w.webContents.getPrintersAsync(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('printToPDF()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); afterEach(closeAllWindows); it('rejects on incorrectly typed parameters', async () => { const badTypes = { landscape: [], displayHeaderFooter: '123', printBackground: 2, scale: 'not-a-number', pageSize: 'IAmAPageSize', margins: 'terrible', pageRanges: { oops: 'im-not-the-right-key' }, headerTemplate: [1, 2, 3], footerTemplate: [4, 5, 6], preferCSSPageSize: 'no' }; await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); // These will hard crash in Chromium unless we type-check for (const [key, value] of Object.entries(badTypes)) { const param = { [key]: value }; await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected(); } }); it('does not crash when called multiple times in parallel', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); const promises = []; for (let i = 0; i < 3; i++) { promises.push(w.webContents.printToPDF({})); } const results = await Promise.all(promises); for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); it('does not crash when called multiple times in sequence', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); const results = []; for (let i = 0; i < 3; i++) { const result = await w.webContents.printToPDF({}); results.push(result); } for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); it('can print a PDF with default settings', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); const data = await w.webContents.printToPDF({}); expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); }); type PageSizeString = Exclude<Required<Electron.PrintToPDFOptions>['pageSize'], Electron.Size>; it('with custom page sizes', async () => { const paperFormats: Record<PageSizeString, ElectronInternal.PageSize> = { Letter: { width: 8.5, height: 11 }, Legal: { width: 8.5, height: 14 }, Tabloid: { width: 11, height: 17 }, Ledger: { width: 17, height: 11 }, A0: { width: 33.1, height: 46.8 }, A1: { width: 23.4, height: 33.1 }, A2: { width: 16.54, height: 23.4 }, A3: { width: 11.7, height: 16.54 }, A4: { width: 8.27, height: 11.7 }, A5: { width: 5.83, height: 8.27 }, A6: { width: 4.13, height: 5.83 } }; await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); for (const format of Object.keys(paperFormats) as PageSizeString[]) { const data = await w.webContents.printToPDF({ pageSize: format }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); // page.view is [top, left, width, height]. const width = page.view[2] / 72; const height = page.view[3] / 72; const approxEq = (a: number, b: number, epsilon = 0.01) => Math.abs(a - b) <= epsilon; expect(approxEq(width, paperFormats[format].width)).to.be.true(); expect(approxEq(height, paperFormats[format].height)).to.be.true(); } }); it('with custom header and footer', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ displayHeaderFooter: true, headerTemplate: '<div>I\'m a PDF header</div>', footerTemplate: '<div>I\'m a PDF footer</div>' }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); const { items } = await page.getTextContent(); // Check that generated PDF contains a header. const containsText = (text: RegExp) => items.some(({ str }: { str: string }) => str.match(text)); expect(containsText(/I'm a PDF header/)).to.be.true(); expect(containsText(/I'm a PDF footer/)).to.be.true(); }); it('in landscape mode', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ landscape: true }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); // page.view is [top, left, width, height]. const width = page.view[2]; const height = page.view[3]; expect(width).to.be.greaterThan(height); }); it('with custom page ranges', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-large.html')); const data = await w.webContents.printToPDF({ pageRanges: '1-3', landscape: true }); const doc = await pdfjs.getDocument(data).promise; // Check that correct # of pages are rendered. expect(doc.numPages).to.equal(3); }); it('does not tag PDFs by default', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({}); const doc = await pdfjs.getDocument(data).promise; const markInfo = await doc.getMarkInfo(); expect(markInfo).to.be.null(); }); it('can generate tag data for PDFs', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ generateTaggedPDF: true }); const doc = await pdfjs.getDocument(data).promise; const markInfo = await doc.getMarkInfo(); expect(markInfo).to.deep.equal({ Marked: true, UserProperties: false, Suspects: false }); }); }); describe('PictureInPicture video', () => { afterEach(closeAllWindows); it('works as expected', async function () { const w = new BrowserWindow({ webPreferences: { sandbox: true } }); // TODO(codebytere): figure out why this workaround is needed and remove. // It is not germane to the actual test. await w.loadFile(path.join(fixturesPath, 'blank.html')); await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html')); await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')', true); const result = await w.webContents.executeJavaScript('runTest(true)', true); expect(result).to.be.true(); }); }); describe('Shared Workers', () => { afterEach(closeAllWindows); it('can get multiple shared workers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = once(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); expect(sharedWorkers).to.have.lengthOf(2); expect(sharedWorkers[0].url).to.contain('shared-worker'); expect(sharedWorkers[1].url).to.contain('shared-worker'); }); it('can inspect a specific shared worker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = once(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.inspectSharedWorkerById(sharedWorkers[0].id); await devtoolsOpened; const devtoolsClosed = once(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devtoolsClosed; }); }); describe('login event', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; let serverPort: number; let proxyServer: http.Server; let proxyServerPort: number; before(async () => { server = http.createServer((request, response) => { if (request.url === '/no-auth') { return response.end('ok'); } if (request.headers.authorization) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers.authorization); } response .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }) .end('401'); }); ({ port: serverPort, url: serverUrl } = await listen(server)); }); before(async () => { proxyServer = http.createServer((request, response) => { if (request.headers['proxy-authorization']) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers['proxy-authorization']); } response .writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }) .end(); }); proxyServerPort = (await listen(proxyServer)).port; }); afterEach(async () => { await session.defaultSession.clearAuthCache(); }); after(() => { server.close(); proxyServer.close(); }); it('is emitted when navigating', async () => { const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(serverUrl + '/'); expect(eventAuthInfo.isProxy).to.be.false(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(serverPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('is emitted when a proxy requests authorization', async () => { const customSession = session.fromPartition(`${Math.random()}`); await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' }); const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(`${serverUrl}/no-auth`); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`); expect(eventAuthInfo.isProxy).to.be.true(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(proxyServerPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('cancels authentication when callback is called with no arguments', async () => { const w = new BrowserWindow({ show: false }); w.webContents.on('login', (event, request, authInfo, cb) => { event.preventDefault(); cb(); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal('401'); }); }); describe('page-title-updated event', () => { afterEach(closeAllWindows); it('is emitted with a full title for pages with no navigation', async () => { const bw = new BrowserWindow({ show: false }); await bw.loadURL('about:blank'); bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null'); const [, child] = await once(app, 'web-contents-created') as [any, WebContents]; bw.webContents.executeJavaScript('child.document.title = "new title"'); const [, title] = await once(child, 'page-title-updated') as [any, string]; expect(title).to.equal('new title'); }); }); describe('context-menu event', () => { afterEach(closeAllWindows); it('emits when right-clicked in page', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const promise = once(w.webContents, 'context-menu') as Promise<[any, Electron.ContextMenuParams]>; // Simulate right-click to create context-menu event. const opts = { x: 0, y: 0, button: 'right' as const }; w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' }); w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' }); const [, params] = await promise; expect(params.pageURL).to.equal(w.webContents.getURL()); expect(params.frame).to.be.an('object'); expect(params.x).to.be.a('number'); expect(params.y).to.be.a('number'); }); }); describe('close() method', () => { afterEach(closeAllWindows); it('closes when close() is called', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('closes when close() is called after loading a page', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('can be GCed before loading a page', async () => { const v8Util = process._linkedBinding('electron_common_v8_util'); let registry: FinalizationRegistry<unknown> | null = null; const cleanedUp = new Promise<number>(resolve => { registry = new FinalizationRegistry(resolve as any); }); (() => { const w = (webContents as typeof ElectronInternal.WebContents).create(); registry!.register(w, 42); })(); const i = setInterval(() => v8Util.requestGarbageCollectionForTesting(), 100); defer(() => clearInterval(i)); expect(await cleanedUp).to.equal(42); }); it('causes its parent browserwindow to be closed', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const closed = once(w, 'closed'); w.webContents.close(); await closed; expect(w.isDestroyed()).to.be.true(); }); it('ignores beforeunload if waitForBeforeUnload not specified', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.on('will-prevent-unload', () => { throw new Error('unexpected will-prevent-unload'); }); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('runs beforeunload if waitForBeforeUnload is specified', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); const willPreventUnload = once(w, 'will-prevent-unload'); w.close({ waitForBeforeUnload: true }); await willPreventUnload; expect(w.isDestroyed()).to.be.false(); }); it('overriding beforeunload prevention results in webcontents close', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.once('will-prevent-unload', e => e.preventDefault()); const destroyed = once(w, 'destroyed'); w.close({ waitForBeforeUnload: true }); await destroyed; expect(w.isDestroyed()).to.be.true(); }); }); describe('content-bounds-updated event', () => { afterEach(closeAllWindows); it('emits when moveTo is called', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.moveTo(100, 100)', true); const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle]; const { width, height } = w.getBounds(); expect(rect).to.deep.equal({ x: 100, y: 100, width, height }); await new Promise(setImmediate); expect(w.getBounds().x).to.equal(100); expect(w.getBounds().y).to.equal(100); }); it('emits when resizeTo is called', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.resizeTo(100, 100)', true); const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle]; const { x, y } = w.getBounds(); expect(rect).to.deep.equal({ x, y, width: 100, height: 100 }); await new Promise(setImmediate); expect({ width: w.getBounds().width, height: w.getBounds().height }).to.deep.equal(process.platform === 'win32' ? { // The width is reported as being larger on Windows? I'm not sure why // this is. width: 136, height: 100 } : { width: 100, height: 100 }); }); it('does not change window bounds if cancelled', async () => { const w = new BrowserWindow({ show: false }); const { width, height } = w.getBounds(); w.loadURL('about:blank'); w.webContents.once('content-bounds-updated', e => e.preventDefault()); await w.webContents.executeJavaScript('window.resizeTo(100, 100)', true); await new Promise(setImmediate); expect(w.getBounds().width).to.equal(width); expect(w.getBounds().height).to.equal(height); }); }); });
closed
electron/electron
https://github.com/electron/electron
40,354
[Bug]: Zoom controller doesn't persist when changing webviews
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.2 ### What operating system are you using? Windows ### Operating System Version Windows 11 Pro 22H2 - Build 22621.2428 ### What arch are you using? x64 ### Last Known Working Electron version 26.0.0 ### Expected Behavior When switching between different Webviews the Zoom scale persists after going back to the initial webview. ### Actual Behavior [Ferdium](https://github.com/ferdium/ferdium-app) currently uses multiple Webviews for each service it renders. When switching between Webviews the Zoom scale is not persistent (when switching away the zoom resets - this is visible for some milliseconds before changing to the other webview). ### Testcase Gist URL _No response_ ### Additional Information I'm logging this issue in Electron given that this was not present in past versions of Electron, but only after `26.0.0` (I'm blaming `26.1.0` as the version who started to cause issues). After some investigation it seems like the PR that caused this unwanted behaviour is: https://github.com/electron/electron/pull/39495 . Is it possible for you to search and revert this unwanted breakage? We would really need this to be fix because we have several users with this accessibility needs. Thank you very much in advance! PS: If this is not the proper way to open an issue on Electron please let me know.
https://github.com/electron/electron/issues/40354
https://github.com/electron/electron/pull/40650
66b4b216468feab79c7527295f2485067ea2cf15
10a165a9ff731137b679a4ef3a9e3d18bcdfd514
2023-10-27T12:40:22Z
c++
2023-12-04T15:39:20Z
shell/browser/web_contents_zoom_controller.cc
// Copyright (c) 2017 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/web_contents_zoom_controller.h" #include <string> #include "content/public/browser/browser_thread.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/web_contents.h" #include "content/public/browser/web_contents_user_data.h" #include "content/public/common/page_type.h" #include "net/base/url_util.h" #include "shell/browser/web_contents_zoom_observer.h" #include "third_party/blink/public/common/page/page_zoom.h" using content::BrowserThread; namespace electron { namespace { const double kPageZoomEpsilon = 0.001; } // namespace WebContentsZoomController::WebContentsZoomController( content::WebContents* web_contents) : content::WebContentsObserver(web_contents), content::WebContentsUserData<WebContentsZoomController>(*web_contents) { DCHECK_CURRENTLY_ON(BrowserThread::UI); host_zoom_map_ = content::HostZoomMap::GetForWebContents(web_contents); zoom_level_ = host_zoom_map_->GetDefaultZoomLevel(); default_zoom_factor_ = kPageZoomEpsilon; zoom_subscription_ = host_zoom_map_->AddZoomLevelChangedCallback( base::BindRepeating(&WebContentsZoomController::OnZoomLevelChanged, base::Unretained(this))); UpdateState(std::string()); } WebContentsZoomController::~WebContentsZoomController() { DCHECK_CURRENTLY_ON(BrowserThread::UI); for (auto& observer : observers_) { observer.OnZoomControllerDestroyed(this); } } void WebContentsZoomController::AddObserver(WebContentsZoomObserver* observer) { DCHECK_CURRENTLY_ON(BrowserThread::UI); observers_.AddObserver(observer); } void WebContentsZoomController::RemoveObserver( WebContentsZoomObserver* observer) { DCHECK_CURRENTLY_ON(BrowserThread::UI); observers_.RemoveObserver(observer); } void WebContentsZoomController::SetEmbedderZoomController( WebContentsZoomController* controller) { DCHECK_CURRENTLY_ON(BrowserThread::UI); embedder_zoom_controller_ = controller; } bool WebContentsZoomController::SetZoomLevel(double level) { DCHECK_CURRENTLY_ON(BrowserThread::UI); content::NavigationEntry* entry = web_contents()->GetController().GetLastCommittedEntry(); // Cannot zoom in disabled mode. Also, don't allow changing zoom level on // a crashed tab, an error page or an interstitial page. if (zoom_mode_ == ZOOM_MODE_DISABLED || !web_contents()->GetPrimaryMainFrame()->IsRenderFrameLive()) return false; // Do not actually rescale the page in manual mode. if (zoom_mode_ == ZOOM_MODE_MANUAL) { // If the zoom level hasn't changed, early out to avoid sending an event. if (blink::PageZoomValuesEqual(zoom_level_, level)) return true; double old_zoom_level = zoom_level_; zoom_level_ = level; ZoomChangedEventData zoom_change_data(web_contents(), old_zoom_level, zoom_level_, false /* temporary */, zoom_mode_); for (auto& observer : observers_) observer.OnZoomChanged(zoom_change_data); return true; } content::HostZoomMap* zoom_map = content::HostZoomMap::GetForWebContents(web_contents()); DCHECK(zoom_map); DCHECK(!event_data_); event_data_ = std::make_unique<ZoomChangedEventData>( web_contents(), GetZoomLevel(), level, false /* temporary */, zoom_mode_); content::GlobalRenderFrameHostId rfh_id = web_contents()->GetPrimaryMainFrame()->GetGlobalId(); if (zoom_mode_ == ZOOM_MODE_ISOLATED || zoom_map->UsesTemporaryZoomLevel(rfh_id)) { zoom_map->SetTemporaryZoomLevel(rfh_id, level); ZoomChangedEventData zoom_change_data(web_contents(), zoom_level_, level, true /* temporary */, zoom_mode_); for (auto& observer : observers_) observer.OnZoomChanged(zoom_change_data); } else { if (!entry) { // If we exit without triggering an update, we should clear event_data_, // else we may later trigger a DCHECK(event_data_). event_data_.reset(); return false; } std::string host = net::GetHostOrSpecFromURL(content::HostZoomMap::GetURLFromEntry(entry)); zoom_map->SetZoomLevelForHost(host, level); } DCHECK(!event_data_); return true; } double WebContentsZoomController::GetZoomLevel() const { DCHECK_CURRENTLY_ON(BrowserThread::UI); return zoom_mode_ == ZOOM_MODE_MANUAL ? zoom_level_ : content::HostZoomMap::GetZoomLevel(web_contents()); } void WebContentsZoomController::SetDefaultZoomFactor(double factor) { default_zoom_factor_ = factor; } double WebContentsZoomController::GetDefaultZoomFactor() { return default_zoom_factor_; } void WebContentsZoomController::SetTemporaryZoomLevel(double level) { DCHECK_CURRENTLY_ON(BrowserThread::UI); content::GlobalRenderFrameHostId old_rfh_id_ = web_contents()->GetPrimaryMainFrame()->GetGlobalId(); host_zoom_map_->SetTemporaryZoomLevel(old_rfh_id_, level); // Notify observers of zoom level changes. ZoomChangedEventData zoom_change_data(web_contents(), zoom_level_, level, true /* temporary */, zoom_mode_); for (WebContentsZoomObserver& observer : observers_) observer.OnZoomChanged(zoom_change_data); } bool WebContentsZoomController::UsesTemporaryZoomLevel() { DCHECK_CURRENTLY_ON(BrowserThread::UI); content::GlobalRenderFrameHostId rfh_id = web_contents()->GetPrimaryMainFrame()->GetGlobalId(); return host_zoom_map_->UsesTemporaryZoomLevel(rfh_id); } void WebContentsZoomController::SetZoomMode(ZoomMode new_mode) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (new_mode == zoom_mode_) return; content::HostZoomMap* zoom_map = content::HostZoomMap::GetForWebContents(web_contents()); DCHECK(zoom_map); content::GlobalRenderFrameHostId rfh_id = web_contents()->GetPrimaryMainFrame()->GetGlobalId(); double original_zoom_level = GetZoomLevel(); DCHECK(!event_data_); event_data_ = std::make_unique<ZoomChangedEventData>( web_contents(), original_zoom_level, original_zoom_level, false /* temporary */, new_mode); switch (new_mode) { case ZOOM_MODE_DEFAULT: { content::NavigationEntry* entry = web_contents()->GetController().GetLastCommittedEntry(); if (entry) { GURL url = content::HostZoomMap::GetURLFromEntry(entry); std::string host = net::GetHostOrSpecFromURL(url); if (zoom_map->HasZoomLevel(url.scheme(), host)) { // If there are other tabs with the same origin, then set this tab's // zoom level to match theirs. The temporary zoom level will be // cleared below, but this call will make sure this tab re-draws at // the correct zoom level. double origin_zoom_level = zoom_map->GetZoomLevelForHostAndScheme(url.scheme(), host); event_data_->new_zoom_level = origin_zoom_level; zoom_map->SetTemporaryZoomLevel(rfh_id, origin_zoom_level); } else { // The host will need a level prior to removing the temporary level. // We don't want the zoom level to change just because we entered // default mode. zoom_map->SetZoomLevelForHost(host, original_zoom_level); } } // Remove per-tab zoom data for this tab. No event callback expected. zoom_map->ClearTemporaryZoomLevel(rfh_id); break; } case ZOOM_MODE_ISOLATED: { // Unless the zoom mode was |ZOOM_MODE_DISABLED| before this call, the // page needs an initial isolated zoom back to the same level it was at // in the other mode. if (zoom_mode_ != ZOOM_MODE_DISABLED) { zoom_map->SetTemporaryZoomLevel(rfh_id, original_zoom_level); } else { // When we don't call any HostZoomMap set functions, we send the event // manually. for (auto& observer : observers_) observer.OnZoomChanged(*event_data_); event_data_.reset(); } break; } case ZOOM_MODE_MANUAL: { // Unless the zoom mode was |ZOOM_MODE_DISABLED| before this call, the // page needs to be resized to the default zoom. While in manual mode, // the zoom level is handled independently. if (zoom_mode_ != ZOOM_MODE_DISABLED) { zoom_map->SetTemporaryZoomLevel(rfh_id, GetDefaultZoomLevel()); zoom_level_ = original_zoom_level; } else { // When we don't call any HostZoomMap set functions, we send the event // manually. for (auto& observer : observers_) observer.OnZoomChanged(*event_data_); event_data_.reset(); } break; } case ZOOM_MODE_DISABLED: { // The page needs to be zoomed back to default before disabling the zoom double new_zoom_level = GetDefaultZoomLevel(); event_data_->new_zoom_level = new_zoom_level; zoom_map->SetTemporaryZoomLevel(rfh_id, new_zoom_level); break; } } // Any event data we've stored should have been consumed by this point. DCHECK(!event_data_); zoom_mode_ = new_mode; } void WebContentsZoomController::ResetZoomModeOnNavigationIfNeeded( const GURL& url) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (zoom_mode_ != ZOOM_MODE_ISOLATED && zoom_mode_ != ZOOM_MODE_MANUAL) return; content::HostZoomMap* zoom_map = content::HostZoomMap::GetForWebContents(web_contents()); zoom_level_ = zoom_map->GetDefaultZoomLevel(); double old_zoom_level = zoom_map->GetZoomLevel(web_contents()); double new_zoom_level = zoom_map->GetZoomLevelForHostAndScheme( url.scheme(), net::GetHostOrSpecFromURL(url)); event_data_ = std::make_unique<ZoomChangedEventData>( web_contents(), old_zoom_level, new_zoom_level, false, ZOOM_MODE_DEFAULT); // The call to ClearTemporaryZoomLevel() doesn't generate any events from // HostZoomMap, but the call to UpdateState() at the end of // DidFinishNavigation will notify our observers. // Note: it's possible the render_process/frame ids have disappeared (e.g. // if we navigated to a new origin), but this won't cause a problem in the // call below. zoom_map->ClearTemporaryZoomLevel( web_contents()->GetPrimaryMainFrame()->GetGlobalId()); zoom_mode_ = ZOOM_MODE_DEFAULT; } void WebContentsZoomController::DidFinishNavigation( content::NavigationHandle* navigation_handle) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!navigation_handle->IsInPrimaryMainFrame() || !navigation_handle->HasCommitted()) { return; } if (navigation_handle->IsErrorPage()) content::HostZoomMap::SendErrorPageZoomLevelRefresh(web_contents()); if (!navigation_handle->IsSameDocument()) { ResetZoomModeOnNavigationIfNeeded(navigation_handle->GetURL()); SetZoomFactorOnNavigationIfNeeded(navigation_handle->GetURL()); } // If the main frame's content has changed, the new page may have a different // zoom level from the old one. UpdateState(std::string()); DCHECK(!event_data_); } void WebContentsZoomController::WebContentsDestroyed() { DCHECK_CURRENTLY_ON(BrowserThread::UI); // At this point we should no longer be sending any zoom events with this // WebContents. for (auto& observer : observers_) { observer.OnZoomControllerDestroyed(this); } embedder_zoom_controller_ = nullptr; } void WebContentsZoomController::RenderFrameHostChanged( content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // If our associated HostZoomMap changes, update our subscription. content::HostZoomMap* new_host_zoom_map = content::HostZoomMap::GetForWebContents(web_contents()); if (new_host_zoom_map == host_zoom_map_) return; host_zoom_map_ = new_host_zoom_map; zoom_subscription_ = host_zoom_map_->AddZoomLevelChangedCallback( base::BindRepeating(&WebContentsZoomController::OnZoomLevelChanged, base::Unretained(this))); } void WebContentsZoomController::SetZoomFactorOnNavigationIfNeeded( const GURL& url) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (blink::PageZoomValuesEqual(GetDefaultZoomFactor(), kPageZoomEpsilon)) return; content::GlobalRenderFrameHostId old_rfh_id_ = content::GlobalRenderFrameHostId(old_process_id_, old_view_id_); if (host_zoom_map_->UsesTemporaryZoomLevel(old_rfh_id_)) { host_zoom_map_->ClearTemporaryZoomLevel(old_rfh_id_); } if (embedder_zoom_controller_ && embedder_zoom_controller_->UsesTemporaryZoomLevel()) { double level = embedder_zoom_controller_->GetZoomLevel(); SetTemporaryZoomLevel(level); return; } // When kZoomFactor is available, it takes precedence over // pref store values but if the host has zoom factor set explicitly // then it takes precedence. // pref store < kZoomFactor < setZoomLevel std::string host = net::GetHostOrSpecFromURL(url); std::string scheme = url.scheme(); double zoom_factor = GetDefaultZoomFactor(); double zoom_level = blink::PageZoomFactorToZoomLevel(zoom_factor); if (host_zoom_map_->HasZoomLevel(scheme, host)) { zoom_level = host_zoom_map_->GetZoomLevelForHostAndScheme(scheme, host); } if (blink::PageZoomValuesEqual(zoom_level, GetZoomLevel())) return; SetZoomLevel(zoom_level); } void WebContentsZoomController::OnZoomLevelChanged( const content::HostZoomMap::ZoomLevelChange& change) { DCHECK_CURRENTLY_ON(BrowserThread::UI); UpdateState(change.host); } void WebContentsZoomController::UpdateState(const std::string& host) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // If |host| is empty, all observers should be updated. if (!host.empty()) { // Use the navigation entry's URL instead of the WebContents' so virtual // URLs work (e.g. chrome://settings). http://crbug.com/153950 content::NavigationEntry* entry = web_contents()->GetController().GetLastCommittedEntry(); if (!entry || host != net::GetHostOrSpecFromURL( content::HostZoomMap::GetURLFromEntry(entry))) { return; } } if (event_data_) { // For state changes initiated within the ZoomController, information about // the change should be sent. ZoomChangedEventData zoom_change_data = *event_data_; event_data_.reset(); for (auto& observer : observers_) observer.OnZoomChanged(zoom_change_data); } else { double zoom_level = GetZoomLevel(); ZoomChangedEventData zoom_change_data(web_contents(), zoom_level, zoom_level, false, zoom_mode_); for (auto& observer : observers_) observer.OnZoomChanged(zoom_change_data); } } WEB_CONTENTS_USER_DATA_KEY_IMPL(WebContentsZoomController); } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,354
[Bug]: Zoom controller doesn't persist when changing webviews
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.2 ### What operating system are you using? Windows ### Operating System Version Windows 11 Pro 22H2 - Build 22621.2428 ### What arch are you using? x64 ### Last Known Working Electron version 26.0.0 ### Expected Behavior When switching between different Webviews the Zoom scale persists after going back to the initial webview. ### Actual Behavior [Ferdium](https://github.com/ferdium/ferdium-app) currently uses multiple Webviews for each service it renders. When switching between Webviews the Zoom scale is not persistent (when switching away the zoom resets - this is visible for some milliseconds before changing to the other webview). ### Testcase Gist URL _No response_ ### Additional Information I'm logging this issue in Electron given that this was not present in past versions of Electron, but only after `26.0.0` (I'm blaming `26.1.0` as the version who started to cause issues). After some investigation it seems like the PR that caused this unwanted behaviour is: https://github.com/electron/electron/pull/39495 . Is it possible for you to search and revert this unwanted breakage? We would really need this to be fix because we have several users with this accessibility needs. Thank you very much in advance! PS: If this is not the proper way to open an issue on Electron please let me know.
https://github.com/electron/electron/issues/40354
https://github.com/electron/electron/pull/40650
66b4b216468feab79c7527295f2485067ea2cf15
10a165a9ff731137b679a4ef3a9e3d18bcdfd514
2023-10-27T12:40:22Z
c++
2023-12-04T15:39:20Z
spec/fixtures/pages/webview-zoom-change-persist-host.html
closed
electron/electron
https://github.com/electron/electron
40,354
[Bug]: Zoom controller doesn't persist when changing webviews
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.2 ### What operating system are you using? Windows ### Operating System Version Windows 11 Pro 22H2 - Build 22621.2428 ### What arch are you using? x64 ### Last Known Working Electron version 26.0.0 ### Expected Behavior When switching between different Webviews the Zoom scale persists after going back to the initial webview. ### Actual Behavior [Ferdium](https://github.com/ferdium/ferdium-app) currently uses multiple Webviews for each service it renders. When switching between Webviews the Zoom scale is not persistent (when switching away the zoom resets - this is visible for some milliseconds before changing to the other webview). ### Testcase Gist URL _No response_ ### Additional Information I'm logging this issue in Electron given that this was not present in past versions of Electron, but only after `26.0.0` (I'm blaming `26.1.0` as the version who started to cause issues). After some investigation it seems like the PR that caused this unwanted behaviour is: https://github.com/electron/electron/pull/39495 . Is it possible for you to search and revert this unwanted breakage? We would really need this to be fix because we have several users with this accessibility needs. Thank you very much in advance! PS: If this is not the proper way to open an issue on Electron please let me know.
https://github.com/electron/electron/issues/40354
https://github.com/electron/electron/pull/40650
66b4b216468feab79c7527295f2485067ea2cf15
10a165a9ff731137b679a4ef3a9e3d18bcdfd514
2023-10-27T12:40:22Z
c++
2023-12-04T15:39:20Z
spec/node-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as fs from 'node:fs'; import * as path from 'node:path'; import * as util from 'node:util'; import { getRemoteContext, ifdescribe, ifit, itremote, useRemoteContext } from './lib/spec-helpers'; import { webContents } from 'electron/main'; import { EventEmitter } from 'node:stream'; import { once } from 'node:events'; const mainFixturesPath = path.resolve(__dirname, 'fixtures'); describe('node feature', () => { const fixtures = path.join(__dirname, 'fixtures'); describe('child_process', () => { describe('child_process.fork', () => { it('Works in browser process', async () => { const child = childProcess.fork(path.join(fixtures, 'module', 'ping.js')); const message = once(child, 'message'); child.send('message'); const [msg] = await message; expect(msg).to.equal('message'); }); }); }); describe('child_process in renderer', () => { useRemoteContext(); describe('child_process.fork', () => { itremote('works in current process', async (fixtures: string) => { const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'ping.js')); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.equal('message'); }, [fixtures]); itremote('preserves args', async (fixtures: string) => { const args = ['--expose_gc', '-test', '1']; const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'process_args.js'), args); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(args).to.deep.equal(msg.slice(2)); }, [fixtures]); itremote('works in forked process', async (fixtures: string) => { const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'fork_ping.js')); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.equal('message'); }, [fixtures]); itremote('works in forked process when options.env is specified', async (fixtures: string) => { const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'fork_ping.js'), [], { path: process.env.PATH }); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.equal('message'); }, [fixtures]); itremote('has String::localeCompare working in script', async (fixtures: string) => { const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'locale-compare.js')); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.deep.equal([0, -1, 1]); }, [fixtures]); itremote('has setImmediate working in script', async (fixtures: string) => { const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'set-immediate.js')); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.equal('ok'); }, [fixtures]); itremote('pipes stdio', async (fixtures: string) => { const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'process-stdout.js'), { silent: true }); let data = ''; child.stdout.on('data', (chunk: any) => { data += String(chunk); }); const code = await new Promise<any>(resolve => child.once('close', resolve)); expect(code).to.equal(0); expect(data).to.equal('pipes stdio'); }, [fixtures]); itremote('works when sending a message to a process forked with the --eval argument', async () => { const source = "process.on('message', (message) => { process.send(message) })"; const forked = require('node:child_process').fork('--eval', [source]); const message = new Promise(resolve => forked.once('message', resolve)); forked.send('hello'); const msg = await message; expect(msg).to.equal('hello'); }); it('has the electron version in process.versions', async () => { const source = 'process.send(process.versions)'; const forked = require('node:child_process').fork('--eval', [source]); const [message] = await once(forked, 'message'); expect(message) .to.have.own.property('electron') .that.is.a('string') .and.matches(/^\d+\.\d+\.\d+(\S*)?$/); }); }); describe('child_process.spawn', () => { itremote('supports spawning Electron as a node process via the ELECTRON_RUN_AS_NODE env var', async (fixtures: string) => { const child = require('node:child_process').spawn(process.execPath, [require('node:path').join(fixtures, 'module', 'run-as-node.js')], { env: { ELECTRON_RUN_AS_NODE: true } }); let output = ''; child.stdout.on('data', (data: any) => { output += data; }); try { await new Promise(resolve => child.stdout.once('close', resolve)); expect(JSON.parse(output)).to.deep.equal({ stdoutType: 'pipe', processType: 'undefined', window: 'undefined' }); } finally { child.kill(); } }, [fixtures]); }); describe('child_process.exec', () => { ifit(process.platform === 'linux')('allows executing a setuid binary from non-sandboxed renderer', async () => { // Chrome uses prctl(2) to set the NO_NEW_PRIVILEGES flag on Linux (see // https://github.com/torvalds/linux/blob/40fde647cc/Documentation/userspace-api/no_new_privs.rst). // We disable this for unsandboxed processes, which the renderer tests // are running in. If this test fails with an error like 'effective uid // is not 0', then it's likely that our patch to prevent the flag from // being set has become ineffective. const w = await getRemoteContext(); const stdout = await w.webContents.executeJavaScript('require(\'child_process\').execSync(\'sudo --help\')'); expect(stdout).to.not.be.empty(); }); }); }); it('does not hang when using the fs module in the renderer process', async () => { const appPath = path.join(mainFixturesPath, 'apps', 'libuv-hang', 'main.js'); const appProcess = childProcess.spawn(process.execPath, [appPath], { cwd: path.join(mainFixturesPath, 'apps', 'libuv-hang'), stdio: 'inherit' }); const [code] = await once(appProcess, 'close'); expect(code).to.equal(0); }); describe('contexts', () => { describe('setTimeout called under Chromium event loop in browser process', () => { it('Can be scheduled in time', (done) => { setTimeout(done, 0); }); it('Can be promisified', (done) => { util.promisify(setTimeout)(0).then(done); }); }); describe('setInterval called under Chromium event loop in browser process', () => { it('can be scheduled in time', (done) => { let interval: any = null; let clearing = false; const clear = () => { if (interval === null || clearing) return; // interval might trigger while clearing (remote is slow sometimes) clearing = true; clearInterval(interval); clearing = false; interval = null; done(); }; interval = setInterval(clear, 10); }); }); const suspendListeners = (emitter: EventEmitter, eventName: string, callback: (...args: any[]) => void) => { const listeners = emitter.listeners(eventName) as ((...args: any[]) => void)[]; emitter.removeAllListeners(eventName); emitter.once(eventName, (...args) => { emitter.removeAllListeners(eventName); for (const listener of listeners) { emitter.on(eventName, listener); } callback(...args); }); }; describe('error thrown in main process node context', () => { it('gets emitted as a process uncaughtException event', async () => { fs.readFile(__filename, () => { throw new Error('hello'); }); const result = await new Promise(resolve => suspendListeners(process, 'uncaughtException', (error) => { resolve(error.message); })); expect(result).to.equal('hello'); }); }); describe('promise rejection in main process node context', () => { it('gets emitted as a process unhandledRejection event', async () => { fs.readFile(__filename, () => { Promise.reject(new Error('hello')); }); const result = await new Promise(resolve => suspendListeners(process, 'unhandledRejection', (error) => { resolve(error.message); })); expect(result).to.equal('hello'); }); it('does not log the warning more than once when the rejection is unhandled', async () => { const appPath = path.join(mainFixturesPath, 'api', 'unhandled-rejection.js'); const appProcess = childProcess.spawn(process.execPath, [appPath]); let output = ''; const out = (data: string) => { output += data; if (/UnhandledPromiseRejectionWarning/.test(data)) { appProcess.kill(); } }; appProcess.stdout!.on('data', out); appProcess.stderr!.on('data', out); await once(appProcess, 'exit'); expect(/UnhandledPromiseRejectionWarning/.test(output)).to.equal(true); const matches = output.match(/Error: oops/gm); expect(matches).to.have.lengthOf(1); }); it('does not log the warning more than once when the rejection is handled', async () => { const appPath = path.join(mainFixturesPath, 'api', 'unhandled-rejection-handled.js'); const appProcess = childProcess.spawn(process.execPath, [appPath]); let output = ''; const out = (data: string) => { output += data; }; appProcess.stdout!.on('data', out); appProcess.stderr!.on('data', out); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); expect(/UnhandledPromiseRejectionWarning/.test(output)).to.equal(false); const matches = output.match(/Error: oops/gm); expect(matches).to.have.lengthOf(1); }); }); }); describe('contexts in renderer', () => { useRemoteContext(); describe('setTimeout in fs callback', () => { itremote('does not crash', async (filename: string) => { await new Promise(resolve => require('node:fs').readFile(filename, () => { setTimeout(resolve, 0); })); }, [__filename]); }); describe('error thrown in renderer process node context', () => { itremote('gets emitted as a process uncaughtException event', async (filename: string) => { const error = new Error('boo!'); require('node:fs').readFile(filename, () => { throw error; }); await new Promise<void>((resolve, reject) => { process.once('uncaughtException', (thrown) => { try { expect(thrown).to.equal(error); resolve(); } catch (e) { reject(e); } }); }); }, [__filename]); }); describe('URL handling in the renderer process', () => { itremote('can successfully handle WHATWG URLs constructed by Blink', (fixtures: string) => { const url = new URL('file://' + require('node:path').resolve(fixtures, 'pages', 'base-page.html')); expect(() => { require('node:fs').createReadStream(url); }).to.not.throw(); }, [fixtures]); }); describe('setTimeout called under blink env in renderer process', () => { itremote('can be scheduled in time', async () => { await new Promise(resolve => setTimeout(resolve, 10)); }); itremote('works from the timers module', async () => { await new Promise(resolve => require('node:timers').setTimeout(resolve, 10)); }); }); describe('setInterval called under blink env in renderer process', () => { itremote('can be scheduled in time', async () => { await new Promise<void>(resolve => { const id = setInterval(() => { clearInterval(id); resolve(); }, 10); }); }); itremote('can be scheduled in time from timers module', async () => { const { setInterval, clearInterval } = require('node:timers'); await new Promise<void>(resolve => { const id = setInterval(() => { clearInterval(id); resolve(); }, 10); }); }); }); }); describe('message loop in renderer', () => { useRemoteContext(); describe('process.nextTick', () => { itremote('emits the callback', () => new Promise(resolve => process.nextTick(resolve))); itremote('works in nested calls', () => new Promise(resolve => { process.nextTick(() => { process.nextTick(() => process.nextTick(resolve)); }); })); }); describe('setImmediate', () => { itremote('emits the callback', () => new Promise(resolve => setImmediate(resolve))); itremote('works in nested calls', () => new Promise(resolve => { setImmediate(() => { setImmediate(() => setImmediate(resolve)); }); })); }); }); ifdescribe(process.platform === 'darwin')('net.connect', () => { itremote('emit error when connect to a socket path without listeners', async (fixtures: string) => { const socketPath = require('node:path').join(require('node:os').tmpdir(), 'electron-test.sock'); const script = require('node:path').join(fixtures, 'module', 'create_socket.js'); const child = require('node:child_process').fork(script, [socketPath]); const code = await new Promise(resolve => child.once('exit', resolve)); expect(code).to.equal(0); const client = require('node:net').connect(socketPath); const error = await new Promise<any>(resolve => client.once('error', resolve)); expect(error.code).to.equal('ECONNREFUSED'); }, [fixtures]); }); describe('Buffer', () => { useRemoteContext(); itremote('can be created from Blink external string', () => { const p = document.createElement('p'); p.innerText = '闲云潭影日悠悠,物换星移几度秋'; const b = Buffer.from(p.innerText); expect(b.toString()).to.equal('闲云潭影日悠悠,物换星移几度秋'); expect(Buffer.byteLength(p.innerText)).to.equal(45); }); itremote('correctly parses external one-byte UTF8 string', () => { const p = document.createElement('p'); p.innerText = 'Jøhänñéß'; const b = Buffer.from(p.innerText); expect(b.toString()).to.equal('Jøhänñéß'); expect(Buffer.byteLength(p.innerText)).to.equal(13); }); itremote('does not crash when creating large Buffers', () => { let buffer = Buffer.from(new Array(4096).join(' ')); expect(buffer.length).to.equal(4095); buffer = Buffer.from(new Array(4097).join(' ')); expect(buffer.length).to.equal(4096); }); itremote('does not crash for crypto operations', () => { const crypto = require('node:crypto'); const data = 'lG9E+/g4JmRmedDAnihtBD4Dfaha/GFOjd+xUOQI05UtfVX3DjUXvrS98p7kZQwY3LNhdiFo7MY5rGft8yBuDhKuNNag9vRx/44IuClDhdQ='; const key = 'q90K9yBqhWZnAMCMTOJfPQ=='; const cipherText = '{"error_code":114,"error_message":"Tham số không hợp lệ","data":null}'; for (let i = 0; i < 10000; ++i) { const iv = Buffer.from('0'.repeat(32), 'hex'); const input = Buffer.from(data, 'base64'); const decipher = crypto.createDecipheriv('aes-128-cbc', Buffer.from(key, 'base64'), iv); const result = Buffer.concat([decipher.update(input), decipher.final()]).toString('utf8'); expect(cipherText).to.equal(result); } }); itremote('does not crash when using crypto.diffieHellman() constructors', () => { const crypto = require('node:crypto'); crypto.createDiffieHellman('abc'); crypto.createDiffieHellman('abc', 2); // Needed to test specific DiffieHellman ctors. crypto.createDiffieHellman('abc', Buffer.from([2])); crypto.createDiffieHellman('abc', '123'); }); itremote('does not crash when calling crypto.createPrivateKey() with an unsupported algorithm', () => { const crypto = require('node:crypto'); const ed448 = { crv: 'Ed448', x: 'KYWcaDwgH77xdAwcbzOgvCVcGMy9I6prRQBhQTTdKXUcr-VquTz7Fd5adJO0wT2VHysF3bk3kBoA', d: 'UhC3-vN5vp_g9PnTknXZgfXUez7Xvw-OfuJ0pYkuwzpYkcTvacqoFkV_O05WMHpyXkzH9q2wzx5n', kty: 'OKP' }; expect(() => { crypto.createPrivateKey({ key: ed448, format: 'jwk' }); }).to.throw(/Invalid JWK data/); }); }); describe('process.stdout', () => { useRemoteContext(); itremote('does not throw an exception when accessed', () => { expect(() => process.stdout).to.not.throw(); }); itremote('does not throw an exception when calling write()', () => { expect(() => { process.stdout.write('test'); }).to.not.throw(); }); // TODO: figure out why process.stdout.isTTY is true on Darwin but not Linux/Win. ifdescribe(process.platform !== 'darwin')('isTTY', () => { itremote('should be undefined in the renderer process', function () { expect(process.stdout.isTTY).to.be.undefined(); }); }); }); describe('process.stdin', () => { useRemoteContext(); itremote('does not throw an exception when accessed', () => { expect(() => process.stdin).to.not.throw(); }); itremote('returns null when read from', () => { expect(process.stdin.read()).to.be.null(); }); }); describe('process.version', () => { itremote('should not have -pre', () => { expect(process.version.endsWith('-pre')).to.be.false(); }); }); describe('vm.runInNewContext', () => { itremote('should not crash', () => { require('node:vm').runInNewContext(''); }); }); describe('crypto', () => { useRemoteContext(); itremote('should list the ripemd160 hash in getHashes', () => { expect(require('node:crypto').getHashes()).to.include('ripemd160'); }); itremote('should be able to create a ripemd160 hash and use it', () => { const hash = require('node:crypto').createHash('ripemd160'); hash.update('electron-ripemd160'); expect(hash.digest('hex')).to.equal('fa7fec13c624009ab126ebb99eda6525583395fe'); }); itremote('should list aes-{128,256}-cfb in getCiphers', () => { expect(require('node:crypto').getCiphers()).to.include.members(['aes-128-cfb', 'aes-256-cfb']); }); itremote('should be able to create an aes-128-cfb cipher', () => { require('node:crypto').createCipheriv('aes-128-cfb', '0123456789abcdef', '0123456789abcdef'); }); itremote('should be able to create an aes-256-cfb cipher', () => { require('node:crypto').createCipheriv('aes-256-cfb', '0123456789abcdef0123456789abcdef', '0123456789abcdef'); }); itremote('should be able to create a bf-{cbc,cfb,ecb} ciphers', () => { require('node:crypto').createCipheriv('bf-cbc', Buffer.from('0123456789abcdef'), Buffer.from('01234567')); require('node:crypto').createCipheriv('bf-cfb', Buffer.from('0123456789abcdef'), Buffer.from('01234567')); require('node:crypto').createCipheriv('bf-ecb', Buffer.from('0123456789abcdef'), Buffer.from('01234567')); }); itremote('should list des-ede-cbc in getCiphers', () => { expect(require('node:crypto').getCiphers()).to.include('des-ede-cbc'); }); itremote('should be able to create an des-ede-cbc cipher', () => { const key = Buffer.from('0123456789abcdeff1e0d3c2b5a49786', 'hex'); const iv = Buffer.from('fedcba9876543210', 'hex'); require('node:crypto').createCipheriv('des-ede-cbc', key, iv); }); itremote('should not crash when getting an ECDH key', () => { const ecdh = require('node:crypto').createECDH('prime256v1'); expect(ecdh.generateKeys()).to.be.an.instanceof(Buffer); expect(ecdh.getPrivateKey()).to.be.an.instanceof(Buffer); }); itremote('should not crash when generating DH keys or fetching DH fields', () => { const dh = require('node:crypto').createDiffieHellman('modp15'); expect(dh.generateKeys()).to.be.an.instanceof(Buffer); expect(dh.getPublicKey()).to.be.an.instanceof(Buffer); expect(dh.getPrivateKey()).to.be.an.instanceof(Buffer); expect(dh.getPrime()).to.be.an.instanceof(Buffer); expect(dh.getGenerator()).to.be.an.instanceof(Buffer); }); itremote('should not crash when creating an ECDH cipher', () => { const crypto = require('node:crypto'); const dh = crypto.createECDH('prime256v1'); dh.generateKeys(); dh.setPrivateKey(dh.getPrivateKey()); }); }); itremote('includes the electron version in process.versions', () => { expect(process.versions) .to.have.own.property('electron') .that.is.a('string') .and.matches(/^\d+\.\d+\.\d+(\S*)?$/); }); itremote('includes the chrome version in process.versions', () => { expect(process.versions) .to.have.own.property('chrome') .that.is.a('string') .and.matches(/^\d+\.\d+\.\d+\.\d+$/); }); describe('NODE_OPTIONS', () => { let child: childProcess.ChildProcessWithoutNullStreams; let exitPromise: Promise<any[]>; it('Fails for options disallowed by Node.js itself', (done) => { after(async () => { const [code, signal] = await exitPromise; expect(signal).to.equal(null); // Exit code 9 indicates cli flag parsing failure expect(code).to.equal(9); child.kill(); }); const env = { ...process.env, NODE_OPTIONS: '--v8-options' }; child = childProcess.spawn(process.execPath, { env }); exitPromise = once(child, 'exit'); let output = ''; let success = false; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; const listener = (data: Buffer) => { output += data; if (/electron: --v8-options is not allowed in NODE_OPTIONS/m.test(output)) { success = true; cleanup(); done(); } }; child.stderr.on('data', listener); child.stdout.on('data', listener); child.on('exit', () => { if (!success) { cleanup(); done(new Error(`Unexpected output: ${output.toString()}`)); } }); }); it('Disallows crypto-related options', (done) => { after(() => { child.kill(); }); const appPath = path.join(fixtures, 'module', 'noop.js'); const env = { ...process.env, NODE_OPTIONS: '--use-openssl-ca' }; child = childProcess.spawn(process.execPath, ['--enable-logging', appPath], { env }); let output = ''; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; const listener = (data: Buffer) => { output += data; if (/The NODE_OPTION --use-openssl-ca is not supported in Electron/m.test(output)) { cleanup(); done(); } }; child.stderr.on('data', listener); child.stdout.on('data', listener); }); it('does allow --require in non-packaged apps', async () => { const appPath = path.join(fixtures, 'module', 'noop.js'); const env = { ...process.env, NODE_OPTIONS: `--require=${path.join(fixtures, 'module', 'fail.js')}` }; // App should exit with code 1. const child = childProcess.spawn(process.execPath, [appPath], { env }); const [code] = await once(child, 'exit'); expect(code).to.equal(1); }); it('does not allow --require in packaged apps', async () => { const appPath = path.join(fixtures, 'module', 'noop.js'); const env = { ...process.env, ELECTRON_FORCE_IS_PACKAGED: 'true', NODE_OPTIONS: `--require=${path.join(fixtures, 'module', 'fail.js')}` }; // App should exit with code 0. const child = childProcess.spawn(process.execPath, [appPath], { env }); const [code] = await once(child, 'exit'); expect(code).to.equal(0); }); }); describe('Node.js cli flags', () => { let child: childProcess.ChildProcessWithoutNullStreams; let exitPromise: Promise<any[]>; it('Prohibits crypto-related flags in ELECTRON_RUN_AS_NODE mode', (done) => { after(async () => { const [code, signal] = await exitPromise; expect(signal).to.equal(null); expect(code).to.equal(9); child.kill(); }); child = childProcess.spawn(process.execPath, ['--force-fips'], { env: { ELECTRON_RUN_AS_NODE: 'true' } }); exitPromise = once(child, 'exit'); let output = ''; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; const listener = (data: Buffer) => { output += data; if (/.*The Node.js cli flag --force-fips is not supported in Electron/m.test(output)) { cleanup(); done(); } }; child.stderr.on('data', listener); child.stdout.on('data', listener); }); }); describe('process.stdout', () => { it('is a real Node stream', () => { expect((process.stdout as any)._type).to.not.be.undefined(); }); }); describe('fs.readFile', () => { it('can accept a FileHandle as the Path argument', async () => { const filePathForHandle = path.resolve(mainFixturesPath, 'dogs-running.txt'); const fileHandle = await fs.promises.open(filePathForHandle, 'r'); const file = await fs.promises.readFile(fileHandle, { encoding: 'utf8' }); expect(file).to.not.be.empty(); await fileHandle.close(); }); }); describe('inspector', () => { let child: childProcess.ChildProcessWithoutNullStreams; let exitPromise: Promise<any[]> | null; afterEach(async () => { if (child && exitPromise) { const [code, signal] = await exitPromise; expect(signal).to.equal(null); expect(code).to.equal(0); } else if (child) { child.kill(); } child = null as any; exitPromise = null as any; }); it('Supports starting the v8 inspector with --inspect/--inspect-brk', (done) => { child = childProcess.spawn(process.execPath, ['--inspect-brk', path.join(fixtures, 'module', 'run-as-node.js')], { env: { ELECTRON_RUN_AS_NODE: 'true' } }); let output = ''; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; const listener = (data: Buffer) => { output += data; if (/Debugger listening on ws:/m.test(output)) { cleanup(); done(); } }; child.stderr.on('data', listener); child.stdout.on('data', listener); }); it('Supports starting the v8 inspector with --inspect and a provided port', async () => { child = childProcess.spawn(process.execPath, ['--inspect=17364', path.join(fixtures, 'module', 'run-as-node.js')], { env: { ELECTRON_RUN_AS_NODE: 'true' } }); exitPromise = once(child, 'exit'); let output = ''; const listener = (data: Buffer) => { output += data; }; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; child.stderr.on('data', listener); child.stdout.on('data', listener); await once(child, 'exit'); cleanup(); if (/^Debugger listening on ws:/m.test(output)) { expect(output.trim()).to.contain(':17364', 'should be listening on port 17364'); } else { throw new Error(`Unexpected output: ${output.toString()}`); } }); it('Does not start the v8 inspector when --inspect is after a -- argument', async () => { child = childProcess.spawn(process.execPath, [path.join(fixtures, 'module', 'noop.js'), '--', '--inspect']); exitPromise = once(child, 'exit'); let output = ''; const listener = (data: Buffer) => { output += data; }; child.stderr.on('data', listener); child.stdout.on('data', listener); await once(child, 'exit'); if (output.trim().startsWith('Debugger listening on ws://')) { throw new Error('Inspector was started when it should not have been'); } }); // IPC Electron child process not supported on Windows. ifit(process.platform !== 'win32')('does not crash when quitting with the inspector connected', function (done) { child = childProcess.spawn(process.execPath, [path.join(fixtures, 'module', 'delay-exit'), '--inspect=0'], { stdio: ['ipc'] }) as childProcess.ChildProcessWithoutNullStreams; exitPromise = once(child, 'exit'); const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; let output = ''; const success = false; function listener (data: Buffer) { output += data; console.log(data.toString()); // NOTE: temporary debug logging to try to catch flake. const match = /^Debugger listening on (ws:\/\/.+:\d+\/.+)\n/m.exec(output.trim()); if (match) { cleanup(); // NOTE: temporary debug logging to try to catch flake. child.stderr.on('data', (m) => console.log(m.toString())); child.stdout.on('data', (m) => console.log(m.toString())); const w = (webContents as typeof ElectronInternal.WebContents).create(); w.loadURL('about:blank') .then(() => w.executeJavaScript(`new Promise(resolve => { const connection = new WebSocket(${JSON.stringify(match[1])}) connection.onopen = () => { connection.onclose = () => resolve() connection.close() } })`)) .then(() => { w.destroy(); child.send('plz-quit'); done(); }); } } child.stderr.on('data', listener); child.stdout.on('data', listener); child.on('exit', () => { if (!success) cleanup(); }); }); it('Supports js binding', async () => { child = childProcess.spawn(process.execPath, ['--inspect', path.join(fixtures, 'module', 'inspector-binding.js')], { env: { ELECTRON_RUN_AS_NODE: 'true' }, stdio: ['ipc'] }) as childProcess.ChildProcessWithoutNullStreams; exitPromise = once(child, 'exit'); const [{ cmd, debuggerEnabled, success }] = await once(child, 'message'); expect(cmd).to.equal('assert'); expect(debuggerEnabled).to.be.true(); expect(success).to.be.true(); }); }); it('Can find a module using a package.json main field', () => { const result = childProcess.spawnSync(process.execPath, [path.resolve(fixtures, 'api', 'electron-main-module', 'app.asar')], { stdio: 'inherit' }); expect(result.status).to.equal(0); }); it('handles Promise timeouts correctly', async () => { const scriptPath = path.join(fixtures, 'module', 'node-promise-timer.js'); const child = childProcess.spawn(process.execPath, [scriptPath], { env: { ELECTRON_RUN_AS_NODE: 'true' } }); const [code, signal] = await once(child, 'exit'); expect(code).to.equal(0); expect(signal).to.equal(null); child.kill(); }); it('performs microtask checkpoint correctly', (done) => { const f3 = async () => { return new Promise((resolve, reject) => { reject(new Error('oops')); }); }; process.once('unhandledRejection', () => done(new Error('catch block is delayed to next tick'))); setTimeout(() => { f3().catch(() => done()); }); }); });
closed
electron/electron
https://github.com/electron/electron
40,354
[Bug]: Zoom controller doesn't persist when changing webviews
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.2 ### What operating system are you using? Windows ### Operating System Version Windows 11 Pro 22H2 - Build 22621.2428 ### What arch are you using? x64 ### Last Known Working Electron version 26.0.0 ### Expected Behavior When switching between different Webviews the Zoom scale persists after going back to the initial webview. ### Actual Behavior [Ferdium](https://github.com/ferdium/ferdium-app) currently uses multiple Webviews for each service it renders. When switching between Webviews the Zoom scale is not persistent (when switching away the zoom resets - this is visible for some milliseconds before changing to the other webview). ### Testcase Gist URL _No response_ ### Additional Information I'm logging this issue in Electron given that this was not present in past versions of Electron, but only after `26.0.0` (I'm blaming `26.1.0` as the version who started to cause issues). After some investigation it seems like the PR that caused this unwanted behaviour is: https://github.com/electron/electron/pull/39495 . Is it possible for you to search and revert this unwanted breakage? We would really need this to be fix because we have several users with this accessibility needs. Thank you very much in advance! PS: If this is not the proper way to open an issue on Electron please let me know.
https://github.com/electron/electron/issues/40354
https://github.com/electron/electron/pull/40650
66b4b216468feab79c7527295f2485067ea2cf15
10a165a9ff731137b679a4ef3a9e3d18bcdfd514
2023-10-27T12:40:22Z
c++
2023-12-04T15:39:20Z
spec/webview-spec.ts
import * as path from 'node:path'; import * as url from 'node:url'; import { BrowserWindow, session, ipcMain, app, WebContents } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import { emittedUntil } from './lib/events-helpers'; import { ifit, ifdescribe, defer, itremote, useRemoteContext, listen } from './lib/spec-helpers'; import { expect } from 'chai'; import * as http from 'node:http'; import * as auth from 'basic-auth'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; declare let WebView: any; const features = process._linkedBinding('electron_common_features'); async function loadWebView (w: WebContents, attributes: Record<string, string>, opts?: {openDevTools?: boolean}): Promise<void> { const { openDevTools } = { openDevTools: false, ...opts }; await w.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView() webview.id = 'webview' for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) { webview.setAttribute(k, v) } document.body.appendChild(webview) webview.addEventListener('dom-ready', () => { if (${openDevTools}) { webview.openDevTools() } }) webview.addEventListener('did-finish-load', () => { resolve() }) }) `); } async function loadWebViewAndWaitForEvent (w: WebContents, attributes: Record<string, string>, eventName: string): Promise<any> { return await w.executeJavaScript(`new Promise((resolve, reject) => { const webview = new WebView() webview.id = 'webview' for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) { webview.setAttribute(k, v) } webview.addEventListener(${JSON.stringify(eventName)}, (e) => resolve({...e}), {once: true}) document.body.appendChild(webview) })`); }; async function loadWebViewAndWaitForMessage (w: WebContents, attributes: Record<string, string>): Promise<string> { const { message } = await loadWebViewAndWaitForEvent(w, attributes, 'console-message'); return message; }; describe('<webview> tag', function () { const fixtures = path.join(__dirname, 'fixtures'); const blankPageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'blank.html')).toString(); function hideChildWindows (e: any, wc: WebContents) { wc.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false } })); } before(() => { app.on('web-contents-created', hideChildWindows); }); after(() => { app.off('web-contents-created', hideChildWindows); }); describe('behavior', () => { afterEach(closeAllWindows); it('works without script tag in page', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html')); await once(ipcMain, 'pong'); }); it('works with sandbox', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, sandbox: true } }); w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html')); await once(ipcMain, 'pong'); }); it('works with contextIsolation', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, contextIsolation: true } }); w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html')); await once(ipcMain, 'pong'); }); it('works with contextIsolation + sandbox', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, contextIsolation: true, sandbox: true } }); w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html')); await once(ipcMain, 'pong'); }); it('works with Trusted Types', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadFile(path.join(fixtures, 'pages', 'webview-trusted-types.html')); await once(ipcMain, 'pong'); }); it('is disabled by default', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'module', 'preload-webview.js'), nodeIntegration: true } }); const webview = once(ipcMain, 'webview'); w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html')); const [, type] = await webview; expect(type).to.equal('undefined', 'WebView still exists'); }); }); // FIXME(deepak1556): Ch69 follow up. xdescribe('document.visibilityState/hidden', () => { afterEach(() => { ipcMain.removeAllListeners('pong'); }); afterEach(closeAllWindows); it('updates when the window is shown after the ready-to-show event', async () => { const w = new BrowserWindow({ show: false }); const readyToShowSignal = once(w, 'ready-to-show'); const pongSignal1 = once(ipcMain, 'pong'); w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html')); await pongSignal1; const pongSignal2 = once(ipcMain, 'pong'); await readyToShowSignal; w.show(); const [, visibilityState, hidden] = await pongSignal2; expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false(); }); it('inherits the parent window visibility state and receives visibilitychange events', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true(); // We have to start waiting for the event // before we ask the webContents to resize. const getResponse = once(ipcMain, 'pong'); w.webContents.emit('-window-visibility-change', 'visible'); return getResponse.then(([, visibilityState, hidden]) => { expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false(); }); }); }); describe('did-attach-webview event', () => { afterEach(closeAllWindows); it('is emitted when a webview has been attached', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('did-attach event', () => { afterEach(closeAllWindows); it('is emitted when a webview has been attached', async () => { const w = new BrowserWindow({ webPreferences: { webviewTag: true } }); await w.loadURL('about:blank'); const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { const webview = new WebView() webview.setAttribute('src', 'about:blank') webview.addEventListener('did-attach', (e) => { resolve('ok') }) document.body.appendChild(webview) })`); expect(message).to.equal('ok'); }); }); describe('did-change-theme-color event', () => { afterEach(closeAllWindows); it('emits when theme color changes', async () => { const w = new BrowserWindow({ webPreferences: { webviewTag: true } }); await w.loadURL('about:blank'); const src = url.format({ pathname: `${fixtures.replaceAll('\\', '/')}/pages/theme-color.html`, protocol: 'file', slashes: true }); const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { const webview = new WebView() webview.setAttribute('src', '${src}') webview.addEventListener('did-change-theme-color', (e) => { resolve('ok') }) document.body.appendChild(webview) })`); expect(message).to.equal('ok'); }); }); describe('devtools', () => { afterEach(closeAllWindows); // FIXME: This test is flaky on WOA, so skip it there. ifit(process.platform !== 'win32' || process.arch !== 'arm64')('loads devtools extensions registered on the parent window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); w.webContents.session.removeExtension('foo'); const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo'); await w.webContents.session.loadExtension(extensionPath, { allowFileAccess: true }); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'webview-devtools.html')); loadWebView(w.webContents, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${path.join(__dirname, 'fixtures', 'blank.html')}` }, { openDevTools: true }); let childWebContentsId = 0; app.once('web-contents-created', (e, webContents) => { childWebContentsId = webContents.id; webContents.on('devtools-opened', function () { const showPanelIntervalId = setInterval(function () { if (!webContents.isDestroyed() && webContents.devToolsWebContents) { webContents.devToolsWebContents.executeJavaScript('(' + function () { const { EUI } = (window as any); const instance = EUI.InspectorView.InspectorView.instance(); const tabs = instance.tabbedPane.tabs; const lastPanelId: any = tabs[tabs.length - 1].id; instance.showPanel(lastPanelId); }.toString() + ')()'); } else { clearInterval(showPanelIntervalId); } }, 100); }); }); const [, { runtimeId, tabId }] = await once(ipcMain, 'answer'); expect(runtimeId).to.match(/^[a-z]{32}$/); expect(tabId).to.equal(childWebContentsId); await w.webContents.executeJavaScript('webview.closeDevTools()'); }); }); describe('zoom behavior', () => { const zoomScheme = standardScheme; const webviewSession = session.fromPartition('webview-temp'); afterEach(closeAllWindows); before(() => { const protocol = webviewSession.protocol; protocol.registerStringProtocol(zoomScheme, (request, callback) => { callback('hello'); }); }); after(() => { const protocol = webviewSession.protocol; protocol.unregisterProtocol(zoomScheme); }); it('inherits the zoomFactor of the parent window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, zoomFactor: 1.2, contextIsolation: false } }); const zoomEventPromise = once(ipcMain, 'webview-parent-zoom-level'); w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-factor.html')); const [, zoomFactor, zoomLevel] = await zoomEventPromise; expect(zoomFactor).to.equal(1.2); expect(zoomLevel).to.equal(1); }); it('maintains zoom level on navigation', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, zoomFactor: 1.2, contextIsolation: false } }); const promise = new Promise<void>((resolve) => { ipcMain.on('webview-zoom-level', (event, zoomLevel, zoomFactor, newHost, final) => { if (!newHost) { expect(zoomFactor).to.equal(1.44); expect(zoomLevel).to.equal(2.0); } else { expect(zoomFactor).to.equal(1.2); expect(zoomLevel).to.equal(1); } if (final) { resolve(); } }); }); w.loadFile(path.join(fixtures, 'pages', 'webview-custom-zoom-level.html')); await promise; }); it('maintains zoom level when navigating within same page', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, zoomFactor: 1.2, contextIsolation: false } }); const promise = new Promise<void>((resolve) => { ipcMain.on('webview-zoom-in-page', (event, zoomLevel, zoomFactor, final) => { expect(zoomFactor).to.equal(1.44); expect(zoomLevel).to.equal(2.0); if (final) { resolve(); } }); }); w.loadFile(path.join(fixtures, 'pages', 'webview-in-page-navigate.html')); await promise; }); it('inherits zoom level for the origin when available', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, zoomFactor: 1.2, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'webview-origin-zoom-level.html')); const [, zoomLevel] = await once(ipcMain, 'webview-origin-zoom-level'); expect(zoomLevel).to.equal(2.0); }); it('does not crash when navigating with zoom level inherited from parent', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, zoomFactor: 1.2, session: webviewSession, contextIsolation: false } }); const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const readyPromise = once(ipcMain, 'dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html')); const [, webview] = await attachPromise; await readyPromise; expect(webview.getZoomFactor()).to.equal(1.2); await w.loadURL(`${zoomScheme}://host1`); }); it('does not crash when changing zoom level after webview is destroyed', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, session: webviewSession, contextIsolation: false } }); const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; await w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html')); await attachPromise; await w.webContents.executeJavaScript('view.remove()'); w.webContents.setZoomLevel(0.5); }); }); describe('requestFullscreen from webview', () => { afterEach(closeAllWindows); async function loadWebViewWindow (): Promise<[BrowserWindow, WebContents]> { const w = new BrowserWindow({ webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const loadPromise = once(w.webContents, 'did-finish-load'); const readyPromise = once(ipcMain, 'webview-ready'); w.loadFile(path.join(__dirname, 'fixtures', 'webview', 'fullscreen', 'main.html')); const [, webview] = await attachPromise; await Promise.all([readyPromise, loadPromise]); return [w, webview]; }; afterEach(async () => { // The leaving animation is un-observable but can interfere with future tests // Specifically this is async on macOS but can be on other platforms too await setTimeout(1000); closeAllWindows(); }); ifit(process.platform !== 'darwin')('should make parent frame element fullscreen too (non-macOS)', async () => { const [w, webview] = await loadWebViewWindow(); expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false(); const parentFullscreen = once(ipcMain, 'fullscreenchange'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await parentFullscreen; expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true(); const close = once(w, 'closed'); w.close(); await close; }); ifit(process.platform === 'darwin')('should make parent frame element fullscreen too (macOS)', async () => { const [w, webview] = await loadWebViewWindow(); expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false(); const parentFullscreen = once(ipcMain, 'fullscreenchange'); const enterHTMLFS = once(w.webContents, 'enter-html-full-screen'); const leaveHTMLFS = once(w.webContents, 'leave-html-full-screen'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true(); await webview.executeJavaScript('document.exitFullscreen()'); await Promise.all([enterHTMLFS, leaveHTMLFS, parentFullscreen]); const close = once(w, 'closed'); w.close(); await close; }); // FIXME(zcbenz): Fullscreen events do not work on Linux. ifit(process.platform !== 'linux')('exiting fullscreen should unfullscreen window', async () => { const [w, webview] = await loadWebViewWindow(); const enterFullScreen = once(w, 'enter-full-screen'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); await webview.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; await setTimeout(); expect(w.isFullScreen()).to.be.false(); const close = once(w, 'closed'); w.close(); await close; }); it('pressing ESC should unfullscreen window', async () => { const [w, webview] = await loadWebViewWindow(); const enterFullScreen = once(w, 'enter-full-screen'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); webview.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); await leaveFullScreen; await setTimeout(1000); expect(w.isFullScreen()).to.be.false(); const close = once(w, 'closed'); w.close(); await close; }); it('pressing ESC should emit the leave-html-full-screen event', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const enterFSWindow = once(w, 'enter-html-full-screen'); const enterFSWebview = once(webContents, 'enter-html-full-screen'); await webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFSWindow; await enterFSWebview; const leaveFSWindow = once(w, 'leave-html-full-screen'); const leaveFSWebview = once(webContents, 'leave-html-full-screen'); webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); await leaveFSWebview; await leaveFSWindow; const close = once(w, 'closed'); w.close(); await close; }); it('should support user gesture', async () => { const [w, webview] = await loadWebViewWindow(); const waitForEnterHtmlFullScreen = once(webview, 'enter-html-full-screen'); const jsScript = "document.querySelector('video').webkitRequestFullscreen()"; webview.executeJavaScript(jsScript, true); await waitForEnterHtmlFullScreen; const close = once(w, 'closed'); w.close(); await close; }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('opens window of about:blank with cross-scripting enabled', async () => { // Don't wait for loading to finish. loadWebView(w.webContents, { allowpopups: 'on', nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${path.join(fixtures, 'api', 'native-window-open-blank.html')}` }); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { // Don't wait for loading to finish. loadWebView(w.webContents, { allowpopups: 'on', nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${path.join(fixtures, 'api', 'native-window-open-file.html')}` }); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); it('returns null from window.open when allowpopups is not set', async () => { // Don't wait for loading to finish. loadWebView(w.webContents, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${path.join(fixtures, 'api', 'native-window-open-no-allowpopups.html')}` }); const [, { windowOpenReturnedNull }] = await once(ipcMain, 'answer'); expect(windowOpenReturnedNull).to.be.true(); }); it('blocks accessing cross-origin frames', async () => { // Don't wait for loading to finish. loadWebView(w.webContents, { allowpopups: 'on', nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${path.join(fixtures, 'api', 'native-window-open-cross-origin.html')}` }); const [, content] = await once(ipcMain, 'answer'); const expectedContent = /Failed to read a named property 'toString' from 'Location': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./; expect(content).to.match(expectedContent); }); it('emits a browser-window-created event', async () => { // Don't wait for loading to finish. loadWebView(w.webContents, { allowpopups: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/window-open.html` }); await once(app, 'browser-window-created'); }); it('emits a web-contents-created event', async () => { const webContentsCreated = emittedUntil(app, 'web-contents-created', (event: Electron.Event, contents: Electron.WebContents) => contents.getType() === 'window'); loadWebView(w.webContents, { allowpopups: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/window-open.html` }); await webContentsCreated; }); it('does not crash when creating window with noopener', async () => { loadWebView(w.webContents, { allowpopups: 'on', src: `file://${path.join(fixtures, 'api', 'native-window-open-noopener.html')}` }); await once(app, 'browser-window-created'); }); }); describe('webpreferences attribute', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('can enable context isolation', async () => { loadWebView(w.webContents, { allowpopups: 'yes', preload: `file://${fixtures}/api/isolated-preload.js`, src: `file://${fixtures}/api/isolated.html`, webpreferences: 'contextIsolation=yes' }); const [, data] = await once(ipcMain, 'isolated-world'); expect(data).to.deep.equal({ 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' } }); }); }); describe('permission request handlers', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); const partition = 'permissionTest'; function setUpRequestHandler (webContentsId: number, requestedPermission: string) { return new Promise<void>((resolve, reject) => { session.fromPartition(partition).setPermissionRequestHandler(function (webContents, permission, callback) { if (webContents.id === webContentsId) { // requestMIDIAccess with sysex requests both midi and midiSysex so // grant the first midi one and then reject the midiSysex one if (requestedPermission === 'midiSysex' && permission === 'midi') { return callback(true); } try { expect(permission).to.equal(requestedPermission); } catch (e) { return reject(e); } callback(false); resolve(); } }); }); } afterEach(() => { session.fromPartition(partition).setPermissionRequestHandler(null); }); // This is disabled because CI machines don't have cameras or microphones, // so Chrome responds with "NotFoundError" instead of // "PermissionDeniedError". It should be re-enabled if we find a way to mock // the presence of a microphone & camera. xit('emits when using navigator.getUserMedia api', async () => { const errorFromRenderer = once(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/media.html`, partition, nodeintegration: 'on' }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; setUpRequestHandler(webViewContents.id, 'media'); const [, errorName] = await errorFromRenderer; expect(errorName).to.equal('PermissionDeniedError'); }); it('emits when using navigator.geolocation api', async () => { const errorFromRenderer = once(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/geolocation.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; setUpRequestHandler(webViewContents.id, 'geolocation'); const [, error] = await errorFromRenderer; expect(error).to.equal('User denied Geolocation'); }); it('emits when using navigator.requestMIDIAccess without sysex api', async () => { const errorFromRenderer = once(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/midi.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; setUpRequestHandler(webViewContents.id, 'midi'); const [, error] = await errorFromRenderer; expect(error).to.equal('SecurityError'); }); it('emits when using navigator.requestMIDIAccess with sysex api', async () => { const errorFromRenderer = once(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/midi-sysex.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; setUpRequestHandler(webViewContents.id, 'midiSysex'); const [, error] = await errorFromRenderer; expect(error).to.equal('SecurityError'); }); it('emits when accessing external protocol', async () => { loadWebView(w.webContents, { src: 'magnet:test', partition }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; await setUpRequestHandler(webViewContents.id, 'openExternal'); }); it('emits when using Notification.requestPermission', async () => { const errorFromRenderer = once(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/notification.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; await setUpRequestHandler(webViewContents.id, 'notifications'); const [, error] = await errorFromRenderer; expect(error).to.equal('denied'); }); }); describe('DOM events', () => { afterEach(closeAllWindows); it('receives extra properties on DOM events when contextIsolation is enabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, contextIsolation: true } }); await w.loadURL('about:blank'); const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { const webview = new WebView() webview.setAttribute('src', 'data:text/html,<script>console.log("hi")</script>') webview.addEventListener('console-message', (e) => { resolve(e.message) }) document.body.appendChild(webview) })`); expect(message).to.equal('hi'); }); it('emits focus event when contextIsolation is enabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, contextIsolation: true } }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { const webview = new WebView() webview.setAttribute('src', 'about:blank') webview.addEventListener('dom-ready', () => { webview.focus() }) webview.addEventListener('focus', () => { resolve(); }) document.body.appendChild(webview) })`); }); }); describe('attributes', () => { let w: WebContents; before(async () => { const window = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); await window.loadURL(`file://${fixtures}/pages/blank.html`); w = window.webContents; }); afterEach(async () => { await w.executeJavaScript(`{ for (const el of document.querySelectorAll('webview')) el.remove(); }`); }); after(closeAllWindows); describe('src attribute', () => { it('specifies the page to load', async () => { const message = await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/a.html` }); expect(message).to.equal('a'); }); it('navigates to new page when changed', async () => { await loadWebView(w, { src: `file://${fixtures}/pages/a.html` }); const { message } = await w.executeJavaScript(`new Promise(resolve => { webview.addEventListener('console-message', e => resolve({message: e.message})) webview.src = ${JSON.stringify(`file://${fixtures}/pages/b.html`)} })`); expect(message).to.equal('b'); }); it('resolves relative URLs', async () => { const message = await loadWebViewAndWaitForMessage(w, { src: './e.html' }); expect(message).to.equal('Window script is loaded before preload script'); }); it('ignores empty values', async () => { loadWebView(w, {}); for (const emptyValue of ['""', 'null', 'undefined']) { const src = await w.executeJavaScript(`webview.src = ${emptyValue}, webview.src`); expect(src).to.equal(''); } }); it('does not wait until loadURL is resolved', async () => { await loadWebView(w, { src: 'about:blank' }); const delay = await w.executeJavaScript(`new Promise(resolve => { const before = Date.now(); webview.src = 'file://${fixtures}/pages/blank.html'; const now = Date.now(); resolve(now - before); })`); // Setting src is essentially sending a sync IPC message, which should // not exceed more than a few ms. // // This is for testing #18638. expect(delay).to.be.below(100); }); }); describe('nodeintegration attribute', () => { it('inserts no node symbols when not set', async () => { const message = await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/c.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'undefined', module: 'undefined', process: 'undefined', global: 'undefined' }); }); it('inserts node symbols when set', async () => { const message = await loadWebViewAndWaitForMessage(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/d.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object' }); }); it('loads node symbols after POST navigation when set', async function () { const message = await loadWebViewAndWaitForMessage(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/post.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object' }); }); it('disables node integration on child windows when it is disabled on the webview', async () => { const src = url.format({ pathname: `${fixtures}/pages/webview-opener-no-node-integration.html`, protocol: 'file', query: { p: `${fixtures}/pages/window-opener-node.html` }, slashes: true }); const message = await loadWebViewAndWaitForMessage(w, { allowpopups: 'on', webpreferences: 'contextIsolation=no', src }); expect(JSON.parse(message).isProcessGlobalUndefined).to.be.true(); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native modules when navigation happens', async function () { await loadWebView(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/native-module.html` }); const message = await w.executeJavaScript(`new Promise(resolve => { webview.addEventListener('console-message', e => resolve(e.message)) webview.reload(); })`); expect(message).to.equal('function'); }); }); describe('preload attribute', () => { useRemoteContext({ webPreferences: { webviewTag: true } }); it('loads the script before other scripts in window', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: `${fixtures}/module/preload.js`, src: `file://${fixtures}/pages/e.html` }); expect(message).to.be.a('string'); expect(message).to.be.not.equal('Window script is loaded before preload script'); }); it('preload script can still use "process" and "Buffer" when nodeintegration is off', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: `${fixtures}/module/preload-node-off.js`, src: `file://${fixtures}/api/blank.html` }); const types = JSON.parse(message); expect(types).to.include({ process: 'object', Buffer: 'function' }); }); it('runs in the correct scope when sandboxed', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: `${fixtures}/module/preload-context.js`, src: `file://${fixtures}/api/blank.html`, webpreferences: 'sandbox=yes' }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', // arguments passed to it should be available electron: 'undefined', // objects from the scope it is called from should not be available window: 'object', // the window object should be available localVar: 'undefined' // but local variables should not be exposed to the window }); }); it('preload script can require modules that still use "process" and "Buffer" when nodeintegration is off', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: `${fixtures}/module/preload-node-off-wrapper.js`, webpreferences: 'sandbox=no', src: `file://${fixtures}/api/blank.html` }); const types = JSON.parse(message); expect(types).to.include({ process: 'object', Buffer: 'function' }); }); it('receives ipc message in preload script', async () => { await loadWebView(w, { preload: `${fixtures}/module/preload-ipc.js`, src: `file://${fixtures}/pages/e.html` }); const message = 'boom!'; const { channel, args } = await w.executeJavaScript(`new Promise(resolve => { webview.send('ping', ${JSON.stringify(message)}) webview.addEventListener('ipc-message', ({channel, args}) => resolve({channel, args})) })`); expect(channel).to.equal('pong'); expect(args).to.deep.equal([message]); }); itremote('<webview>.sendToFrame()', async (fixtures: string) => { const w = new WebView(); w.setAttribute('nodeintegration', 'on'); w.setAttribute('webpreferences', 'contextIsolation=no'); w.setAttribute('preload', `file://${fixtures}/module/preload-ipc.js`); w.setAttribute('src', `file://${fixtures}/pages/ipc-message.html`); document.body.appendChild(w); const { frameId } = await new Promise<any>(resolve => w.addEventListener('ipc-message', resolve, { once: true })); const message = 'boom!'; w.sendToFrame(frameId, 'ping', message); const { channel, args } = await new Promise<any>(resolve => w.addEventListener('ipc-message', resolve, { once: true })); expect(channel).to.equal('pong'); expect(args).to.deep.equal([message]); }, [fixtures]); it('works without script tag in page', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: `${fixtures}/module/preload.js`, webpreferences: 'sandbox=no', src: `file://${fixtures}/pages/base-page.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object', Buffer: 'function' }); }); it('resolves relative URLs', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: '../module/preload.js', webpreferences: 'sandbox=no', src: `file://${fixtures}/pages/e.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object', Buffer: 'function' }); }); itremote('ignores empty values', async () => { const webview = new WebView(); for (const emptyValue of ['', null, undefined]) { webview.preload = emptyValue; expect(webview.preload).to.equal(''); } }); }); describe('httpreferrer attribute', () => { it('sets the referrer url', async () => { const referrer = 'http://github.com/'; const received = await new Promise<string | undefined>((resolve, reject) => { const server = http.createServer((req, res) => { try { resolve(req.headers.referer); } catch (e) { reject(e); } finally { res.end(); server.close(); } }); listen(server).then(({ url }) => { loadWebView(w, { httpreferrer: referrer, src: url }); }); }); expect(received).to.equal(referrer); }); }); describe('useragent attribute', () => { it('sets the user agent', async () => { const referrer = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko'; const message = await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/useragent.html`, useragent: referrer }); expect(message).to.equal(referrer); }); }); describe('disablewebsecurity attribute', () => { it('does not disable web security when not set', async () => { await loadWebView(w, { src: 'about:blank' }); const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`); expect(result).to.equal('failed'); }); it('disables web security when set', async () => { await loadWebView(w, { src: 'about:blank', disablewebsecurity: '' }); const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`); expect(result).to.equal('ok'); }); it('does not break node integration', async () => { const message = await loadWebViewAndWaitForMessage(w, { disablewebsecurity: '', nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/d.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object' }); }); it('does not break preload script', async () => { const message = await loadWebViewAndWaitForMessage(w, { disablewebsecurity: '', preload: `${fixtures}/module/preload.js`, webpreferences: 'sandbox=no', src: `file://${fixtures}/pages/e.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object', Buffer: 'function' }); }); }); describe('partition attribute', () => { it('inserts no node symbols when not set', async () => { const message = await loadWebViewAndWaitForMessage(w, { partition: 'test1', src: `file://${fixtures}/pages/c.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'undefined', module: 'undefined', process: 'undefined', global: 'undefined' }); }); it('inserts node symbols when set', async () => { const message = await loadWebViewAndWaitForMessage(w, { nodeintegration: 'on', partition: 'test2', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/d.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object' }); }); it('isolates storage for different id', async () => { await w.executeJavaScript('localStorage.setItem(\'test\', \'one\')'); const message = await loadWebViewAndWaitForMessage(w, { partition: 'test3', src: `file://${fixtures}/pages/partition/one.html` }); const parsedMessage = JSON.parse(message); expect(parsedMessage).to.include({ numberOfEntries: 0, testValue: null }); }); it('uses current session storage when no id is provided', async () => { await w.executeJavaScript('localStorage.setItem(\'test\', \'two\')'); const testValue = 'two'; const message = await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/partition/one.html` }); const parsedMessage = JSON.parse(message); expect(parsedMessage).to.include({ testValue }); }); }); describe('allowpopups attribute', () => { const generateSpecs = (description: string, webpreferences = '') => { describe(description, () => { it('can not open new window when not set', async () => { const message = await loadWebViewAndWaitForMessage(w, { webpreferences, src: `file://${fixtures}/pages/window-open-hide.html` }); expect(message).to.equal('null'); }); it('can open new window when set', async () => { const message = await loadWebViewAndWaitForMessage(w, { webpreferences, allowpopups: 'on', src: `file://${fixtures}/pages/window-open-hide.html` }); expect(message).to.equal('window'); }); }); }; generateSpecs('without sandbox'); generateSpecs('with sandbox', 'sandbox=yes'); }); describe('webpreferences attribute', () => { it('can enable nodeintegration', async () => { const message = await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/d.html`, webpreferences: 'nodeIntegration,contextIsolation=no' }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object' }); }); it('can disable web security and enable nodeintegration', async () => { await loadWebView(w, { src: 'about:blank', webpreferences: 'webSecurity=no, nodeIntegration=yes, contextIsolation=no' }); const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`); expect(result).to.equal('ok'); const type = await w.executeJavaScript('webview.executeJavaScript("typeof require")'); expect(type).to.equal('function'); }); }); }); describe('events', () => { useRemoteContext({ webPreferences: { webviewTag: true } }); let w: WebContents; before(async () => { const window = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); await window.loadURL(`file://${fixtures}/pages/blank.html`); w = window.webContents; }); afterEach(async () => { await w.executeJavaScript(`{ for (const el of document.querySelectorAll('webview')) el.remove(); }`); }); after(closeAllWindows); describe('ipc-message event', () => { it('emits when guest sends an ipc message to browser', async () => { const { frameId, channel, args } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/ipc-message.html`, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }, 'ipc-message'); expect(frameId).to.be.an('array').that.has.lengthOf(2); expect(channel).to.equal('channel'); expect(args).to.deep.equal(['arg1', 'arg2']); }); }); describe('page-title-updated event', () => { it('emits when title is set', async () => { const { title, explicitSet } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/a.html` }, 'page-title-updated'); expect(title).to.equal('test'); expect(explicitSet).to.be.true(); }); }); describe('page-favicon-updated event', () => { it('emits when favicon urls are received', async () => { const { favicons } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/a.html` }, 'page-favicon-updated'); expect(favicons).to.be.an('array').of.length(2); if (process.platform === 'win32') { expect(favicons[0]).to.match(/^file:\/\/\/[A-Z]:\/favicon.png$/i); } else { expect(favicons[0]).to.equal('file:///favicon.png'); } }); }); describe('did-redirect-navigation event', () => { it('is emitted on redirects', async () => { const server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } }); const { url } = await listen(server); defer(() => { server.close(); }); const event = await loadWebViewAndWaitForEvent(w, { src: `${url}/302` }, 'did-redirect-navigation'); expect(event.url).to.equal(`${url}/200`); expect(event.isInPlace).to.be.false(); expect(event.isMainFrame).to.be.true(); expect(event.frameProcessId).to.be.a('number'); expect(event.frameRoutingId).to.be.a('number'); }); }); describe('will-navigate event', () => { it('emits when a url that leads to outside of the page is loaded', async () => { const { url } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/webview-will-navigate.html` }, 'will-navigate'); expect(url).to.equal('http://host/'); }); }); describe('will-frame-navigate event', () => { it('emits when a link that leads to outside of the page is loaded', async () => { const { url, isMainFrame } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/webview-will-navigate.html` }, 'will-frame-navigate'); expect(url).to.equal('http://host/'); expect(isMainFrame).to.be.true(); }); it('emits when a link within an iframe, which leads to outside of the page, is loaded', async () => { await loadWebView(w, { src: `file://${fixtures}/pages/webview-will-navigate-in-frame.html`, nodeIntegration: '' }); const { url, frameProcessId, frameRoutingId } = await w.executeJavaScript(` new Promise((resolve, reject) => { let hasFrameNavigatedOnce = false; const webview = document.getElementById('webview'); webview.addEventListener('will-frame-navigate', ({url, isMainFrame, frameProcessId, frameRoutingId}) => { if (isMainFrame) return; if (hasFrameNavigatedOnce) resolve({ url, isMainFrame, frameProcessId, frameRoutingId, }); // First navigation is the initial iframe load within the <webview> hasFrameNavigatedOnce = true; }); webview.executeJavaScript('loadSubframe()'); }); `); expect(url).to.equal('http://host/'); expect(frameProcessId).to.be.a('number'); expect(frameRoutingId).to.be.a('number'); }); }); describe('did-navigate event', () => { it('emits when a url that leads to outside of the page is clicked', async () => { const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-will-navigate.html')).toString(); const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate'); expect(event.url).to.equal(pageUrl); }); }); describe('did-navigate-in-page event', () => { it('emits when an anchor link is clicked', async () => { const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-did-navigate-in-page.html')).toString(); const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate-in-page'); expect(event.url).to.equal(`${pageUrl}#test_content`); }); it('emits when window.history.replaceState is called', async () => { const { url } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/webview-did-navigate-in-page-with-history.html` }, 'did-navigate-in-page'); expect(url).to.equal('http://host/'); }); it('emits when window.location.hash is changed', async () => { const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-did-navigate-in-page-with-hash.html')).toString(); const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate-in-page'); expect(event.url).to.equal(`${pageUrl}#test`); }); }); describe('close event', () => { it('should fire when interior page calls window.close', async () => { await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/close.html` }, 'close'); }); }); describe('devtools-opened event', () => { it('should fire when webview.openDevTools() is called', async () => { await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/base-page.html` }, 'dom-ready'); await w.executeJavaScript(`new Promise((resolve) => { webview.openDevTools() webview.addEventListener('devtools-opened', () => resolve(), {once: true}) })`); await w.executeJavaScript('webview.closeDevTools()'); }); }); describe('devtools-closed event', () => { itremote('should fire when webview.closeDevTools() is called', async (fixtures: string) => { const webview = new WebView(); webview.src = `file://${fixtures}/pages/base-page.html`; document.body.appendChild(webview); await new Promise(resolve => webview.addEventListener('dom-ready', resolve, { once: true })); webview.openDevTools(); await new Promise(resolve => webview.addEventListener('devtools-opened', resolve, { once: true })); webview.closeDevTools(); await new Promise(resolve => webview.addEventListener('devtools-closed', resolve, { once: true })); }, [fixtures]); }); describe('devtools-focused event', () => { itremote('should fire when webview.openDevTools() is called', async (fixtures: string) => { const webview = new WebView(); webview.src = `file://${fixtures}/pages/base-page.html`; document.body.appendChild(webview); const waitForDevToolsFocused = new Promise(resolve => webview.addEventListener('devtools-focused', resolve, { once: true })); await new Promise(resolve => webview.addEventListener('dom-ready', resolve, { once: true })); webview.openDevTools(); await waitForDevToolsFocused; webview.closeDevTools(); }, [fixtures]); }); describe('dom-ready event', () => { it('emits when document is loaded', async () => { const server = http.createServer(() => {}); const { port } = await listen(server); await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/dom-ready.html?port=${port}` }, 'dom-ready'); }); itremote('throws a custom error when an API method is called before the event is emitted', () => { const expectedErrorMessage = 'The WebView must be attached to the DOM ' + 'and the dom-ready event emitted before this method can be called.'; const webview = new WebView(); expect(() => { webview.stop(); }).to.throw(expectedErrorMessage); }); }); describe('context-menu event', () => { it('emits when right-clicked in page', async () => { await loadWebView(w, { src: 'about:blank' }); const { params, url } = await w.executeJavaScript(`new Promise(resolve => { webview.addEventListener('context-menu', (e) => resolve({...e, url: webview.getURL() }), {once: true}) // Simulate right-click to create context-menu event. const opts = { x: 0, y: 0, button: 'right' }; webview.sendInputEvent({ ...opts, type: 'mouseDown' }); webview.sendInputEvent({ ...opts, type: 'mouseUp' }); })`); expect(params.pageURL).to.equal(url); expect(params.frame).to.be.undefined(); expect(params.x).to.be.a('number'); expect(params.y).to.be.a('number'); }); }); describe('found-in-page event', () => { itremote('emits when a request is made', async (fixtures: string) => { const webview = new WebView(); const didFinishLoad = new Promise(resolve => webview.addEventListener('did-finish-load', resolve, { once: true })); webview.src = `file://${fixtures}/pages/content.html`; document.body.appendChild(webview); // TODO(deepak1556): With https://codereview.chromium.org/2836973002 // focus of the webContents is required when triggering the api. // Remove this workaround after determining the cause for // incorrect focus. webview.focus(); await didFinishLoad; const activeMatchOrdinal = []; for (;;) { const foundInPage = new Promise<any>(resolve => webview.addEventListener('found-in-page', resolve, { once: true })); const requestId = webview.findInPage('virtual'); const event = await foundInPage; expect(event.result.requestId).to.equal(requestId); expect(event.result.matches).to.equal(3); activeMatchOrdinal.push(event.result.activeMatchOrdinal); if (event.result.activeMatchOrdinal === event.result.matches) { break; } } expect(activeMatchOrdinal).to.deep.equal([1, 2, 3]); webview.stopFindInPage('clearSelection'); }, [fixtures]); }); describe('will-attach-webview event', () => { itremote('does not emit when src is not changed', async () => { const webview = new WebView(); document.body.appendChild(webview); await setTimeout(); const expectedErrorMessage = 'The WebView must be attached to the DOM and the dom-ready event emitted before this method can be called.'; expect(() => { webview.stop(); }).to.throw(expectedErrorMessage); }); it('supports changing the web preferences', async () => { w.once('will-attach-webview', (event, webPreferences, params) => { params.src = `file://${path.join(fixtures, 'pages', 'c.html')}`; webPreferences.nodeIntegration = false; }); const message = await loadWebViewAndWaitForMessage(w, { nodeintegration: 'yes', src: `file://${fixtures}/pages/a.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'undefined', module: 'undefined', process: 'undefined', global: 'undefined' }); }); it('handler modifying params.instanceId does not break <webview>', async () => { w.once('will-attach-webview', (event, webPreferences, params) => { params.instanceId = null as any; }); await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/a.html` }); }); it('supports preventing a webview from being created', async () => { w.once('will-attach-webview', event => event.preventDefault()); await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/c.html` }, 'destroyed'); }); it('supports removing the preload script', async () => { w.once('will-attach-webview', (event, webPreferences, params) => { params.src = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-stripped-preload.html')).toString(); delete webPreferences.preload; }); const message = await loadWebViewAndWaitForMessage(w, { nodeintegration: 'yes', preload: path.join(fixtures, 'module', 'preload-set-global.js'), src: `file://${fixtures}/pages/a.html` }); expect(message).to.equal('undefined'); }); }); describe('media-started-playing and media-paused events', () => { it('emits when audio starts and stops playing', async function () { if (!await w.executeJavaScript('document.createElement(\'audio\').canPlayType(\'audio/wav\')')) { return this.skip(); } await loadWebView(w, { src: blankPageUrl }); // With the new autoplay policy, audio elements must be unmuted // see https://goo.gl/xX8pDD. await w.executeJavaScript(`new Promise(resolve => { webview.executeJavaScript(\` const audio = document.createElement("audio") audio.src = "../assets/tone.wav" document.body.appendChild(audio); audio.play() \`, true) webview.addEventListener('media-started-playing', () => resolve(), {once: true}) })`); await w.executeJavaScript(`new Promise(resolve => { webview.executeJavaScript(\` document.querySelector("audio").pause() \`, true) webview.addEventListener('media-paused', () => resolve(), {once: true}) })`); }); }); }); describe('methods', () => { let w: WebContents; before(async () => { const window = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); await window.loadURL(`file://${fixtures}/pages/blank.html`); w = window.webContents; }); afterEach(async () => { await w.executeJavaScript(`{ for (const el of document.querySelectorAll('webview')) el.remove(); }`); }); after(closeAllWindows); describe('<webview>.reload()', () => { it('should emit beforeunload handler', async () => { await loadWebView(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/beforeunload-false.html` }); // Event handler has to be added before reload. const channel = await w.executeJavaScript(`new Promise(resolve => { webview.addEventListener('ipc-message', e => resolve(e.channel)) webview.reload(); })`); expect(channel).to.equal('onbeforeunload'); }); }); describe('<webview>.goForward()', () => { useRemoteContext({ webPreferences: { webviewTag: true } }); itremote('should work after a replaced history entry', async (fixtures: string) => { function waitForEvent (target: EventTarget, event: string) { return new Promise<any>(resolve => target.addEventListener(event, resolve, { once: true })); } function waitForEvents (target: EventTarget, ...events: string[]) { return Promise.all(events.map(event => waitForEvent(webview, event))); } const webview = new WebView(); webview.setAttribute('nodeintegration', 'on'); webview.setAttribute('webpreferences', 'contextIsolation=no'); webview.src = `file://${fixtures}/pages/history-replace.html`; document.body.appendChild(webview); { const [e] = await waitForEvents(webview, 'ipc-message', 'did-stop-loading'); expect(e.channel).to.equal('history'); expect(e.args[0]).to.equal(1); expect(webview.canGoBack()).to.be.false(); expect(webview.canGoForward()).to.be.false(); } webview.src = `file://${fixtures}/pages/base-page.html`; await new Promise<void>(resolve => webview.addEventListener('did-stop-loading', resolve, { once: true })); expect(webview.canGoBack()).to.be.true(); expect(webview.canGoForward()).to.be.false(); webview.goBack(); { const [e] = await waitForEvents(webview, 'ipc-message', 'did-stop-loading'); expect(e.channel).to.equal('history'); expect(e.args[0]).to.equal(2); expect(webview.canGoBack()).to.be.false(); expect(webview.canGoForward()).to.be.true(); } webview.goForward(); await new Promise<void>(resolve => webview.addEventListener('did-stop-loading', resolve, { once: true })); expect(webview.canGoBack()).to.be.true(); expect(webview.canGoForward()).to.be.false(); }, [fixtures]); }); describe('<webview>.clearHistory()', () => { it('should clear the navigation history', async () => { await loadWebView(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: blankPageUrl }); // Navigation must be triggered by a user gesture to make canGoBack() return true await w.executeJavaScript('webview.executeJavaScript(`history.pushState(null, "", "foo.html")`, true)'); expect(await w.executeJavaScript('webview.canGoBack()')).to.be.true(); await w.executeJavaScript('webview.clearHistory()'); expect(await w.executeJavaScript('webview.canGoBack()')).to.be.false(); }); }); describe('executeJavaScript', () => { it('can return the result of the executed script', async () => { await loadWebView(w, { src: 'about:blank' }); const jsScript = "'4'+2"; const expectedResult = '42'; const result = await w.executeJavaScript(`webview.executeJavaScript(${JSON.stringify(jsScript)})`); expect(result).to.equal(expectedResult); }); }); it('supports inserting CSS', async () => { await loadWebView(w, { src: `file://${fixtures}/pages/base-page.html` }); await w.executeJavaScript('webview.insertCSS(\'body { background-repeat: round; }\')'); const result = await w.executeJavaScript('webview.executeJavaScript(\'window.getComputedStyle(document.body).getPropertyValue("background-repeat")\')'); expect(result).to.equal('round'); }); it('supports removing inserted CSS', async () => { await loadWebView(w, { src: `file://${fixtures}/pages/base-page.html` }); const key = await w.executeJavaScript('webview.insertCSS(\'body { background-repeat: round; }\')'); await w.executeJavaScript(`webview.removeInsertedCSS(${JSON.stringify(key)})`); const result = await w.executeJavaScript('webview.executeJavaScript(\'window.getComputedStyle(document.body).getPropertyValue("background-repeat")\')'); expect(result).to.equal('repeat'); }); describe('sendInputEvent', () => { it('can send keyboard event', async () => { await loadWebViewAndWaitForEvent(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/onkeyup.html` }, 'dom-ready'); const waitForIpcMessage = w.executeJavaScript('new Promise(resolve => webview.addEventListener("ipc-message", e => resolve({...e})), {once: true})'); w.executeJavaScript(`webview.sendInputEvent({ type: 'keyup', keyCode: 'c', modifiers: ['shift'] })`); const { channel, args } = await waitForIpcMessage; expect(channel).to.equal('keyup'); expect(args).to.deep.equal(['C', 'KeyC', 67, true, false]); }); it('can send mouse event', async () => { await loadWebViewAndWaitForEvent(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/onmouseup.html` }, 'dom-ready'); const waitForIpcMessage = w.executeJavaScript('new Promise(resolve => webview.addEventListener("ipc-message", e => resolve({...e})), {once: true})'); w.executeJavaScript(`webview.sendInputEvent({ type: 'mouseup', modifiers: ['ctrl'], x: 10, y: 20 })`); const { channel, args } = await waitForIpcMessage; expect(channel).to.equal('mouseup'); expect(args).to.deep.equal([10, 20, false, true]); }); }); describe('<webview>.getWebContentsId', () => { it('can return the WebContents ID', async () => { await loadWebView(w, { src: 'about:blank' }); expect(await w.executeJavaScript('webview.getWebContentsId()')).to.be.a('number'); }); }); ifdescribe(features.isPrintingEnabled())('<webview>.printToPDF()', () => { it('rejects on incorrectly typed parameters', async () => { const badTypes = { landscape: [], displayHeaderFooter: '123', printBackground: 2, scale: 'not-a-number', pageSize: 'IAmAPageSize', margins: 'terrible', pageRanges: { oops: 'im-not-the-right-key' }, headerTemplate: [1, 2, 3], footerTemplate: [4, 5, 6], preferCSSPageSize: 'no' }; // These will hard crash in Chromium unless we type-check for (const [key, value] of Object.entries(badTypes)) { const param = { [key]: value }; const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'; await loadWebView(w, { src }); await expect(w.executeJavaScript(`webview.printToPDF(${JSON.stringify(param)})`)).to.eventually.be.rejected(); } }); it('can print to PDF', async () => { const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'; await loadWebView(w, { src }); const data = await w.executeJavaScript('webview.printToPDF({})'); expect(data).to.be.an.instanceof(Uint8Array).that.is.not.empty(); }); }); describe('DOM events', () => { for (const [description, sandbox] of [ ['without sandbox', false] as const, ['with sandbox', true] as const ]) { describe(description, () => { it('emits focus event', async () => { await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/a.html`, webpreferences: `sandbox=${sandbox ? 'yes' : 'no'}` }, 'dom-ready'); // If this test fails, check if webview.focus() still works. await w.executeJavaScript(`new Promise(resolve => { webview.addEventListener('focus', () => resolve(), {once: true}); webview.focus(); })`); }); }); } }); // TODO(miniak): figure out why this is failing on windows ifdescribe(process.platform !== 'win32')('<webview>.capturePage()', () => { it('returns a Promise with a NativeImage', async function () { this.retries(5); const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'; await loadWebViewAndWaitForEvent(w, { src }, 'did-stop-loading'); const image = await w.executeJavaScript('webview.capturePage()'); expect(image.isEmpty()).to.be.false(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha const imgBuffer = image.toPNG(); expect(imgBuffer[25]).to.equal(6); }); it('returns a Promise with a NativeImage in the renderer', async function () { this.retries(5); const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'; await loadWebViewAndWaitForEvent(w, { src }, 'did-stop-loading'); const byte = await w.executeJavaScript(`new Promise(resolve => { webview.capturePage().then(image => { resolve(image.toPNG()[25]) }); })`); expect(byte).to.equal(6); }); }); // FIXME(zcbenz): Disabled because of moving to OOPIF webview. xdescribe('setDevToolsWebContents() API', () => { /* it('sets webContents of webview as devtools', async () => { const webview2 = new WebView(); loadWebView(webview2); // Setup an event handler for further usage. const waitForDomReady = waitForEvent(webview2, 'dom-ready'); loadWebView(webview, { src: 'about:blank' }); await waitForEvent(webview, 'dom-ready'); webview.getWebContents().setDevToolsWebContents(webview2.getWebContents()); webview.getWebContents().openDevTools(); await waitForDomReady; // Its WebContents should be a DevTools. const devtools = webview2.getWebContents(); expect(devtools.getURL().startsWith('devtools://devtools')).to.be.true(); const name = await devtools.executeJavaScript('InspectorFrontendHost.constructor.name'); document.body.removeChild(webview2); expect(name).to.be.equal('InspectorFrontendHostImpl'); }); */ }); }); describe('basic auth', () => { let w: WebContents; before(async () => { const window = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); await window.loadURL(`file://${fixtures}/pages/blank.html`); w = window.webContents; }); afterEach(async () => { await w.executeJavaScript(`{ for (const el of document.querySelectorAll('webview')) el.remove(); }`); }); after(closeAllWindows); it('should authenticate with correct credentials', async () => { const message = 'Authenticated'; const server = http.createServer((req, res) => { const credentials = auth(req)!; if (credentials.name === 'test' && credentials.pass === 'test') { res.end(message); } else { res.end('failed'); } }); defer(() => { server.close(); }); const { port } = await listen(server); const e = await loadWebViewAndWaitForEvent(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/basic-auth.html?port=${port}` }, 'ipc-message'); expect(e.channel).to.equal(message); }); }); });
closed
electron/electron
https://github.com/electron/electron
40,354
[Bug]: Zoom controller doesn't persist when changing webviews
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.2 ### What operating system are you using? Windows ### Operating System Version Windows 11 Pro 22H2 - Build 22621.2428 ### What arch are you using? x64 ### Last Known Working Electron version 26.0.0 ### Expected Behavior When switching between different Webviews the Zoom scale persists after going back to the initial webview. ### Actual Behavior [Ferdium](https://github.com/ferdium/ferdium-app) currently uses multiple Webviews for each service it renders. When switching between Webviews the Zoom scale is not persistent (when switching away the zoom resets - this is visible for some milliseconds before changing to the other webview). ### Testcase Gist URL _No response_ ### Additional Information I'm logging this issue in Electron given that this was not present in past versions of Electron, but only after `26.0.0` (I'm blaming `26.1.0` as the version who started to cause issues). After some investigation it seems like the PR that caused this unwanted behaviour is: https://github.com/electron/electron/pull/39495 . Is it possible for you to search and revert this unwanted breakage? We would really need this to be fix because we have several users with this accessibility needs. Thank you very much in advance! PS: If this is not the proper way to open an issue on Electron please let me know.
https://github.com/electron/electron/issues/40354
https://github.com/electron/electron/pull/40650
66b4b216468feab79c7527295f2485067ea2cf15
10a165a9ff731137b679a4ef3a9e3d18bcdfd514
2023-10-27T12:40:22Z
c++
2023-12-04T15:39:20Z
shell/browser/web_contents_zoom_controller.cc
// Copyright (c) 2017 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/web_contents_zoom_controller.h" #include <string> #include "content/public/browser/browser_thread.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/web_contents.h" #include "content/public/browser/web_contents_user_data.h" #include "content/public/common/page_type.h" #include "net/base/url_util.h" #include "shell/browser/web_contents_zoom_observer.h" #include "third_party/blink/public/common/page/page_zoom.h" using content::BrowserThread; namespace electron { namespace { const double kPageZoomEpsilon = 0.001; } // namespace WebContentsZoomController::WebContentsZoomController( content::WebContents* web_contents) : content::WebContentsObserver(web_contents), content::WebContentsUserData<WebContentsZoomController>(*web_contents) { DCHECK_CURRENTLY_ON(BrowserThread::UI); host_zoom_map_ = content::HostZoomMap::GetForWebContents(web_contents); zoom_level_ = host_zoom_map_->GetDefaultZoomLevel(); default_zoom_factor_ = kPageZoomEpsilon; zoom_subscription_ = host_zoom_map_->AddZoomLevelChangedCallback( base::BindRepeating(&WebContentsZoomController::OnZoomLevelChanged, base::Unretained(this))); UpdateState(std::string()); } WebContentsZoomController::~WebContentsZoomController() { DCHECK_CURRENTLY_ON(BrowserThread::UI); for (auto& observer : observers_) { observer.OnZoomControllerDestroyed(this); } } void WebContentsZoomController::AddObserver(WebContentsZoomObserver* observer) { DCHECK_CURRENTLY_ON(BrowserThread::UI); observers_.AddObserver(observer); } void WebContentsZoomController::RemoveObserver( WebContentsZoomObserver* observer) { DCHECK_CURRENTLY_ON(BrowserThread::UI); observers_.RemoveObserver(observer); } void WebContentsZoomController::SetEmbedderZoomController( WebContentsZoomController* controller) { DCHECK_CURRENTLY_ON(BrowserThread::UI); embedder_zoom_controller_ = controller; } bool WebContentsZoomController::SetZoomLevel(double level) { DCHECK_CURRENTLY_ON(BrowserThread::UI); content::NavigationEntry* entry = web_contents()->GetController().GetLastCommittedEntry(); // Cannot zoom in disabled mode. Also, don't allow changing zoom level on // a crashed tab, an error page or an interstitial page. if (zoom_mode_ == ZOOM_MODE_DISABLED || !web_contents()->GetPrimaryMainFrame()->IsRenderFrameLive()) return false; // Do not actually rescale the page in manual mode. if (zoom_mode_ == ZOOM_MODE_MANUAL) { // If the zoom level hasn't changed, early out to avoid sending an event. if (blink::PageZoomValuesEqual(zoom_level_, level)) return true; double old_zoom_level = zoom_level_; zoom_level_ = level; ZoomChangedEventData zoom_change_data(web_contents(), old_zoom_level, zoom_level_, false /* temporary */, zoom_mode_); for (auto& observer : observers_) observer.OnZoomChanged(zoom_change_data); return true; } content::HostZoomMap* zoom_map = content::HostZoomMap::GetForWebContents(web_contents()); DCHECK(zoom_map); DCHECK(!event_data_); event_data_ = std::make_unique<ZoomChangedEventData>( web_contents(), GetZoomLevel(), level, false /* temporary */, zoom_mode_); content::GlobalRenderFrameHostId rfh_id = web_contents()->GetPrimaryMainFrame()->GetGlobalId(); if (zoom_mode_ == ZOOM_MODE_ISOLATED || zoom_map->UsesTemporaryZoomLevel(rfh_id)) { zoom_map->SetTemporaryZoomLevel(rfh_id, level); ZoomChangedEventData zoom_change_data(web_contents(), zoom_level_, level, true /* temporary */, zoom_mode_); for (auto& observer : observers_) observer.OnZoomChanged(zoom_change_data); } else { if (!entry) { // If we exit without triggering an update, we should clear event_data_, // else we may later trigger a DCHECK(event_data_). event_data_.reset(); return false; } std::string host = net::GetHostOrSpecFromURL(content::HostZoomMap::GetURLFromEntry(entry)); zoom_map->SetZoomLevelForHost(host, level); } DCHECK(!event_data_); return true; } double WebContentsZoomController::GetZoomLevel() const { DCHECK_CURRENTLY_ON(BrowserThread::UI); return zoom_mode_ == ZOOM_MODE_MANUAL ? zoom_level_ : content::HostZoomMap::GetZoomLevel(web_contents()); } void WebContentsZoomController::SetDefaultZoomFactor(double factor) { default_zoom_factor_ = factor; } double WebContentsZoomController::GetDefaultZoomFactor() { return default_zoom_factor_; } void WebContentsZoomController::SetTemporaryZoomLevel(double level) { DCHECK_CURRENTLY_ON(BrowserThread::UI); content::GlobalRenderFrameHostId old_rfh_id_ = web_contents()->GetPrimaryMainFrame()->GetGlobalId(); host_zoom_map_->SetTemporaryZoomLevel(old_rfh_id_, level); // Notify observers of zoom level changes. ZoomChangedEventData zoom_change_data(web_contents(), zoom_level_, level, true /* temporary */, zoom_mode_); for (WebContentsZoomObserver& observer : observers_) observer.OnZoomChanged(zoom_change_data); } bool WebContentsZoomController::UsesTemporaryZoomLevel() { DCHECK_CURRENTLY_ON(BrowserThread::UI); content::GlobalRenderFrameHostId rfh_id = web_contents()->GetPrimaryMainFrame()->GetGlobalId(); return host_zoom_map_->UsesTemporaryZoomLevel(rfh_id); } void WebContentsZoomController::SetZoomMode(ZoomMode new_mode) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (new_mode == zoom_mode_) return; content::HostZoomMap* zoom_map = content::HostZoomMap::GetForWebContents(web_contents()); DCHECK(zoom_map); content::GlobalRenderFrameHostId rfh_id = web_contents()->GetPrimaryMainFrame()->GetGlobalId(); double original_zoom_level = GetZoomLevel(); DCHECK(!event_data_); event_data_ = std::make_unique<ZoomChangedEventData>( web_contents(), original_zoom_level, original_zoom_level, false /* temporary */, new_mode); switch (new_mode) { case ZOOM_MODE_DEFAULT: { content::NavigationEntry* entry = web_contents()->GetController().GetLastCommittedEntry(); if (entry) { GURL url = content::HostZoomMap::GetURLFromEntry(entry); std::string host = net::GetHostOrSpecFromURL(url); if (zoom_map->HasZoomLevel(url.scheme(), host)) { // If there are other tabs with the same origin, then set this tab's // zoom level to match theirs. The temporary zoom level will be // cleared below, but this call will make sure this tab re-draws at // the correct zoom level. double origin_zoom_level = zoom_map->GetZoomLevelForHostAndScheme(url.scheme(), host); event_data_->new_zoom_level = origin_zoom_level; zoom_map->SetTemporaryZoomLevel(rfh_id, origin_zoom_level); } else { // The host will need a level prior to removing the temporary level. // We don't want the zoom level to change just because we entered // default mode. zoom_map->SetZoomLevelForHost(host, original_zoom_level); } } // Remove per-tab zoom data for this tab. No event callback expected. zoom_map->ClearTemporaryZoomLevel(rfh_id); break; } case ZOOM_MODE_ISOLATED: { // Unless the zoom mode was |ZOOM_MODE_DISABLED| before this call, the // page needs an initial isolated zoom back to the same level it was at // in the other mode. if (zoom_mode_ != ZOOM_MODE_DISABLED) { zoom_map->SetTemporaryZoomLevel(rfh_id, original_zoom_level); } else { // When we don't call any HostZoomMap set functions, we send the event // manually. for (auto& observer : observers_) observer.OnZoomChanged(*event_data_); event_data_.reset(); } break; } case ZOOM_MODE_MANUAL: { // Unless the zoom mode was |ZOOM_MODE_DISABLED| before this call, the // page needs to be resized to the default zoom. While in manual mode, // the zoom level is handled independently. if (zoom_mode_ != ZOOM_MODE_DISABLED) { zoom_map->SetTemporaryZoomLevel(rfh_id, GetDefaultZoomLevel()); zoom_level_ = original_zoom_level; } else { // When we don't call any HostZoomMap set functions, we send the event // manually. for (auto& observer : observers_) observer.OnZoomChanged(*event_data_); event_data_.reset(); } break; } case ZOOM_MODE_DISABLED: { // The page needs to be zoomed back to default before disabling the zoom double new_zoom_level = GetDefaultZoomLevel(); event_data_->new_zoom_level = new_zoom_level; zoom_map->SetTemporaryZoomLevel(rfh_id, new_zoom_level); break; } } // Any event data we've stored should have been consumed by this point. DCHECK(!event_data_); zoom_mode_ = new_mode; } void WebContentsZoomController::ResetZoomModeOnNavigationIfNeeded( const GURL& url) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (zoom_mode_ != ZOOM_MODE_ISOLATED && zoom_mode_ != ZOOM_MODE_MANUAL) return; content::HostZoomMap* zoom_map = content::HostZoomMap::GetForWebContents(web_contents()); zoom_level_ = zoom_map->GetDefaultZoomLevel(); double old_zoom_level = zoom_map->GetZoomLevel(web_contents()); double new_zoom_level = zoom_map->GetZoomLevelForHostAndScheme( url.scheme(), net::GetHostOrSpecFromURL(url)); event_data_ = std::make_unique<ZoomChangedEventData>( web_contents(), old_zoom_level, new_zoom_level, false, ZOOM_MODE_DEFAULT); // The call to ClearTemporaryZoomLevel() doesn't generate any events from // HostZoomMap, but the call to UpdateState() at the end of // DidFinishNavigation will notify our observers. // Note: it's possible the render_process/frame ids have disappeared (e.g. // if we navigated to a new origin), but this won't cause a problem in the // call below. zoom_map->ClearTemporaryZoomLevel( web_contents()->GetPrimaryMainFrame()->GetGlobalId()); zoom_mode_ = ZOOM_MODE_DEFAULT; } void WebContentsZoomController::DidFinishNavigation( content::NavigationHandle* navigation_handle) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!navigation_handle->IsInPrimaryMainFrame() || !navigation_handle->HasCommitted()) { return; } if (navigation_handle->IsErrorPage()) content::HostZoomMap::SendErrorPageZoomLevelRefresh(web_contents()); if (!navigation_handle->IsSameDocument()) { ResetZoomModeOnNavigationIfNeeded(navigation_handle->GetURL()); SetZoomFactorOnNavigationIfNeeded(navigation_handle->GetURL()); } // If the main frame's content has changed, the new page may have a different // zoom level from the old one. UpdateState(std::string()); DCHECK(!event_data_); } void WebContentsZoomController::WebContentsDestroyed() { DCHECK_CURRENTLY_ON(BrowserThread::UI); // At this point we should no longer be sending any zoom events with this // WebContents. for (auto& observer : observers_) { observer.OnZoomControllerDestroyed(this); } embedder_zoom_controller_ = nullptr; } void WebContentsZoomController::RenderFrameHostChanged( content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // If our associated HostZoomMap changes, update our subscription. content::HostZoomMap* new_host_zoom_map = content::HostZoomMap::GetForWebContents(web_contents()); if (new_host_zoom_map == host_zoom_map_) return; host_zoom_map_ = new_host_zoom_map; zoom_subscription_ = host_zoom_map_->AddZoomLevelChangedCallback( base::BindRepeating(&WebContentsZoomController::OnZoomLevelChanged, base::Unretained(this))); } void WebContentsZoomController::SetZoomFactorOnNavigationIfNeeded( const GURL& url) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (blink::PageZoomValuesEqual(GetDefaultZoomFactor(), kPageZoomEpsilon)) return; content::GlobalRenderFrameHostId old_rfh_id_ = content::GlobalRenderFrameHostId(old_process_id_, old_view_id_); if (host_zoom_map_->UsesTemporaryZoomLevel(old_rfh_id_)) { host_zoom_map_->ClearTemporaryZoomLevel(old_rfh_id_); } if (embedder_zoom_controller_ && embedder_zoom_controller_->UsesTemporaryZoomLevel()) { double level = embedder_zoom_controller_->GetZoomLevel(); SetTemporaryZoomLevel(level); return; } // When kZoomFactor is available, it takes precedence over // pref store values but if the host has zoom factor set explicitly // then it takes precedence. // pref store < kZoomFactor < setZoomLevel std::string host = net::GetHostOrSpecFromURL(url); std::string scheme = url.scheme(); double zoom_factor = GetDefaultZoomFactor(); double zoom_level = blink::PageZoomFactorToZoomLevel(zoom_factor); if (host_zoom_map_->HasZoomLevel(scheme, host)) { zoom_level = host_zoom_map_->GetZoomLevelForHostAndScheme(scheme, host); } if (blink::PageZoomValuesEqual(zoom_level, GetZoomLevel())) return; SetZoomLevel(zoom_level); } void WebContentsZoomController::OnZoomLevelChanged( const content::HostZoomMap::ZoomLevelChange& change) { DCHECK_CURRENTLY_ON(BrowserThread::UI); UpdateState(change.host); } void WebContentsZoomController::UpdateState(const std::string& host) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // If |host| is empty, all observers should be updated. if (!host.empty()) { // Use the navigation entry's URL instead of the WebContents' so virtual // URLs work (e.g. chrome://settings). http://crbug.com/153950 content::NavigationEntry* entry = web_contents()->GetController().GetLastCommittedEntry(); if (!entry || host != net::GetHostOrSpecFromURL( content::HostZoomMap::GetURLFromEntry(entry))) { return; } } if (event_data_) { // For state changes initiated within the ZoomController, information about // the change should be sent. ZoomChangedEventData zoom_change_data = *event_data_; event_data_.reset(); for (auto& observer : observers_) observer.OnZoomChanged(zoom_change_data); } else { double zoom_level = GetZoomLevel(); ZoomChangedEventData zoom_change_data(web_contents(), zoom_level, zoom_level, false, zoom_mode_); for (auto& observer : observers_) observer.OnZoomChanged(zoom_change_data); } } WEB_CONTENTS_USER_DATA_KEY_IMPL(WebContentsZoomController); } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,354
[Bug]: Zoom controller doesn't persist when changing webviews
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.2 ### What operating system are you using? Windows ### Operating System Version Windows 11 Pro 22H2 - Build 22621.2428 ### What arch are you using? x64 ### Last Known Working Electron version 26.0.0 ### Expected Behavior When switching between different Webviews the Zoom scale persists after going back to the initial webview. ### Actual Behavior [Ferdium](https://github.com/ferdium/ferdium-app) currently uses multiple Webviews for each service it renders. When switching between Webviews the Zoom scale is not persistent (when switching away the zoom resets - this is visible for some milliseconds before changing to the other webview). ### Testcase Gist URL _No response_ ### Additional Information I'm logging this issue in Electron given that this was not present in past versions of Electron, but only after `26.0.0` (I'm blaming `26.1.0` as the version who started to cause issues). After some investigation it seems like the PR that caused this unwanted behaviour is: https://github.com/electron/electron/pull/39495 . Is it possible for you to search and revert this unwanted breakage? We would really need this to be fix because we have several users with this accessibility needs. Thank you very much in advance! PS: If this is not the proper way to open an issue on Electron please let me know.
https://github.com/electron/electron/issues/40354
https://github.com/electron/electron/pull/40650
66b4b216468feab79c7527295f2485067ea2cf15
10a165a9ff731137b679a4ef3a9e3d18bcdfd514
2023-10-27T12:40:22Z
c++
2023-12-04T15:39:20Z
spec/fixtures/pages/webview-zoom-change-persist-host.html
closed
electron/electron
https://github.com/electron/electron
40,354
[Bug]: Zoom controller doesn't persist when changing webviews
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.2 ### What operating system are you using? Windows ### Operating System Version Windows 11 Pro 22H2 - Build 22621.2428 ### What arch are you using? x64 ### Last Known Working Electron version 26.0.0 ### Expected Behavior When switching between different Webviews the Zoom scale persists after going back to the initial webview. ### Actual Behavior [Ferdium](https://github.com/ferdium/ferdium-app) currently uses multiple Webviews for each service it renders. When switching between Webviews the Zoom scale is not persistent (when switching away the zoom resets - this is visible for some milliseconds before changing to the other webview). ### Testcase Gist URL _No response_ ### Additional Information I'm logging this issue in Electron given that this was not present in past versions of Electron, but only after `26.0.0` (I'm blaming `26.1.0` as the version who started to cause issues). After some investigation it seems like the PR that caused this unwanted behaviour is: https://github.com/electron/electron/pull/39495 . Is it possible for you to search and revert this unwanted breakage? We would really need this to be fix because we have several users with this accessibility needs. Thank you very much in advance! PS: If this is not the proper way to open an issue on Electron please let me know.
https://github.com/electron/electron/issues/40354
https://github.com/electron/electron/pull/40650
66b4b216468feab79c7527295f2485067ea2cf15
10a165a9ff731137b679a4ef3a9e3d18bcdfd514
2023-10-27T12:40:22Z
c++
2023-12-04T15:39:20Z
spec/node-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as fs from 'node:fs'; import * as path from 'node:path'; import * as util from 'node:util'; import { getRemoteContext, ifdescribe, ifit, itremote, useRemoteContext } from './lib/spec-helpers'; import { webContents } from 'electron/main'; import { EventEmitter } from 'node:stream'; import { once } from 'node:events'; const mainFixturesPath = path.resolve(__dirname, 'fixtures'); describe('node feature', () => { const fixtures = path.join(__dirname, 'fixtures'); describe('child_process', () => { describe('child_process.fork', () => { it('Works in browser process', async () => { const child = childProcess.fork(path.join(fixtures, 'module', 'ping.js')); const message = once(child, 'message'); child.send('message'); const [msg] = await message; expect(msg).to.equal('message'); }); }); }); describe('child_process in renderer', () => { useRemoteContext(); describe('child_process.fork', () => { itremote('works in current process', async (fixtures: string) => { const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'ping.js')); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.equal('message'); }, [fixtures]); itremote('preserves args', async (fixtures: string) => { const args = ['--expose_gc', '-test', '1']; const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'process_args.js'), args); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(args).to.deep.equal(msg.slice(2)); }, [fixtures]); itremote('works in forked process', async (fixtures: string) => { const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'fork_ping.js')); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.equal('message'); }, [fixtures]); itremote('works in forked process when options.env is specified', async (fixtures: string) => { const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'fork_ping.js'), [], { path: process.env.PATH }); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.equal('message'); }, [fixtures]); itremote('has String::localeCompare working in script', async (fixtures: string) => { const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'locale-compare.js')); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.deep.equal([0, -1, 1]); }, [fixtures]); itremote('has setImmediate working in script', async (fixtures: string) => { const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'set-immediate.js')); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.equal('ok'); }, [fixtures]); itremote('pipes stdio', async (fixtures: string) => { const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'process-stdout.js'), { silent: true }); let data = ''; child.stdout.on('data', (chunk: any) => { data += String(chunk); }); const code = await new Promise<any>(resolve => child.once('close', resolve)); expect(code).to.equal(0); expect(data).to.equal('pipes stdio'); }, [fixtures]); itremote('works when sending a message to a process forked with the --eval argument', async () => { const source = "process.on('message', (message) => { process.send(message) })"; const forked = require('node:child_process').fork('--eval', [source]); const message = new Promise(resolve => forked.once('message', resolve)); forked.send('hello'); const msg = await message; expect(msg).to.equal('hello'); }); it('has the electron version in process.versions', async () => { const source = 'process.send(process.versions)'; const forked = require('node:child_process').fork('--eval', [source]); const [message] = await once(forked, 'message'); expect(message) .to.have.own.property('electron') .that.is.a('string') .and.matches(/^\d+\.\d+\.\d+(\S*)?$/); }); }); describe('child_process.spawn', () => { itremote('supports spawning Electron as a node process via the ELECTRON_RUN_AS_NODE env var', async (fixtures: string) => { const child = require('node:child_process').spawn(process.execPath, [require('node:path').join(fixtures, 'module', 'run-as-node.js')], { env: { ELECTRON_RUN_AS_NODE: true } }); let output = ''; child.stdout.on('data', (data: any) => { output += data; }); try { await new Promise(resolve => child.stdout.once('close', resolve)); expect(JSON.parse(output)).to.deep.equal({ stdoutType: 'pipe', processType: 'undefined', window: 'undefined' }); } finally { child.kill(); } }, [fixtures]); }); describe('child_process.exec', () => { ifit(process.platform === 'linux')('allows executing a setuid binary from non-sandboxed renderer', async () => { // Chrome uses prctl(2) to set the NO_NEW_PRIVILEGES flag on Linux (see // https://github.com/torvalds/linux/blob/40fde647cc/Documentation/userspace-api/no_new_privs.rst). // We disable this for unsandboxed processes, which the renderer tests // are running in. If this test fails with an error like 'effective uid // is not 0', then it's likely that our patch to prevent the flag from // being set has become ineffective. const w = await getRemoteContext(); const stdout = await w.webContents.executeJavaScript('require(\'child_process\').execSync(\'sudo --help\')'); expect(stdout).to.not.be.empty(); }); }); }); it('does not hang when using the fs module in the renderer process', async () => { const appPath = path.join(mainFixturesPath, 'apps', 'libuv-hang', 'main.js'); const appProcess = childProcess.spawn(process.execPath, [appPath], { cwd: path.join(mainFixturesPath, 'apps', 'libuv-hang'), stdio: 'inherit' }); const [code] = await once(appProcess, 'close'); expect(code).to.equal(0); }); describe('contexts', () => { describe('setTimeout called under Chromium event loop in browser process', () => { it('Can be scheduled in time', (done) => { setTimeout(done, 0); }); it('Can be promisified', (done) => { util.promisify(setTimeout)(0).then(done); }); }); describe('setInterval called under Chromium event loop in browser process', () => { it('can be scheduled in time', (done) => { let interval: any = null; let clearing = false; const clear = () => { if (interval === null || clearing) return; // interval might trigger while clearing (remote is slow sometimes) clearing = true; clearInterval(interval); clearing = false; interval = null; done(); }; interval = setInterval(clear, 10); }); }); const suspendListeners = (emitter: EventEmitter, eventName: string, callback: (...args: any[]) => void) => { const listeners = emitter.listeners(eventName) as ((...args: any[]) => void)[]; emitter.removeAllListeners(eventName); emitter.once(eventName, (...args) => { emitter.removeAllListeners(eventName); for (const listener of listeners) { emitter.on(eventName, listener); } callback(...args); }); }; describe('error thrown in main process node context', () => { it('gets emitted as a process uncaughtException event', async () => { fs.readFile(__filename, () => { throw new Error('hello'); }); const result = await new Promise(resolve => suspendListeners(process, 'uncaughtException', (error) => { resolve(error.message); })); expect(result).to.equal('hello'); }); }); describe('promise rejection in main process node context', () => { it('gets emitted as a process unhandledRejection event', async () => { fs.readFile(__filename, () => { Promise.reject(new Error('hello')); }); const result = await new Promise(resolve => suspendListeners(process, 'unhandledRejection', (error) => { resolve(error.message); })); expect(result).to.equal('hello'); }); it('does not log the warning more than once when the rejection is unhandled', async () => { const appPath = path.join(mainFixturesPath, 'api', 'unhandled-rejection.js'); const appProcess = childProcess.spawn(process.execPath, [appPath]); let output = ''; const out = (data: string) => { output += data; if (/UnhandledPromiseRejectionWarning/.test(data)) { appProcess.kill(); } }; appProcess.stdout!.on('data', out); appProcess.stderr!.on('data', out); await once(appProcess, 'exit'); expect(/UnhandledPromiseRejectionWarning/.test(output)).to.equal(true); const matches = output.match(/Error: oops/gm); expect(matches).to.have.lengthOf(1); }); it('does not log the warning more than once when the rejection is handled', async () => { const appPath = path.join(mainFixturesPath, 'api', 'unhandled-rejection-handled.js'); const appProcess = childProcess.spawn(process.execPath, [appPath]); let output = ''; const out = (data: string) => { output += data; }; appProcess.stdout!.on('data', out); appProcess.stderr!.on('data', out); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); expect(/UnhandledPromiseRejectionWarning/.test(output)).to.equal(false); const matches = output.match(/Error: oops/gm); expect(matches).to.have.lengthOf(1); }); }); }); describe('contexts in renderer', () => { useRemoteContext(); describe('setTimeout in fs callback', () => { itremote('does not crash', async (filename: string) => { await new Promise(resolve => require('node:fs').readFile(filename, () => { setTimeout(resolve, 0); })); }, [__filename]); }); describe('error thrown in renderer process node context', () => { itremote('gets emitted as a process uncaughtException event', async (filename: string) => { const error = new Error('boo!'); require('node:fs').readFile(filename, () => { throw error; }); await new Promise<void>((resolve, reject) => { process.once('uncaughtException', (thrown) => { try { expect(thrown).to.equal(error); resolve(); } catch (e) { reject(e); } }); }); }, [__filename]); }); describe('URL handling in the renderer process', () => { itremote('can successfully handle WHATWG URLs constructed by Blink', (fixtures: string) => { const url = new URL('file://' + require('node:path').resolve(fixtures, 'pages', 'base-page.html')); expect(() => { require('node:fs').createReadStream(url); }).to.not.throw(); }, [fixtures]); }); describe('setTimeout called under blink env in renderer process', () => { itremote('can be scheduled in time', async () => { await new Promise(resolve => setTimeout(resolve, 10)); }); itremote('works from the timers module', async () => { await new Promise(resolve => require('node:timers').setTimeout(resolve, 10)); }); }); describe('setInterval called under blink env in renderer process', () => { itremote('can be scheduled in time', async () => { await new Promise<void>(resolve => { const id = setInterval(() => { clearInterval(id); resolve(); }, 10); }); }); itremote('can be scheduled in time from timers module', async () => { const { setInterval, clearInterval } = require('node:timers'); await new Promise<void>(resolve => { const id = setInterval(() => { clearInterval(id); resolve(); }, 10); }); }); }); }); describe('message loop in renderer', () => { useRemoteContext(); describe('process.nextTick', () => { itremote('emits the callback', () => new Promise(resolve => process.nextTick(resolve))); itremote('works in nested calls', () => new Promise(resolve => { process.nextTick(() => { process.nextTick(() => process.nextTick(resolve)); }); })); }); describe('setImmediate', () => { itremote('emits the callback', () => new Promise(resolve => setImmediate(resolve))); itremote('works in nested calls', () => new Promise(resolve => { setImmediate(() => { setImmediate(() => setImmediate(resolve)); }); })); }); }); ifdescribe(process.platform === 'darwin')('net.connect', () => { itremote('emit error when connect to a socket path without listeners', async (fixtures: string) => { const socketPath = require('node:path').join(require('node:os').tmpdir(), 'electron-test.sock'); const script = require('node:path').join(fixtures, 'module', 'create_socket.js'); const child = require('node:child_process').fork(script, [socketPath]); const code = await new Promise(resolve => child.once('exit', resolve)); expect(code).to.equal(0); const client = require('node:net').connect(socketPath); const error = await new Promise<any>(resolve => client.once('error', resolve)); expect(error.code).to.equal('ECONNREFUSED'); }, [fixtures]); }); describe('Buffer', () => { useRemoteContext(); itremote('can be created from Blink external string', () => { const p = document.createElement('p'); p.innerText = '闲云潭影日悠悠,物换星移几度秋'; const b = Buffer.from(p.innerText); expect(b.toString()).to.equal('闲云潭影日悠悠,物换星移几度秋'); expect(Buffer.byteLength(p.innerText)).to.equal(45); }); itremote('correctly parses external one-byte UTF8 string', () => { const p = document.createElement('p'); p.innerText = 'Jøhänñéß'; const b = Buffer.from(p.innerText); expect(b.toString()).to.equal('Jøhänñéß'); expect(Buffer.byteLength(p.innerText)).to.equal(13); }); itremote('does not crash when creating large Buffers', () => { let buffer = Buffer.from(new Array(4096).join(' ')); expect(buffer.length).to.equal(4095); buffer = Buffer.from(new Array(4097).join(' ')); expect(buffer.length).to.equal(4096); }); itremote('does not crash for crypto operations', () => { const crypto = require('node:crypto'); const data = 'lG9E+/g4JmRmedDAnihtBD4Dfaha/GFOjd+xUOQI05UtfVX3DjUXvrS98p7kZQwY3LNhdiFo7MY5rGft8yBuDhKuNNag9vRx/44IuClDhdQ='; const key = 'q90K9yBqhWZnAMCMTOJfPQ=='; const cipherText = '{"error_code":114,"error_message":"Tham số không hợp lệ","data":null}'; for (let i = 0; i < 10000; ++i) { const iv = Buffer.from('0'.repeat(32), 'hex'); const input = Buffer.from(data, 'base64'); const decipher = crypto.createDecipheriv('aes-128-cbc', Buffer.from(key, 'base64'), iv); const result = Buffer.concat([decipher.update(input), decipher.final()]).toString('utf8'); expect(cipherText).to.equal(result); } }); itremote('does not crash when using crypto.diffieHellman() constructors', () => { const crypto = require('node:crypto'); crypto.createDiffieHellman('abc'); crypto.createDiffieHellman('abc', 2); // Needed to test specific DiffieHellman ctors. crypto.createDiffieHellman('abc', Buffer.from([2])); crypto.createDiffieHellman('abc', '123'); }); itremote('does not crash when calling crypto.createPrivateKey() with an unsupported algorithm', () => { const crypto = require('node:crypto'); const ed448 = { crv: 'Ed448', x: 'KYWcaDwgH77xdAwcbzOgvCVcGMy9I6prRQBhQTTdKXUcr-VquTz7Fd5adJO0wT2VHysF3bk3kBoA', d: 'UhC3-vN5vp_g9PnTknXZgfXUez7Xvw-OfuJ0pYkuwzpYkcTvacqoFkV_O05WMHpyXkzH9q2wzx5n', kty: 'OKP' }; expect(() => { crypto.createPrivateKey({ key: ed448, format: 'jwk' }); }).to.throw(/Invalid JWK data/); }); }); describe('process.stdout', () => { useRemoteContext(); itremote('does not throw an exception when accessed', () => { expect(() => process.stdout).to.not.throw(); }); itremote('does not throw an exception when calling write()', () => { expect(() => { process.stdout.write('test'); }).to.not.throw(); }); // TODO: figure out why process.stdout.isTTY is true on Darwin but not Linux/Win. ifdescribe(process.platform !== 'darwin')('isTTY', () => { itremote('should be undefined in the renderer process', function () { expect(process.stdout.isTTY).to.be.undefined(); }); }); }); describe('process.stdin', () => { useRemoteContext(); itremote('does not throw an exception when accessed', () => { expect(() => process.stdin).to.not.throw(); }); itremote('returns null when read from', () => { expect(process.stdin.read()).to.be.null(); }); }); describe('process.version', () => { itremote('should not have -pre', () => { expect(process.version.endsWith('-pre')).to.be.false(); }); }); describe('vm.runInNewContext', () => { itremote('should not crash', () => { require('node:vm').runInNewContext(''); }); }); describe('crypto', () => { useRemoteContext(); itremote('should list the ripemd160 hash in getHashes', () => { expect(require('node:crypto').getHashes()).to.include('ripemd160'); }); itremote('should be able to create a ripemd160 hash and use it', () => { const hash = require('node:crypto').createHash('ripemd160'); hash.update('electron-ripemd160'); expect(hash.digest('hex')).to.equal('fa7fec13c624009ab126ebb99eda6525583395fe'); }); itremote('should list aes-{128,256}-cfb in getCiphers', () => { expect(require('node:crypto').getCiphers()).to.include.members(['aes-128-cfb', 'aes-256-cfb']); }); itremote('should be able to create an aes-128-cfb cipher', () => { require('node:crypto').createCipheriv('aes-128-cfb', '0123456789abcdef', '0123456789abcdef'); }); itremote('should be able to create an aes-256-cfb cipher', () => { require('node:crypto').createCipheriv('aes-256-cfb', '0123456789abcdef0123456789abcdef', '0123456789abcdef'); }); itremote('should be able to create a bf-{cbc,cfb,ecb} ciphers', () => { require('node:crypto').createCipheriv('bf-cbc', Buffer.from('0123456789abcdef'), Buffer.from('01234567')); require('node:crypto').createCipheriv('bf-cfb', Buffer.from('0123456789abcdef'), Buffer.from('01234567')); require('node:crypto').createCipheriv('bf-ecb', Buffer.from('0123456789abcdef'), Buffer.from('01234567')); }); itremote('should list des-ede-cbc in getCiphers', () => { expect(require('node:crypto').getCiphers()).to.include('des-ede-cbc'); }); itremote('should be able to create an des-ede-cbc cipher', () => { const key = Buffer.from('0123456789abcdeff1e0d3c2b5a49786', 'hex'); const iv = Buffer.from('fedcba9876543210', 'hex'); require('node:crypto').createCipheriv('des-ede-cbc', key, iv); }); itremote('should not crash when getting an ECDH key', () => { const ecdh = require('node:crypto').createECDH('prime256v1'); expect(ecdh.generateKeys()).to.be.an.instanceof(Buffer); expect(ecdh.getPrivateKey()).to.be.an.instanceof(Buffer); }); itremote('should not crash when generating DH keys or fetching DH fields', () => { const dh = require('node:crypto').createDiffieHellman('modp15'); expect(dh.generateKeys()).to.be.an.instanceof(Buffer); expect(dh.getPublicKey()).to.be.an.instanceof(Buffer); expect(dh.getPrivateKey()).to.be.an.instanceof(Buffer); expect(dh.getPrime()).to.be.an.instanceof(Buffer); expect(dh.getGenerator()).to.be.an.instanceof(Buffer); }); itremote('should not crash when creating an ECDH cipher', () => { const crypto = require('node:crypto'); const dh = crypto.createECDH('prime256v1'); dh.generateKeys(); dh.setPrivateKey(dh.getPrivateKey()); }); }); itremote('includes the electron version in process.versions', () => { expect(process.versions) .to.have.own.property('electron') .that.is.a('string') .and.matches(/^\d+\.\d+\.\d+(\S*)?$/); }); itremote('includes the chrome version in process.versions', () => { expect(process.versions) .to.have.own.property('chrome') .that.is.a('string') .and.matches(/^\d+\.\d+\.\d+\.\d+$/); }); describe('NODE_OPTIONS', () => { let child: childProcess.ChildProcessWithoutNullStreams; let exitPromise: Promise<any[]>; it('Fails for options disallowed by Node.js itself', (done) => { after(async () => { const [code, signal] = await exitPromise; expect(signal).to.equal(null); // Exit code 9 indicates cli flag parsing failure expect(code).to.equal(9); child.kill(); }); const env = { ...process.env, NODE_OPTIONS: '--v8-options' }; child = childProcess.spawn(process.execPath, { env }); exitPromise = once(child, 'exit'); let output = ''; let success = false; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; const listener = (data: Buffer) => { output += data; if (/electron: --v8-options is not allowed in NODE_OPTIONS/m.test(output)) { success = true; cleanup(); done(); } }; child.stderr.on('data', listener); child.stdout.on('data', listener); child.on('exit', () => { if (!success) { cleanup(); done(new Error(`Unexpected output: ${output.toString()}`)); } }); }); it('Disallows crypto-related options', (done) => { after(() => { child.kill(); }); const appPath = path.join(fixtures, 'module', 'noop.js'); const env = { ...process.env, NODE_OPTIONS: '--use-openssl-ca' }; child = childProcess.spawn(process.execPath, ['--enable-logging', appPath], { env }); let output = ''; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; const listener = (data: Buffer) => { output += data; if (/The NODE_OPTION --use-openssl-ca is not supported in Electron/m.test(output)) { cleanup(); done(); } }; child.stderr.on('data', listener); child.stdout.on('data', listener); }); it('does allow --require in non-packaged apps', async () => { const appPath = path.join(fixtures, 'module', 'noop.js'); const env = { ...process.env, NODE_OPTIONS: `--require=${path.join(fixtures, 'module', 'fail.js')}` }; // App should exit with code 1. const child = childProcess.spawn(process.execPath, [appPath], { env }); const [code] = await once(child, 'exit'); expect(code).to.equal(1); }); it('does not allow --require in packaged apps', async () => { const appPath = path.join(fixtures, 'module', 'noop.js'); const env = { ...process.env, ELECTRON_FORCE_IS_PACKAGED: 'true', NODE_OPTIONS: `--require=${path.join(fixtures, 'module', 'fail.js')}` }; // App should exit with code 0. const child = childProcess.spawn(process.execPath, [appPath], { env }); const [code] = await once(child, 'exit'); expect(code).to.equal(0); }); }); describe('Node.js cli flags', () => { let child: childProcess.ChildProcessWithoutNullStreams; let exitPromise: Promise<any[]>; it('Prohibits crypto-related flags in ELECTRON_RUN_AS_NODE mode', (done) => { after(async () => { const [code, signal] = await exitPromise; expect(signal).to.equal(null); expect(code).to.equal(9); child.kill(); }); child = childProcess.spawn(process.execPath, ['--force-fips'], { env: { ELECTRON_RUN_AS_NODE: 'true' } }); exitPromise = once(child, 'exit'); let output = ''; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; const listener = (data: Buffer) => { output += data; if (/.*The Node.js cli flag --force-fips is not supported in Electron/m.test(output)) { cleanup(); done(); } }; child.stderr.on('data', listener); child.stdout.on('data', listener); }); }); describe('process.stdout', () => { it('is a real Node stream', () => { expect((process.stdout as any)._type).to.not.be.undefined(); }); }); describe('fs.readFile', () => { it('can accept a FileHandle as the Path argument', async () => { const filePathForHandle = path.resolve(mainFixturesPath, 'dogs-running.txt'); const fileHandle = await fs.promises.open(filePathForHandle, 'r'); const file = await fs.promises.readFile(fileHandle, { encoding: 'utf8' }); expect(file).to.not.be.empty(); await fileHandle.close(); }); }); describe('inspector', () => { let child: childProcess.ChildProcessWithoutNullStreams; let exitPromise: Promise<any[]> | null; afterEach(async () => { if (child && exitPromise) { const [code, signal] = await exitPromise; expect(signal).to.equal(null); expect(code).to.equal(0); } else if (child) { child.kill(); } child = null as any; exitPromise = null as any; }); it('Supports starting the v8 inspector with --inspect/--inspect-brk', (done) => { child = childProcess.spawn(process.execPath, ['--inspect-brk', path.join(fixtures, 'module', 'run-as-node.js')], { env: { ELECTRON_RUN_AS_NODE: 'true' } }); let output = ''; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; const listener = (data: Buffer) => { output += data; if (/Debugger listening on ws:/m.test(output)) { cleanup(); done(); } }; child.stderr.on('data', listener); child.stdout.on('data', listener); }); it('Supports starting the v8 inspector with --inspect and a provided port', async () => { child = childProcess.spawn(process.execPath, ['--inspect=17364', path.join(fixtures, 'module', 'run-as-node.js')], { env: { ELECTRON_RUN_AS_NODE: 'true' } }); exitPromise = once(child, 'exit'); let output = ''; const listener = (data: Buffer) => { output += data; }; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; child.stderr.on('data', listener); child.stdout.on('data', listener); await once(child, 'exit'); cleanup(); if (/^Debugger listening on ws:/m.test(output)) { expect(output.trim()).to.contain(':17364', 'should be listening on port 17364'); } else { throw new Error(`Unexpected output: ${output.toString()}`); } }); it('Does not start the v8 inspector when --inspect is after a -- argument', async () => { child = childProcess.spawn(process.execPath, [path.join(fixtures, 'module', 'noop.js'), '--', '--inspect']); exitPromise = once(child, 'exit'); let output = ''; const listener = (data: Buffer) => { output += data; }; child.stderr.on('data', listener); child.stdout.on('data', listener); await once(child, 'exit'); if (output.trim().startsWith('Debugger listening on ws://')) { throw new Error('Inspector was started when it should not have been'); } }); // IPC Electron child process not supported on Windows. ifit(process.platform !== 'win32')('does not crash when quitting with the inspector connected', function (done) { child = childProcess.spawn(process.execPath, [path.join(fixtures, 'module', 'delay-exit'), '--inspect=0'], { stdio: ['ipc'] }) as childProcess.ChildProcessWithoutNullStreams; exitPromise = once(child, 'exit'); const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; let output = ''; const success = false; function listener (data: Buffer) { output += data; console.log(data.toString()); // NOTE: temporary debug logging to try to catch flake. const match = /^Debugger listening on (ws:\/\/.+:\d+\/.+)\n/m.exec(output.trim()); if (match) { cleanup(); // NOTE: temporary debug logging to try to catch flake. child.stderr.on('data', (m) => console.log(m.toString())); child.stdout.on('data', (m) => console.log(m.toString())); const w = (webContents as typeof ElectronInternal.WebContents).create(); w.loadURL('about:blank') .then(() => w.executeJavaScript(`new Promise(resolve => { const connection = new WebSocket(${JSON.stringify(match[1])}) connection.onopen = () => { connection.onclose = () => resolve() connection.close() } })`)) .then(() => { w.destroy(); child.send('plz-quit'); done(); }); } } child.stderr.on('data', listener); child.stdout.on('data', listener); child.on('exit', () => { if (!success) cleanup(); }); }); it('Supports js binding', async () => { child = childProcess.spawn(process.execPath, ['--inspect', path.join(fixtures, 'module', 'inspector-binding.js')], { env: { ELECTRON_RUN_AS_NODE: 'true' }, stdio: ['ipc'] }) as childProcess.ChildProcessWithoutNullStreams; exitPromise = once(child, 'exit'); const [{ cmd, debuggerEnabled, success }] = await once(child, 'message'); expect(cmd).to.equal('assert'); expect(debuggerEnabled).to.be.true(); expect(success).to.be.true(); }); }); it('Can find a module using a package.json main field', () => { const result = childProcess.spawnSync(process.execPath, [path.resolve(fixtures, 'api', 'electron-main-module', 'app.asar')], { stdio: 'inherit' }); expect(result.status).to.equal(0); }); it('handles Promise timeouts correctly', async () => { const scriptPath = path.join(fixtures, 'module', 'node-promise-timer.js'); const child = childProcess.spawn(process.execPath, [scriptPath], { env: { ELECTRON_RUN_AS_NODE: 'true' } }); const [code, signal] = await once(child, 'exit'); expect(code).to.equal(0); expect(signal).to.equal(null); child.kill(); }); it('performs microtask checkpoint correctly', (done) => { const f3 = async () => { return new Promise((resolve, reject) => { reject(new Error('oops')); }); }; process.once('unhandledRejection', () => done(new Error('catch block is delayed to next tick'))); setTimeout(() => { f3().catch(() => done()); }); }); });
closed
electron/electron
https://github.com/electron/electron
40,354
[Bug]: Zoom controller doesn't persist when changing webviews
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.2 ### What operating system are you using? Windows ### Operating System Version Windows 11 Pro 22H2 - Build 22621.2428 ### What arch are you using? x64 ### Last Known Working Electron version 26.0.0 ### Expected Behavior When switching between different Webviews the Zoom scale persists after going back to the initial webview. ### Actual Behavior [Ferdium](https://github.com/ferdium/ferdium-app) currently uses multiple Webviews for each service it renders. When switching between Webviews the Zoom scale is not persistent (when switching away the zoom resets - this is visible for some milliseconds before changing to the other webview). ### Testcase Gist URL _No response_ ### Additional Information I'm logging this issue in Electron given that this was not present in past versions of Electron, but only after `26.0.0` (I'm blaming `26.1.0` as the version who started to cause issues). After some investigation it seems like the PR that caused this unwanted behaviour is: https://github.com/electron/electron/pull/39495 . Is it possible for you to search and revert this unwanted breakage? We would really need this to be fix because we have several users with this accessibility needs. Thank you very much in advance! PS: If this is not the proper way to open an issue on Electron please let me know.
https://github.com/electron/electron/issues/40354
https://github.com/electron/electron/pull/40650
66b4b216468feab79c7527295f2485067ea2cf15
10a165a9ff731137b679a4ef3a9e3d18bcdfd514
2023-10-27T12:40:22Z
c++
2023-12-04T15:39:20Z
spec/webview-spec.ts
import * as path from 'node:path'; import * as url from 'node:url'; import { BrowserWindow, session, ipcMain, app, WebContents } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import { emittedUntil } from './lib/events-helpers'; import { ifit, ifdescribe, defer, itremote, useRemoteContext, listen } from './lib/spec-helpers'; import { expect } from 'chai'; import * as http from 'node:http'; import * as auth from 'basic-auth'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; declare let WebView: any; const features = process._linkedBinding('electron_common_features'); async function loadWebView (w: WebContents, attributes: Record<string, string>, opts?: {openDevTools?: boolean}): Promise<void> { const { openDevTools } = { openDevTools: false, ...opts }; await w.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView() webview.id = 'webview' for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) { webview.setAttribute(k, v) } document.body.appendChild(webview) webview.addEventListener('dom-ready', () => { if (${openDevTools}) { webview.openDevTools() } }) webview.addEventListener('did-finish-load', () => { resolve() }) }) `); } async function loadWebViewAndWaitForEvent (w: WebContents, attributes: Record<string, string>, eventName: string): Promise<any> { return await w.executeJavaScript(`new Promise((resolve, reject) => { const webview = new WebView() webview.id = 'webview' for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) { webview.setAttribute(k, v) } webview.addEventListener(${JSON.stringify(eventName)}, (e) => resolve({...e}), {once: true}) document.body.appendChild(webview) })`); }; async function loadWebViewAndWaitForMessage (w: WebContents, attributes: Record<string, string>): Promise<string> { const { message } = await loadWebViewAndWaitForEvent(w, attributes, 'console-message'); return message; }; describe('<webview> tag', function () { const fixtures = path.join(__dirname, 'fixtures'); const blankPageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'blank.html')).toString(); function hideChildWindows (e: any, wc: WebContents) { wc.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false } })); } before(() => { app.on('web-contents-created', hideChildWindows); }); after(() => { app.off('web-contents-created', hideChildWindows); }); describe('behavior', () => { afterEach(closeAllWindows); it('works without script tag in page', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html')); await once(ipcMain, 'pong'); }); it('works with sandbox', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, sandbox: true } }); w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html')); await once(ipcMain, 'pong'); }); it('works with contextIsolation', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, contextIsolation: true } }); w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html')); await once(ipcMain, 'pong'); }); it('works with contextIsolation + sandbox', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, contextIsolation: true, sandbox: true } }); w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html')); await once(ipcMain, 'pong'); }); it('works with Trusted Types', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadFile(path.join(fixtures, 'pages', 'webview-trusted-types.html')); await once(ipcMain, 'pong'); }); it('is disabled by default', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'module', 'preload-webview.js'), nodeIntegration: true } }); const webview = once(ipcMain, 'webview'); w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html')); const [, type] = await webview; expect(type).to.equal('undefined', 'WebView still exists'); }); }); // FIXME(deepak1556): Ch69 follow up. xdescribe('document.visibilityState/hidden', () => { afterEach(() => { ipcMain.removeAllListeners('pong'); }); afterEach(closeAllWindows); it('updates when the window is shown after the ready-to-show event', async () => { const w = new BrowserWindow({ show: false }); const readyToShowSignal = once(w, 'ready-to-show'); const pongSignal1 = once(ipcMain, 'pong'); w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html')); await pongSignal1; const pongSignal2 = once(ipcMain, 'pong'); await readyToShowSignal; w.show(); const [, visibilityState, hidden] = await pongSignal2; expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false(); }); it('inherits the parent window visibility state and receives visibilitychange events', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true(); // We have to start waiting for the event // before we ask the webContents to resize. const getResponse = once(ipcMain, 'pong'); w.webContents.emit('-window-visibility-change', 'visible'); return getResponse.then(([, visibilityState, hidden]) => { expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false(); }); }); }); describe('did-attach-webview event', () => { afterEach(closeAllWindows); it('is emitted when a webview has been attached', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('did-attach event', () => { afterEach(closeAllWindows); it('is emitted when a webview has been attached', async () => { const w = new BrowserWindow({ webPreferences: { webviewTag: true } }); await w.loadURL('about:blank'); const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { const webview = new WebView() webview.setAttribute('src', 'about:blank') webview.addEventListener('did-attach', (e) => { resolve('ok') }) document.body.appendChild(webview) })`); expect(message).to.equal('ok'); }); }); describe('did-change-theme-color event', () => { afterEach(closeAllWindows); it('emits when theme color changes', async () => { const w = new BrowserWindow({ webPreferences: { webviewTag: true } }); await w.loadURL('about:blank'); const src = url.format({ pathname: `${fixtures.replaceAll('\\', '/')}/pages/theme-color.html`, protocol: 'file', slashes: true }); const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { const webview = new WebView() webview.setAttribute('src', '${src}') webview.addEventListener('did-change-theme-color', (e) => { resolve('ok') }) document.body.appendChild(webview) })`); expect(message).to.equal('ok'); }); }); describe('devtools', () => { afterEach(closeAllWindows); // FIXME: This test is flaky on WOA, so skip it there. ifit(process.platform !== 'win32' || process.arch !== 'arm64')('loads devtools extensions registered on the parent window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); w.webContents.session.removeExtension('foo'); const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo'); await w.webContents.session.loadExtension(extensionPath, { allowFileAccess: true }); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'webview-devtools.html')); loadWebView(w.webContents, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${path.join(__dirname, 'fixtures', 'blank.html')}` }, { openDevTools: true }); let childWebContentsId = 0; app.once('web-contents-created', (e, webContents) => { childWebContentsId = webContents.id; webContents.on('devtools-opened', function () { const showPanelIntervalId = setInterval(function () { if (!webContents.isDestroyed() && webContents.devToolsWebContents) { webContents.devToolsWebContents.executeJavaScript('(' + function () { const { EUI } = (window as any); const instance = EUI.InspectorView.InspectorView.instance(); const tabs = instance.tabbedPane.tabs; const lastPanelId: any = tabs[tabs.length - 1].id; instance.showPanel(lastPanelId); }.toString() + ')()'); } else { clearInterval(showPanelIntervalId); } }, 100); }); }); const [, { runtimeId, tabId }] = await once(ipcMain, 'answer'); expect(runtimeId).to.match(/^[a-z]{32}$/); expect(tabId).to.equal(childWebContentsId); await w.webContents.executeJavaScript('webview.closeDevTools()'); }); }); describe('zoom behavior', () => { const zoomScheme = standardScheme; const webviewSession = session.fromPartition('webview-temp'); afterEach(closeAllWindows); before(() => { const protocol = webviewSession.protocol; protocol.registerStringProtocol(zoomScheme, (request, callback) => { callback('hello'); }); }); after(() => { const protocol = webviewSession.protocol; protocol.unregisterProtocol(zoomScheme); }); it('inherits the zoomFactor of the parent window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, zoomFactor: 1.2, contextIsolation: false } }); const zoomEventPromise = once(ipcMain, 'webview-parent-zoom-level'); w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-factor.html')); const [, zoomFactor, zoomLevel] = await zoomEventPromise; expect(zoomFactor).to.equal(1.2); expect(zoomLevel).to.equal(1); }); it('maintains zoom level on navigation', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, zoomFactor: 1.2, contextIsolation: false } }); const promise = new Promise<void>((resolve) => { ipcMain.on('webview-zoom-level', (event, zoomLevel, zoomFactor, newHost, final) => { if (!newHost) { expect(zoomFactor).to.equal(1.44); expect(zoomLevel).to.equal(2.0); } else { expect(zoomFactor).to.equal(1.2); expect(zoomLevel).to.equal(1); } if (final) { resolve(); } }); }); w.loadFile(path.join(fixtures, 'pages', 'webview-custom-zoom-level.html')); await promise; }); it('maintains zoom level when navigating within same page', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, zoomFactor: 1.2, contextIsolation: false } }); const promise = new Promise<void>((resolve) => { ipcMain.on('webview-zoom-in-page', (event, zoomLevel, zoomFactor, final) => { expect(zoomFactor).to.equal(1.44); expect(zoomLevel).to.equal(2.0); if (final) { resolve(); } }); }); w.loadFile(path.join(fixtures, 'pages', 'webview-in-page-navigate.html')); await promise; }); it('inherits zoom level for the origin when available', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, zoomFactor: 1.2, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'webview-origin-zoom-level.html')); const [, zoomLevel] = await once(ipcMain, 'webview-origin-zoom-level'); expect(zoomLevel).to.equal(2.0); }); it('does not crash when navigating with zoom level inherited from parent', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, zoomFactor: 1.2, session: webviewSession, contextIsolation: false } }); const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const readyPromise = once(ipcMain, 'dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html')); const [, webview] = await attachPromise; await readyPromise; expect(webview.getZoomFactor()).to.equal(1.2); await w.loadURL(`${zoomScheme}://host1`); }); it('does not crash when changing zoom level after webview is destroyed', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, session: webviewSession, contextIsolation: false } }); const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; await w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html')); await attachPromise; await w.webContents.executeJavaScript('view.remove()'); w.webContents.setZoomLevel(0.5); }); }); describe('requestFullscreen from webview', () => { afterEach(closeAllWindows); async function loadWebViewWindow (): Promise<[BrowserWindow, WebContents]> { const w = new BrowserWindow({ webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const loadPromise = once(w.webContents, 'did-finish-load'); const readyPromise = once(ipcMain, 'webview-ready'); w.loadFile(path.join(__dirname, 'fixtures', 'webview', 'fullscreen', 'main.html')); const [, webview] = await attachPromise; await Promise.all([readyPromise, loadPromise]); return [w, webview]; }; afterEach(async () => { // The leaving animation is un-observable but can interfere with future tests // Specifically this is async on macOS but can be on other platforms too await setTimeout(1000); closeAllWindows(); }); ifit(process.platform !== 'darwin')('should make parent frame element fullscreen too (non-macOS)', async () => { const [w, webview] = await loadWebViewWindow(); expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false(); const parentFullscreen = once(ipcMain, 'fullscreenchange'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await parentFullscreen; expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true(); const close = once(w, 'closed'); w.close(); await close; }); ifit(process.platform === 'darwin')('should make parent frame element fullscreen too (macOS)', async () => { const [w, webview] = await loadWebViewWindow(); expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false(); const parentFullscreen = once(ipcMain, 'fullscreenchange'); const enterHTMLFS = once(w.webContents, 'enter-html-full-screen'); const leaveHTMLFS = once(w.webContents, 'leave-html-full-screen'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true(); await webview.executeJavaScript('document.exitFullscreen()'); await Promise.all([enterHTMLFS, leaveHTMLFS, parentFullscreen]); const close = once(w, 'closed'); w.close(); await close; }); // FIXME(zcbenz): Fullscreen events do not work on Linux. ifit(process.platform !== 'linux')('exiting fullscreen should unfullscreen window', async () => { const [w, webview] = await loadWebViewWindow(); const enterFullScreen = once(w, 'enter-full-screen'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); await webview.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; await setTimeout(); expect(w.isFullScreen()).to.be.false(); const close = once(w, 'closed'); w.close(); await close; }); it('pressing ESC should unfullscreen window', async () => { const [w, webview] = await loadWebViewWindow(); const enterFullScreen = once(w, 'enter-full-screen'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); webview.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); await leaveFullScreen; await setTimeout(1000); expect(w.isFullScreen()).to.be.false(); const close = once(w, 'closed'); w.close(); await close; }); it('pressing ESC should emit the leave-html-full-screen event', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const enterFSWindow = once(w, 'enter-html-full-screen'); const enterFSWebview = once(webContents, 'enter-html-full-screen'); await webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFSWindow; await enterFSWebview; const leaveFSWindow = once(w, 'leave-html-full-screen'); const leaveFSWebview = once(webContents, 'leave-html-full-screen'); webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); await leaveFSWebview; await leaveFSWindow; const close = once(w, 'closed'); w.close(); await close; }); it('should support user gesture', async () => { const [w, webview] = await loadWebViewWindow(); const waitForEnterHtmlFullScreen = once(webview, 'enter-html-full-screen'); const jsScript = "document.querySelector('video').webkitRequestFullscreen()"; webview.executeJavaScript(jsScript, true); await waitForEnterHtmlFullScreen; const close = once(w, 'closed'); w.close(); await close; }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('opens window of about:blank with cross-scripting enabled', async () => { // Don't wait for loading to finish. loadWebView(w.webContents, { allowpopups: 'on', nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${path.join(fixtures, 'api', 'native-window-open-blank.html')}` }); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { // Don't wait for loading to finish. loadWebView(w.webContents, { allowpopups: 'on', nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${path.join(fixtures, 'api', 'native-window-open-file.html')}` }); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); it('returns null from window.open when allowpopups is not set', async () => { // Don't wait for loading to finish. loadWebView(w.webContents, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${path.join(fixtures, 'api', 'native-window-open-no-allowpopups.html')}` }); const [, { windowOpenReturnedNull }] = await once(ipcMain, 'answer'); expect(windowOpenReturnedNull).to.be.true(); }); it('blocks accessing cross-origin frames', async () => { // Don't wait for loading to finish. loadWebView(w.webContents, { allowpopups: 'on', nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${path.join(fixtures, 'api', 'native-window-open-cross-origin.html')}` }); const [, content] = await once(ipcMain, 'answer'); const expectedContent = /Failed to read a named property 'toString' from 'Location': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./; expect(content).to.match(expectedContent); }); it('emits a browser-window-created event', async () => { // Don't wait for loading to finish. loadWebView(w.webContents, { allowpopups: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/window-open.html` }); await once(app, 'browser-window-created'); }); it('emits a web-contents-created event', async () => { const webContentsCreated = emittedUntil(app, 'web-contents-created', (event: Electron.Event, contents: Electron.WebContents) => contents.getType() === 'window'); loadWebView(w.webContents, { allowpopups: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/window-open.html` }); await webContentsCreated; }); it('does not crash when creating window with noopener', async () => { loadWebView(w.webContents, { allowpopups: 'on', src: `file://${path.join(fixtures, 'api', 'native-window-open-noopener.html')}` }); await once(app, 'browser-window-created'); }); }); describe('webpreferences attribute', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('can enable context isolation', async () => { loadWebView(w.webContents, { allowpopups: 'yes', preload: `file://${fixtures}/api/isolated-preload.js`, src: `file://${fixtures}/api/isolated.html`, webpreferences: 'contextIsolation=yes' }); const [, data] = await once(ipcMain, 'isolated-world'); expect(data).to.deep.equal({ 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' } }); }); }); describe('permission request handlers', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); const partition = 'permissionTest'; function setUpRequestHandler (webContentsId: number, requestedPermission: string) { return new Promise<void>((resolve, reject) => { session.fromPartition(partition).setPermissionRequestHandler(function (webContents, permission, callback) { if (webContents.id === webContentsId) { // requestMIDIAccess with sysex requests both midi and midiSysex so // grant the first midi one and then reject the midiSysex one if (requestedPermission === 'midiSysex' && permission === 'midi') { return callback(true); } try { expect(permission).to.equal(requestedPermission); } catch (e) { return reject(e); } callback(false); resolve(); } }); }); } afterEach(() => { session.fromPartition(partition).setPermissionRequestHandler(null); }); // This is disabled because CI machines don't have cameras or microphones, // so Chrome responds with "NotFoundError" instead of // "PermissionDeniedError". It should be re-enabled if we find a way to mock // the presence of a microphone & camera. xit('emits when using navigator.getUserMedia api', async () => { const errorFromRenderer = once(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/media.html`, partition, nodeintegration: 'on' }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; setUpRequestHandler(webViewContents.id, 'media'); const [, errorName] = await errorFromRenderer; expect(errorName).to.equal('PermissionDeniedError'); }); it('emits when using navigator.geolocation api', async () => { const errorFromRenderer = once(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/geolocation.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; setUpRequestHandler(webViewContents.id, 'geolocation'); const [, error] = await errorFromRenderer; expect(error).to.equal('User denied Geolocation'); }); it('emits when using navigator.requestMIDIAccess without sysex api', async () => { const errorFromRenderer = once(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/midi.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; setUpRequestHandler(webViewContents.id, 'midi'); const [, error] = await errorFromRenderer; expect(error).to.equal('SecurityError'); }); it('emits when using navigator.requestMIDIAccess with sysex api', async () => { const errorFromRenderer = once(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/midi-sysex.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; setUpRequestHandler(webViewContents.id, 'midiSysex'); const [, error] = await errorFromRenderer; expect(error).to.equal('SecurityError'); }); it('emits when accessing external protocol', async () => { loadWebView(w.webContents, { src: 'magnet:test', partition }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; await setUpRequestHandler(webViewContents.id, 'openExternal'); }); it('emits when using Notification.requestPermission', async () => { const errorFromRenderer = once(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/notification.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; await setUpRequestHandler(webViewContents.id, 'notifications'); const [, error] = await errorFromRenderer; expect(error).to.equal('denied'); }); }); describe('DOM events', () => { afterEach(closeAllWindows); it('receives extra properties on DOM events when contextIsolation is enabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, contextIsolation: true } }); await w.loadURL('about:blank'); const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { const webview = new WebView() webview.setAttribute('src', 'data:text/html,<script>console.log("hi")</script>') webview.addEventListener('console-message', (e) => { resolve(e.message) }) document.body.appendChild(webview) })`); expect(message).to.equal('hi'); }); it('emits focus event when contextIsolation is enabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, contextIsolation: true } }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { const webview = new WebView() webview.setAttribute('src', 'about:blank') webview.addEventListener('dom-ready', () => { webview.focus() }) webview.addEventListener('focus', () => { resolve(); }) document.body.appendChild(webview) })`); }); }); describe('attributes', () => { let w: WebContents; before(async () => { const window = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); await window.loadURL(`file://${fixtures}/pages/blank.html`); w = window.webContents; }); afterEach(async () => { await w.executeJavaScript(`{ for (const el of document.querySelectorAll('webview')) el.remove(); }`); }); after(closeAllWindows); describe('src attribute', () => { it('specifies the page to load', async () => { const message = await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/a.html` }); expect(message).to.equal('a'); }); it('navigates to new page when changed', async () => { await loadWebView(w, { src: `file://${fixtures}/pages/a.html` }); const { message } = await w.executeJavaScript(`new Promise(resolve => { webview.addEventListener('console-message', e => resolve({message: e.message})) webview.src = ${JSON.stringify(`file://${fixtures}/pages/b.html`)} })`); expect(message).to.equal('b'); }); it('resolves relative URLs', async () => { const message = await loadWebViewAndWaitForMessage(w, { src: './e.html' }); expect(message).to.equal('Window script is loaded before preload script'); }); it('ignores empty values', async () => { loadWebView(w, {}); for (const emptyValue of ['""', 'null', 'undefined']) { const src = await w.executeJavaScript(`webview.src = ${emptyValue}, webview.src`); expect(src).to.equal(''); } }); it('does not wait until loadURL is resolved', async () => { await loadWebView(w, { src: 'about:blank' }); const delay = await w.executeJavaScript(`new Promise(resolve => { const before = Date.now(); webview.src = 'file://${fixtures}/pages/blank.html'; const now = Date.now(); resolve(now - before); })`); // Setting src is essentially sending a sync IPC message, which should // not exceed more than a few ms. // // This is for testing #18638. expect(delay).to.be.below(100); }); }); describe('nodeintegration attribute', () => { it('inserts no node symbols when not set', async () => { const message = await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/c.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'undefined', module: 'undefined', process: 'undefined', global: 'undefined' }); }); it('inserts node symbols when set', async () => { const message = await loadWebViewAndWaitForMessage(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/d.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object' }); }); it('loads node symbols after POST navigation when set', async function () { const message = await loadWebViewAndWaitForMessage(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/post.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object' }); }); it('disables node integration on child windows when it is disabled on the webview', async () => { const src = url.format({ pathname: `${fixtures}/pages/webview-opener-no-node-integration.html`, protocol: 'file', query: { p: `${fixtures}/pages/window-opener-node.html` }, slashes: true }); const message = await loadWebViewAndWaitForMessage(w, { allowpopups: 'on', webpreferences: 'contextIsolation=no', src }); expect(JSON.parse(message).isProcessGlobalUndefined).to.be.true(); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native modules when navigation happens', async function () { await loadWebView(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/native-module.html` }); const message = await w.executeJavaScript(`new Promise(resolve => { webview.addEventListener('console-message', e => resolve(e.message)) webview.reload(); })`); expect(message).to.equal('function'); }); }); describe('preload attribute', () => { useRemoteContext({ webPreferences: { webviewTag: true } }); it('loads the script before other scripts in window', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: `${fixtures}/module/preload.js`, src: `file://${fixtures}/pages/e.html` }); expect(message).to.be.a('string'); expect(message).to.be.not.equal('Window script is loaded before preload script'); }); it('preload script can still use "process" and "Buffer" when nodeintegration is off', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: `${fixtures}/module/preload-node-off.js`, src: `file://${fixtures}/api/blank.html` }); const types = JSON.parse(message); expect(types).to.include({ process: 'object', Buffer: 'function' }); }); it('runs in the correct scope when sandboxed', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: `${fixtures}/module/preload-context.js`, src: `file://${fixtures}/api/blank.html`, webpreferences: 'sandbox=yes' }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', // arguments passed to it should be available electron: 'undefined', // objects from the scope it is called from should not be available window: 'object', // the window object should be available localVar: 'undefined' // but local variables should not be exposed to the window }); }); it('preload script can require modules that still use "process" and "Buffer" when nodeintegration is off', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: `${fixtures}/module/preload-node-off-wrapper.js`, webpreferences: 'sandbox=no', src: `file://${fixtures}/api/blank.html` }); const types = JSON.parse(message); expect(types).to.include({ process: 'object', Buffer: 'function' }); }); it('receives ipc message in preload script', async () => { await loadWebView(w, { preload: `${fixtures}/module/preload-ipc.js`, src: `file://${fixtures}/pages/e.html` }); const message = 'boom!'; const { channel, args } = await w.executeJavaScript(`new Promise(resolve => { webview.send('ping', ${JSON.stringify(message)}) webview.addEventListener('ipc-message', ({channel, args}) => resolve({channel, args})) })`); expect(channel).to.equal('pong'); expect(args).to.deep.equal([message]); }); itremote('<webview>.sendToFrame()', async (fixtures: string) => { const w = new WebView(); w.setAttribute('nodeintegration', 'on'); w.setAttribute('webpreferences', 'contextIsolation=no'); w.setAttribute('preload', `file://${fixtures}/module/preload-ipc.js`); w.setAttribute('src', `file://${fixtures}/pages/ipc-message.html`); document.body.appendChild(w); const { frameId } = await new Promise<any>(resolve => w.addEventListener('ipc-message', resolve, { once: true })); const message = 'boom!'; w.sendToFrame(frameId, 'ping', message); const { channel, args } = await new Promise<any>(resolve => w.addEventListener('ipc-message', resolve, { once: true })); expect(channel).to.equal('pong'); expect(args).to.deep.equal([message]); }, [fixtures]); it('works without script tag in page', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: `${fixtures}/module/preload.js`, webpreferences: 'sandbox=no', src: `file://${fixtures}/pages/base-page.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object', Buffer: 'function' }); }); it('resolves relative URLs', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: '../module/preload.js', webpreferences: 'sandbox=no', src: `file://${fixtures}/pages/e.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object', Buffer: 'function' }); }); itremote('ignores empty values', async () => { const webview = new WebView(); for (const emptyValue of ['', null, undefined]) { webview.preload = emptyValue; expect(webview.preload).to.equal(''); } }); }); describe('httpreferrer attribute', () => { it('sets the referrer url', async () => { const referrer = 'http://github.com/'; const received = await new Promise<string | undefined>((resolve, reject) => { const server = http.createServer((req, res) => { try { resolve(req.headers.referer); } catch (e) { reject(e); } finally { res.end(); server.close(); } }); listen(server).then(({ url }) => { loadWebView(w, { httpreferrer: referrer, src: url }); }); }); expect(received).to.equal(referrer); }); }); describe('useragent attribute', () => { it('sets the user agent', async () => { const referrer = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko'; const message = await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/useragent.html`, useragent: referrer }); expect(message).to.equal(referrer); }); }); describe('disablewebsecurity attribute', () => { it('does not disable web security when not set', async () => { await loadWebView(w, { src: 'about:blank' }); const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`); expect(result).to.equal('failed'); }); it('disables web security when set', async () => { await loadWebView(w, { src: 'about:blank', disablewebsecurity: '' }); const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`); expect(result).to.equal('ok'); }); it('does not break node integration', async () => { const message = await loadWebViewAndWaitForMessage(w, { disablewebsecurity: '', nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/d.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object' }); }); it('does not break preload script', async () => { const message = await loadWebViewAndWaitForMessage(w, { disablewebsecurity: '', preload: `${fixtures}/module/preload.js`, webpreferences: 'sandbox=no', src: `file://${fixtures}/pages/e.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object', Buffer: 'function' }); }); }); describe('partition attribute', () => { it('inserts no node symbols when not set', async () => { const message = await loadWebViewAndWaitForMessage(w, { partition: 'test1', src: `file://${fixtures}/pages/c.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'undefined', module: 'undefined', process: 'undefined', global: 'undefined' }); }); it('inserts node symbols when set', async () => { const message = await loadWebViewAndWaitForMessage(w, { nodeintegration: 'on', partition: 'test2', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/d.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object' }); }); it('isolates storage for different id', async () => { await w.executeJavaScript('localStorage.setItem(\'test\', \'one\')'); const message = await loadWebViewAndWaitForMessage(w, { partition: 'test3', src: `file://${fixtures}/pages/partition/one.html` }); const parsedMessage = JSON.parse(message); expect(parsedMessage).to.include({ numberOfEntries: 0, testValue: null }); }); it('uses current session storage when no id is provided', async () => { await w.executeJavaScript('localStorage.setItem(\'test\', \'two\')'); const testValue = 'two'; const message = await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/partition/one.html` }); const parsedMessage = JSON.parse(message); expect(parsedMessage).to.include({ testValue }); }); }); describe('allowpopups attribute', () => { const generateSpecs = (description: string, webpreferences = '') => { describe(description, () => { it('can not open new window when not set', async () => { const message = await loadWebViewAndWaitForMessage(w, { webpreferences, src: `file://${fixtures}/pages/window-open-hide.html` }); expect(message).to.equal('null'); }); it('can open new window when set', async () => { const message = await loadWebViewAndWaitForMessage(w, { webpreferences, allowpopups: 'on', src: `file://${fixtures}/pages/window-open-hide.html` }); expect(message).to.equal('window'); }); }); }; generateSpecs('without sandbox'); generateSpecs('with sandbox', 'sandbox=yes'); }); describe('webpreferences attribute', () => { it('can enable nodeintegration', async () => { const message = await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/d.html`, webpreferences: 'nodeIntegration,contextIsolation=no' }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object' }); }); it('can disable web security and enable nodeintegration', async () => { await loadWebView(w, { src: 'about:blank', webpreferences: 'webSecurity=no, nodeIntegration=yes, contextIsolation=no' }); const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`); expect(result).to.equal('ok'); const type = await w.executeJavaScript('webview.executeJavaScript("typeof require")'); expect(type).to.equal('function'); }); }); }); describe('events', () => { useRemoteContext({ webPreferences: { webviewTag: true } }); let w: WebContents; before(async () => { const window = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); await window.loadURL(`file://${fixtures}/pages/blank.html`); w = window.webContents; }); afterEach(async () => { await w.executeJavaScript(`{ for (const el of document.querySelectorAll('webview')) el.remove(); }`); }); after(closeAllWindows); describe('ipc-message event', () => { it('emits when guest sends an ipc message to browser', async () => { const { frameId, channel, args } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/ipc-message.html`, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }, 'ipc-message'); expect(frameId).to.be.an('array').that.has.lengthOf(2); expect(channel).to.equal('channel'); expect(args).to.deep.equal(['arg1', 'arg2']); }); }); describe('page-title-updated event', () => { it('emits when title is set', async () => { const { title, explicitSet } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/a.html` }, 'page-title-updated'); expect(title).to.equal('test'); expect(explicitSet).to.be.true(); }); }); describe('page-favicon-updated event', () => { it('emits when favicon urls are received', async () => { const { favicons } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/a.html` }, 'page-favicon-updated'); expect(favicons).to.be.an('array').of.length(2); if (process.platform === 'win32') { expect(favicons[0]).to.match(/^file:\/\/\/[A-Z]:\/favicon.png$/i); } else { expect(favicons[0]).to.equal('file:///favicon.png'); } }); }); describe('did-redirect-navigation event', () => { it('is emitted on redirects', async () => { const server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } }); const { url } = await listen(server); defer(() => { server.close(); }); const event = await loadWebViewAndWaitForEvent(w, { src: `${url}/302` }, 'did-redirect-navigation'); expect(event.url).to.equal(`${url}/200`); expect(event.isInPlace).to.be.false(); expect(event.isMainFrame).to.be.true(); expect(event.frameProcessId).to.be.a('number'); expect(event.frameRoutingId).to.be.a('number'); }); }); describe('will-navigate event', () => { it('emits when a url that leads to outside of the page is loaded', async () => { const { url } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/webview-will-navigate.html` }, 'will-navigate'); expect(url).to.equal('http://host/'); }); }); describe('will-frame-navigate event', () => { it('emits when a link that leads to outside of the page is loaded', async () => { const { url, isMainFrame } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/webview-will-navigate.html` }, 'will-frame-navigate'); expect(url).to.equal('http://host/'); expect(isMainFrame).to.be.true(); }); it('emits when a link within an iframe, which leads to outside of the page, is loaded', async () => { await loadWebView(w, { src: `file://${fixtures}/pages/webview-will-navigate-in-frame.html`, nodeIntegration: '' }); const { url, frameProcessId, frameRoutingId } = await w.executeJavaScript(` new Promise((resolve, reject) => { let hasFrameNavigatedOnce = false; const webview = document.getElementById('webview'); webview.addEventListener('will-frame-navigate', ({url, isMainFrame, frameProcessId, frameRoutingId}) => { if (isMainFrame) return; if (hasFrameNavigatedOnce) resolve({ url, isMainFrame, frameProcessId, frameRoutingId, }); // First navigation is the initial iframe load within the <webview> hasFrameNavigatedOnce = true; }); webview.executeJavaScript('loadSubframe()'); }); `); expect(url).to.equal('http://host/'); expect(frameProcessId).to.be.a('number'); expect(frameRoutingId).to.be.a('number'); }); }); describe('did-navigate event', () => { it('emits when a url that leads to outside of the page is clicked', async () => { const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-will-navigate.html')).toString(); const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate'); expect(event.url).to.equal(pageUrl); }); }); describe('did-navigate-in-page event', () => { it('emits when an anchor link is clicked', async () => { const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-did-navigate-in-page.html')).toString(); const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate-in-page'); expect(event.url).to.equal(`${pageUrl}#test_content`); }); it('emits when window.history.replaceState is called', async () => { const { url } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/webview-did-navigate-in-page-with-history.html` }, 'did-navigate-in-page'); expect(url).to.equal('http://host/'); }); it('emits when window.location.hash is changed', async () => { const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-did-navigate-in-page-with-hash.html')).toString(); const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate-in-page'); expect(event.url).to.equal(`${pageUrl}#test`); }); }); describe('close event', () => { it('should fire when interior page calls window.close', async () => { await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/close.html` }, 'close'); }); }); describe('devtools-opened event', () => { it('should fire when webview.openDevTools() is called', async () => { await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/base-page.html` }, 'dom-ready'); await w.executeJavaScript(`new Promise((resolve) => { webview.openDevTools() webview.addEventListener('devtools-opened', () => resolve(), {once: true}) })`); await w.executeJavaScript('webview.closeDevTools()'); }); }); describe('devtools-closed event', () => { itremote('should fire when webview.closeDevTools() is called', async (fixtures: string) => { const webview = new WebView(); webview.src = `file://${fixtures}/pages/base-page.html`; document.body.appendChild(webview); await new Promise(resolve => webview.addEventListener('dom-ready', resolve, { once: true })); webview.openDevTools(); await new Promise(resolve => webview.addEventListener('devtools-opened', resolve, { once: true })); webview.closeDevTools(); await new Promise(resolve => webview.addEventListener('devtools-closed', resolve, { once: true })); }, [fixtures]); }); describe('devtools-focused event', () => { itremote('should fire when webview.openDevTools() is called', async (fixtures: string) => { const webview = new WebView(); webview.src = `file://${fixtures}/pages/base-page.html`; document.body.appendChild(webview); const waitForDevToolsFocused = new Promise(resolve => webview.addEventListener('devtools-focused', resolve, { once: true })); await new Promise(resolve => webview.addEventListener('dom-ready', resolve, { once: true })); webview.openDevTools(); await waitForDevToolsFocused; webview.closeDevTools(); }, [fixtures]); }); describe('dom-ready event', () => { it('emits when document is loaded', async () => { const server = http.createServer(() => {}); const { port } = await listen(server); await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/dom-ready.html?port=${port}` }, 'dom-ready'); }); itremote('throws a custom error when an API method is called before the event is emitted', () => { const expectedErrorMessage = 'The WebView must be attached to the DOM ' + 'and the dom-ready event emitted before this method can be called.'; const webview = new WebView(); expect(() => { webview.stop(); }).to.throw(expectedErrorMessage); }); }); describe('context-menu event', () => { it('emits when right-clicked in page', async () => { await loadWebView(w, { src: 'about:blank' }); const { params, url } = await w.executeJavaScript(`new Promise(resolve => { webview.addEventListener('context-menu', (e) => resolve({...e, url: webview.getURL() }), {once: true}) // Simulate right-click to create context-menu event. const opts = { x: 0, y: 0, button: 'right' }; webview.sendInputEvent({ ...opts, type: 'mouseDown' }); webview.sendInputEvent({ ...opts, type: 'mouseUp' }); })`); expect(params.pageURL).to.equal(url); expect(params.frame).to.be.undefined(); expect(params.x).to.be.a('number'); expect(params.y).to.be.a('number'); }); }); describe('found-in-page event', () => { itremote('emits when a request is made', async (fixtures: string) => { const webview = new WebView(); const didFinishLoad = new Promise(resolve => webview.addEventListener('did-finish-load', resolve, { once: true })); webview.src = `file://${fixtures}/pages/content.html`; document.body.appendChild(webview); // TODO(deepak1556): With https://codereview.chromium.org/2836973002 // focus of the webContents is required when triggering the api. // Remove this workaround after determining the cause for // incorrect focus. webview.focus(); await didFinishLoad; const activeMatchOrdinal = []; for (;;) { const foundInPage = new Promise<any>(resolve => webview.addEventListener('found-in-page', resolve, { once: true })); const requestId = webview.findInPage('virtual'); const event = await foundInPage; expect(event.result.requestId).to.equal(requestId); expect(event.result.matches).to.equal(3); activeMatchOrdinal.push(event.result.activeMatchOrdinal); if (event.result.activeMatchOrdinal === event.result.matches) { break; } } expect(activeMatchOrdinal).to.deep.equal([1, 2, 3]); webview.stopFindInPage('clearSelection'); }, [fixtures]); }); describe('will-attach-webview event', () => { itremote('does not emit when src is not changed', async () => { const webview = new WebView(); document.body.appendChild(webview); await setTimeout(); const expectedErrorMessage = 'The WebView must be attached to the DOM and the dom-ready event emitted before this method can be called.'; expect(() => { webview.stop(); }).to.throw(expectedErrorMessage); }); it('supports changing the web preferences', async () => { w.once('will-attach-webview', (event, webPreferences, params) => { params.src = `file://${path.join(fixtures, 'pages', 'c.html')}`; webPreferences.nodeIntegration = false; }); const message = await loadWebViewAndWaitForMessage(w, { nodeintegration: 'yes', src: `file://${fixtures}/pages/a.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'undefined', module: 'undefined', process: 'undefined', global: 'undefined' }); }); it('handler modifying params.instanceId does not break <webview>', async () => { w.once('will-attach-webview', (event, webPreferences, params) => { params.instanceId = null as any; }); await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/a.html` }); }); it('supports preventing a webview from being created', async () => { w.once('will-attach-webview', event => event.preventDefault()); await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/c.html` }, 'destroyed'); }); it('supports removing the preload script', async () => { w.once('will-attach-webview', (event, webPreferences, params) => { params.src = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-stripped-preload.html')).toString(); delete webPreferences.preload; }); const message = await loadWebViewAndWaitForMessage(w, { nodeintegration: 'yes', preload: path.join(fixtures, 'module', 'preload-set-global.js'), src: `file://${fixtures}/pages/a.html` }); expect(message).to.equal('undefined'); }); }); describe('media-started-playing and media-paused events', () => { it('emits when audio starts and stops playing', async function () { if (!await w.executeJavaScript('document.createElement(\'audio\').canPlayType(\'audio/wav\')')) { return this.skip(); } await loadWebView(w, { src: blankPageUrl }); // With the new autoplay policy, audio elements must be unmuted // see https://goo.gl/xX8pDD. await w.executeJavaScript(`new Promise(resolve => { webview.executeJavaScript(\` const audio = document.createElement("audio") audio.src = "../assets/tone.wav" document.body.appendChild(audio); audio.play() \`, true) webview.addEventListener('media-started-playing', () => resolve(), {once: true}) })`); await w.executeJavaScript(`new Promise(resolve => { webview.executeJavaScript(\` document.querySelector("audio").pause() \`, true) webview.addEventListener('media-paused', () => resolve(), {once: true}) })`); }); }); }); describe('methods', () => { let w: WebContents; before(async () => { const window = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); await window.loadURL(`file://${fixtures}/pages/blank.html`); w = window.webContents; }); afterEach(async () => { await w.executeJavaScript(`{ for (const el of document.querySelectorAll('webview')) el.remove(); }`); }); after(closeAllWindows); describe('<webview>.reload()', () => { it('should emit beforeunload handler', async () => { await loadWebView(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/beforeunload-false.html` }); // Event handler has to be added before reload. const channel = await w.executeJavaScript(`new Promise(resolve => { webview.addEventListener('ipc-message', e => resolve(e.channel)) webview.reload(); })`); expect(channel).to.equal('onbeforeunload'); }); }); describe('<webview>.goForward()', () => { useRemoteContext({ webPreferences: { webviewTag: true } }); itremote('should work after a replaced history entry', async (fixtures: string) => { function waitForEvent (target: EventTarget, event: string) { return new Promise<any>(resolve => target.addEventListener(event, resolve, { once: true })); } function waitForEvents (target: EventTarget, ...events: string[]) { return Promise.all(events.map(event => waitForEvent(webview, event))); } const webview = new WebView(); webview.setAttribute('nodeintegration', 'on'); webview.setAttribute('webpreferences', 'contextIsolation=no'); webview.src = `file://${fixtures}/pages/history-replace.html`; document.body.appendChild(webview); { const [e] = await waitForEvents(webview, 'ipc-message', 'did-stop-loading'); expect(e.channel).to.equal('history'); expect(e.args[0]).to.equal(1); expect(webview.canGoBack()).to.be.false(); expect(webview.canGoForward()).to.be.false(); } webview.src = `file://${fixtures}/pages/base-page.html`; await new Promise<void>(resolve => webview.addEventListener('did-stop-loading', resolve, { once: true })); expect(webview.canGoBack()).to.be.true(); expect(webview.canGoForward()).to.be.false(); webview.goBack(); { const [e] = await waitForEvents(webview, 'ipc-message', 'did-stop-loading'); expect(e.channel).to.equal('history'); expect(e.args[0]).to.equal(2); expect(webview.canGoBack()).to.be.false(); expect(webview.canGoForward()).to.be.true(); } webview.goForward(); await new Promise<void>(resolve => webview.addEventListener('did-stop-loading', resolve, { once: true })); expect(webview.canGoBack()).to.be.true(); expect(webview.canGoForward()).to.be.false(); }, [fixtures]); }); describe('<webview>.clearHistory()', () => { it('should clear the navigation history', async () => { await loadWebView(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: blankPageUrl }); // Navigation must be triggered by a user gesture to make canGoBack() return true await w.executeJavaScript('webview.executeJavaScript(`history.pushState(null, "", "foo.html")`, true)'); expect(await w.executeJavaScript('webview.canGoBack()')).to.be.true(); await w.executeJavaScript('webview.clearHistory()'); expect(await w.executeJavaScript('webview.canGoBack()')).to.be.false(); }); }); describe('executeJavaScript', () => { it('can return the result of the executed script', async () => { await loadWebView(w, { src: 'about:blank' }); const jsScript = "'4'+2"; const expectedResult = '42'; const result = await w.executeJavaScript(`webview.executeJavaScript(${JSON.stringify(jsScript)})`); expect(result).to.equal(expectedResult); }); }); it('supports inserting CSS', async () => { await loadWebView(w, { src: `file://${fixtures}/pages/base-page.html` }); await w.executeJavaScript('webview.insertCSS(\'body { background-repeat: round; }\')'); const result = await w.executeJavaScript('webview.executeJavaScript(\'window.getComputedStyle(document.body).getPropertyValue("background-repeat")\')'); expect(result).to.equal('round'); }); it('supports removing inserted CSS', async () => { await loadWebView(w, { src: `file://${fixtures}/pages/base-page.html` }); const key = await w.executeJavaScript('webview.insertCSS(\'body { background-repeat: round; }\')'); await w.executeJavaScript(`webview.removeInsertedCSS(${JSON.stringify(key)})`); const result = await w.executeJavaScript('webview.executeJavaScript(\'window.getComputedStyle(document.body).getPropertyValue("background-repeat")\')'); expect(result).to.equal('repeat'); }); describe('sendInputEvent', () => { it('can send keyboard event', async () => { await loadWebViewAndWaitForEvent(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/onkeyup.html` }, 'dom-ready'); const waitForIpcMessage = w.executeJavaScript('new Promise(resolve => webview.addEventListener("ipc-message", e => resolve({...e})), {once: true})'); w.executeJavaScript(`webview.sendInputEvent({ type: 'keyup', keyCode: 'c', modifiers: ['shift'] })`); const { channel, args } = await waitForIpcMessage; expect(channel).to.equal('keyup'); expect(args).to.deep.equal(['C', 'KeyC', 67, true, false]); }); it('can send mouse event', async () => { await loadWebViewAndWaitForEvent(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/onmouseup.html` }, 'dom-ready'); const waitForIpcMessage = w.executeJavaScript('new Promise(resolve => webview.addEventListener("ipc-message", e => resolve({...e})), {once: true})'); w.executeJavaScript(`webview.sendInputEvent({ type: 'mouseup', modifiers: ['ctrl'], x: 10, y: 20 })`); const { channel, args } = await waitForIpcMessage; expect(channel).to.equal('mouseup'); expect(args).to.deep.equal([10, 20, false, true]); }); }); describe('<webview>.getWebContentsId', () => { it('can return the WebContents ID', async () => { await loadWebView(w, { src: 'about:blank' }); expect(await w.executeJavaScript('webview.getWebContentsId()')).to.be.a('number'); }); }); ifdescribe(features.isPrintingEnabled())('<webview>.printToPDF()', () => { it('rejects on incorrectly typed parameters', async () => { const badTypes = { landscape: [], displayHeaderFooter: '123', printBackground: 2, scale: 'not-a-number', pageSize: 'IAmAPageSize', margins: 'terrible', pageRanges: { oops: 'im-not-the-right-key' }, headerTemplate: [1, 2, 3], footerTemplate: [4, 5, 6], preferCSSPageSize: 'no' }; // These will hard crash in Chromium unless we type-check for (const [key, value] of Object.entries(badTypes)) { const param = { [key]: value }; const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'; await loadWebView(w, { src }); await expect(w.executeJavaScript(`webview.printToPDF(${JSON.stringify(param)})`)).to.eventually.be.rejected(); } }); it('can print to PDF', async () => { const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'; await loadWebView(w, { src }); const data = await w.executeJavaScript('webview.printToPDF({})'); expect(data).to.be.an.instanceof(Uint8Array).that.is.not.empty(); }); }); describe('DOM events', () => { for (const [description, sandbox] of [ ['without sandbox', false] as const, ['with sandbox', true] as const ]) { describe(description, () => { it('emits focus event', async () => { await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/a.html`, webpreferences: `sandbox=${sandbox ? 'yes' : 'no'}` }, 'dom-ready'); // If this test fails, check if webview.focus() still works. await w.executeJavaScript(`new Promise(resolve => { webview.addEventListener('focus', () => resolve(), {once: true}); webview.focus(); })`); }); }); } }); // TODO(miniak): figure out why this is failing on windows ifdescribe(process.platform !== 'win32')('<webview>.capturePage()', () => { it('returns a Promise with a NativeImage', async function () { this.retries(5); const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'; await loadWebViewAndWaitForEvent(w, { src }, 'did-stop-loading'); const image = await w.executeJavaScript('webview.capturePage()'); expect(image.isEmpty()).to.be.false(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha const imgBuffer = image.toPNG(); expect(imgBuffer[25]).to.equal(6); }); it('returns a Promise with a NativeImage in the renderer', async function () { this.retries(5); const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'; await loadWebViewAndWaitForEvent(w, { src }, 'did-stop-loading'); const byte = await w.executeJavaScript(`new Promise(resolve => { webview.capturePage().then(image => { resolve(image.toPNG()[25]) }); })`); expect(byte).to.equal(6); }); }); // FIXME(zcbenz): Disabled because of moving to OOPIF webview. xdescribe('setDevToolsWebContents() API', () => { /* it('sets webContents of webview as devtools', async () => { const webview2 = new WebView(); loadWebView(webview2); // Setup an event handler for further usage. const waitForDomReady = waitForEvent(webview2, 'dom-ready'); loadWebView(webview, { src: 'about:blank' }); await waitForEvent(webview, 'dom-ready'); webview.getWebContents().setDevToolsWebContents(webview2.getWebContents()); webview.getWebContents().openDevTools(); await waitForDomReady; // Its WebContents should be a DevTools. const devtools = webview2.getWebContents(); expect(devtools.getURL().startsWith('devtools://devtools')).to.be.true(); const name = await devtools.executeJavaScript('InspectorFrontendHost.constructor.name'); document.body.removeChild(webview2); expect(name).to.be.equal('InspectorFrontendHostImpl'); }); */ }); }); describe('basic auth', () => { let w: WebContents; before(async () => { const window = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); await window.loadURL(`file://${fixtures}/pages/blank.html`); w = window.webContents; }); afterEach(async () => { await w.executeJavaScript(`{ for (const el of document.querySelectorAll('webview')) el.remove(); }`); }); after(closeAllWindows); it('should authenticate with correct credentials', async () => { const message = 'Authenticated'; const server = http.createServer((req, res) => { const credentials = auth(req)!; if (credentials.name === 'test' && credentials.pass === 'test') { res.end(message); } else { res.end('failed'); } }); defer(() => { server.close(); }); const { port } = await listen(server); const e = await loadWebViewAndWaitForEvent(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/basic-auth.html?port=${port}` }, 'ipc-message'); expect(e.channel).to.equal(message); }); }); });
closed
electron/electron
https://github.com/electron/electron
39,959
[Bug]: set "transparent" to true and "titleBarStyle” to "hidden", a title bar is shown when window loses focus, "backgroundMaterial" not work until resizing the window.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 27.0.0-beta.5 ### What operating system are you using? Windows ### Operating System Version Windows 11 - 22H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior 1、The window should show without a title bar. 2、The window should be transparent and backgrounds should be "acrylic" style. ![image](https://github.com/electron/electron/assets/13523898/42e404c0-7215-4810-9603-06d93e0b95ad) ### Actual Behavior 1、window background not transparent and not "acrylic" style until I resize the window. ![image](https://github.com/electron/electron/assets/13523898/13e58cf2-4695-4d60-8cf1-f6d347febdf0) after resize the window: ![image](https://github.com/electron/electron/assets/13523898/87c3ed1a-0858-4812-a5f5-857034d9e6b3) 2、If the window loses focus, a title bar is shown and it can't interact. ![image](https://github.com/electron/electron/assets/13523898/2a733fde-4f60-4947-9891-97f18073890d) ### Testcase Gist URL https://gist.github.com/d51806da56e0f6103859d0164b22a80a ### Additional Information _No response_
https://github.com/electron/electron/issues/39959
https://github.com/electron/electron/pull/40749
7995c56fb0b20b254b379a43e1435a81695a3c7d
a208d45aca3b19fb661c630880451e26d46c92a6
2023-09-23T15:15:43Z
c++
2024-01-02T18:59:47Z
patches/chromium/fix_activate_background_material_on_windows.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: clavin <[email protected]> Date: Wed, 30 Aug 2023 18:15:36 -0700 Subject: fix: activate background material on windows This patch adds a condition to the HWND message handler to allow windows with translucent background materials to become activated. This patch likely can't be upstreamed as-is, as Chromium doesn't have this use case in mind currently. diff --git a/ui/views/win/hwnd_message_handler.cc b/ui/views/win/hwnd_message_handler.cc index 23905a6b7f739ff3c6f391f984527ef5d2ed0bd9..ee72bad1b884677b02cc2f86ea307742e5528bad 100644 --- a/ui/views/win/hwnd_message_handler.cc +++ b/ui/views/win/hwnd_message_handler.cc @@ -901,7 +901,7 @@ void HWNDMessageHandler::FrameTypeChanged() { void HWNDMessageHandler::PaintAsActiveChanged() { if (!delegate_->HasNonClientView() || !delegate_->CanActivate() || - !delegate_->HasFrame() || + (!delegate_->HasFrame() && !is_translucent_) || (delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN)) { return; }
closed
electron/electron
https://github.com/electron/electron
39,959
[Bug]: set "transparent" to true and "titleBarStyle” to "hidden", a title bar is shown when window loses focus, "backgroundMaterial" not work until resizing the window.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 27.0.0-beta.5 ### What operating system are you using? Windows ### Operating System Version Windows 11 - 22H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior 1、The window should show without a title bar. 2、The window should be transparent and backgrounds should be "acrylic" style. ![image](https://github.com/electron/electron/assets/13523898/42e404c0-7215-4810-9603-06d93e0b95ad) ### Actual Behavior 1、window background not transparent and not "acrylic" style until I resize the window. ![image](https://github.com/electron/electron/assets/13523898/13e58cf2-4695-4d60-8cf1-f6d347febdf0) after resize the window: ![image](https://github.com/electron/electron/assets/13523898/87c3ed1a-0858-4812-a5f5-857034d9e6b3) 2、If the window loses focus, a title bar is shown and it can't interact. ![image](https://github.com/electron/electron/assets/13523898/2a733fde-4f60-4947-9891-97f18073890d) ### Testcase Gist URL https://gist.github.com/d51806da56e0f6103859d0164b22a80a ### Additional Information _No response_
https://github.com/electron/electron/issues/39959
https://github.com/electron/electron/pull/40749
7995c56fb0b20b254b379a43e1435a81695a3c7d
a208d45aca3b19fb661c630880451e26d46c92a6
2023-09-23T15:15:43Z
c++
2024-01-02T18:59:47Z
shell/browser/ui/win/electron_desktop_window_tree_host_win.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/win/electron_desktop_window_tree_host_win.h" #include "base/win/windows_version.h" #include "electron/buildflags/buildflags.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/win/dark_mode.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/win/hwnd_metrics.h" #include "ui/base/win/shell.h" namespace electron { ElectronDesktopWindowTreeHostWin::ElectronDesktopWindowTreeHostWin( NativeWindowViews* native_window_view, views::DesktopNativeWidgetAura* desktop_native_widget_aura) : views::DesktopWindowTreeHostWin(native_window_view->widget(), desktop_native_widget_aura), native_window_view_(native_window_view) {} ElectronDesktopWindowTreeHostWin::~ElectronDesktopWindowTreeHostWin() = default; bool ElectronDesktopWindowTreeHostWin::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { const bool dark_mode_supported = win::IsDarkModeSupported(); if (dark_mode_supported && message == WM_NCCREATE) { win::SetDarkModeForWindow(GetAcceleratedWidget()); ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); } else if (dark_mode_supported && message == WM_DESTROY) { ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); } return native_window_view_->PreHandleMSG(message, w_param, l_param, result); } bool ElectronDesktopWindowTreeHostWin::ShouldPaintAsActive() const { if (force_should_paint_as_active_.has_value()) { return force_should_paint_as_active_.value(); } return views::DesktopWindowTreeHostWin::ShouldPaintAsActive(); } bool ElectronDesktopWindowTreeHostWin::GetDwmFrameInsetsInPixels( gfx::Insets* insets) const { // Set DWMFrameInsets to prevent maximized frameless window from bleeding // into other monitors. if (IsMaximized() && !native_window_view_->has_frame()) { // This would be equivalent to calling: // DwmExtendFrameIntoClientArea({0, 0, 0, 0}); // // which means do not extend window frame into client area. It is almost // a no-op, but it can tell Windows to not extend the window frame to be // larger than current workspace. // // See also: // https://devblogs.microsoft.com/oldnewthing/20150304-00/?p=44543 *insets = gfx::Insets(); return true; } return false; } bool ElectronDesktopWindowTreeHostWin::GetClientAreaInsets( gfx::Insets* insets, HMONITOR monitor) const { // Windows by default extends the maximized window slightly larger than // current workspace, for frameless window since the standard frame has been // removed, the client area would then be drew outside current workspace. // // Indenting the client area can fix this behavior. if (IsMaximized() && !native_window_view_->has_frame()) { // The insets would be eventually passed to WM_NCCALCSIZE, which takes // the metrics under the DPI of _main_ monitor instead of current monitor. // // Please make sure you tested maximized frameless window under multiple // monitors with different DPIs before changing this code. const int thickness = ::GetSystemMetrics(SM_CXSIZEFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER); *insets = gfx::Insets::TLBR(thickness, thickness, thickness, thickness); return true; } return false; } bool ElectronDesktopWindowTreeHostWin::HandleMouseEventForCaption( UINT message) const { // Windows does not seem to generate WM_NCPOINTERDOWN/UP touch events for // caption buttons with WCO. This results in a no-op for // HWNDMessageHandler::HandlePointerEventTypeTouchOrNonClient and // WM_SYSCOMMAND is not generated for the touch action. However, Windows will // also generate a mouse event for every touch action and this gets handled in // HWNDMessageHandler::HandleMouseEventInternal. // With https://chromium-review.googlesource.com/c/chromium/src/+/1048877/ // Chromium lets the OS handle caption buttons for FrameMode::SYSTEM_DRAWN but // again this does not generate the SC_MINIMIZE, SC_MAXIMIZE, SC_RESTORE // commands when Non-client mouse events are generated for HTCLOSE, // HTMINBUTTON, HTMAXBUTTON. To workaround this issue, wit this delegate we // let chromium handle the mouse events via // HWNDMessageHandler::HandleMouseInputForCaption instead of the OS and this // will generate the necessary system commands to perform caption button // actions due to the DefWindowProc call. // https://source.chromium.org/chromium/chromium/src/+/main:ui/views/win/hwnd_message_handler.cc;l=3611 return native_window_view_->IsWindowControlsOverlayEnabled(); } void ElectronDesktopWindowTreeHostWin::OnNativeThemeUpdated( ui::NativeTheme* observed_theme) { HWND hWnd = GetAcceleratedWidget(); win::SetDarkModeForWindow(hWnd); auto* os_info = base::win::OSInfo::GetInstance(); auto const version = os_info->version(); // Toggle the nonclient area active state to force a redraw (Win10 workaround) if (version < base::win::Version::WIN11) { // When handling WM_NCACTIVATE messages, Chromium logical ORs the wParam and // the value of ShouldPaintAsActive() - so if the latter is true, it's not // possible to toggle the title bar to inactive. Force it to false while we // send the message so that the wParam value will always take effect. Refs // https://source.chromium.org/chromium/chromium/src/+/main:ui/views/win/hwnd_message_handler.cc;l=2332-2381;drc=e6361d070be0adc585ebbff89fec76e2df4ad768 force_should_paint_as_active_ = false; ::SendMessage(hWnd, WM_NCACTIVATE, hWnd != ::GetActiveWindow(), 0); // Clear forced value and tell Chromium the value changed to get a repaint force_should_paint_as_active_.reset(); PaintAsActiveChanged(); } } bool ElectronDesktopWindowTreeHostWin::ShouldWindowContentsBeTransparent() const { // Window should be marked as opaque if no transparency setting has been set, // otherwise videos rendered in the window will trigger a DirectComposition // redraw for every frame. // https://github.com/electron/electron/pull/39895 return native_window_view_->GetOpacity() < 1.0 || native_window_view_->transparent(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,673
[Feature Request]: Document if accelerators are case insensitive or not
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 It's unclear reading the [docs](https://www.electronjs.org/docs/latest/api/accelerator) if accelerators are case insensitive or not. I assume they are because it seems nonsensical for them not to be, but at the same time I see an inconsistent casing being used in the docs, e.g. `PageUp` vs `numdiv`, so it's confusing. ### Proposed Solution Mentioning if they are case insensitive or not. And really if they are not case insensitive they should be. ### Alternatives Considered Checking manually, but that only solves the problem for me, not for everybody else who needs this bit of information. ### Additional Information _No response_
https://github.com/electron/electron/issues/38673
https://github.com/electron/electron/pull/40783
84ba0c6c7d248d7121d1103d2844e7a124b59e3f
3a06047e6153ef494b134970892665c55c32931e
2023-06-08T08:58:39Z
c++
2024-01-04T15:06:12Z
docs/api/accelerator.md
# Accelerator > Define keyboard shortcuts. Accelerators are strings that can contain multiple modifiers and a single key code, combined by the `+` character, and are used to define keyboard shortcuts throughout your application. Examples: * `CommandOrControl+A` * `CommandOrControl+Shift+Z` Shortcuts are registered with the [`globalShortcut`](global-shortcut.md) module using the [`register`](global-shortcut.md#globalshortcutregisteraccelerator-callback) method, i.e. ```js const { app, globalShortcut } = require('electron') app.whenReady().then(() => { // Register a 'CommandOrControl+Y' shortcut listener. globalShortcut.register('CommandOrControl+Y', () => { // Do stuff when Y and either Command/Control is pressed. }) }) ``` ## Platform notice On Linux and Windows, the `Command` key does not have any effect so use `CommandOrControl` which represents `Command` on macOS and `Control` on Linux and Windows to define some accelerators. Use `Alt` instead of `Option`. The `Option` key only exists on macOS, whereas the `Alt` key is available on all platforms. The `Super` (or `Meta`) key is mapped to the `Windows` key on Windows and Linux and `Cmd` on macOS. ## Available modifiers * `Command` (or `Cmd` for short) * `Control` (or `Ctrl` for short) * `CommandOrControl` (or `CmdOrCtrl` for short) * `Alt` * `Option` * `AltGr` * `Shift` * `Super` * `Meta` ## Available key codes * `0` to `9` * `A` to `Z` * `F1` to `F24` * Various Punctuation: `)`, `!`, `@`, `#`, `$`, `%`, `^`, `&`, `*`, `(`, `:`, `;`, `:`, `+`, `=`, `<`, `,`, `_`, `-`, `>`, `.`, `?`, `/`, `~`, `` ` ``, `{`, `]`, `[`, `|`, `\`, `}`, `"` * `Plus` * `Space` * `Tab` * `Capslock` * `Numlock` * `Scrolllock` * `Backspace` * `Delete` * `Insert` * `Return` (or `Enter` as alias) * `Up`, `Down`, `Left` and `Right` * `Home` and `End` * `PageUp` and `PageDown` * `Escape` (or `Esc` for short) * `VolumeUp`, `VolumeDown` and `VolumeMute` * `MediaNextTrack`, `MediaPreviousTrack`, `MediaStop` and `MediaPlayPause` * `PrintScreen` * NumPad Keys * `num0` - `num9` * `numdec` - decimal key * `numadd` - numpad `+` key * `numsub` - numpad `-` key * `nummult` - numpad `*` key * `numdiv` - numpad `÷` key
closed
electron/electron
https://github.com/electron/electron
40,207
[Bug]: Setting color-scheme to dark changes text color but not background color for webviews
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior The background colour of the webview should be black and the text colour should be white. ### Actual Behavior The background colour of the webview is white and the text colour is also white, making it impossible to read the text. ### Testcase Gist URL https://gist.github.com/BrandonXLF/4a6f65cba592bece8d1413f7a8730dca ### Additional Information Continuation of #36122 as it became stale Issue applies to both the `color-scheme` CSS property when it's applied to `:root`/`html` and the `color-scheme` meta tag, but it works fine when applied to other elements like `textarea`. The issue is not present in iframes.
https://github.com/electron/electron/issues/40207
https://github.com/electron/electron/pull/40301
8c71e2adc9b47f8d9e9ad07be9e6a9b3a764a670
50860712943da0feabcb668b264c35b7837286c0
2023-10-15T09:46:05Z
c++
2024-01-05T04:00:27Z
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`, a [`WebContentsView`](web-contents-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="https://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="https://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="https://example.com/"></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. This value can only be modified before the first navigation. ### `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** ```js @ts-expect-error=[3] 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[, options])` * `url` string * `options` Object (optional) * `headers` Record<string, string> (optional) - HTTP request headers. 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>.centerSelection()` Centers the current text selection 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>.scrollToTop()` Scrolls to the top of the current `<webview>`. #### `<webview>.scrollToBottom()` Scrolls to the bottom of the current `<webview>`. #### `<webview>.adjustSelection(options)` * `options` Object * `start` Number (optional) - Amount to shift the start index of the current selection. * `end` Number (optional) - Amount to shift the end index of the current selection. Adjusts the current text selection starting and ending points in the focused frame by the given amounts. A negative amount moves the selection towards the beginning of the document, and a positive amount moves the selection towards the end of the document. See [`webContents.adjustSelection`](web-contents.md#contentsadjustselectionoptions) for examples. ### `<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` in microns. Returns `Promise<void>` Prints `webview`'s web page. Same as `webContents.print([options])`. ### `<webview>.printToPDF(options)` * `options` Object * `landscape` boolean (optional) - Paper orientation.`true` for landscape, `false` for portrait. Defaults to false. * `displayHeaderFooter` boolean (optional) - Whether to display header and footer. Defaults to false. * `printBackground` boolean (optional) - Whether to print background graphics. Defaults to false. * `scale` number(optional) - Scale of the webpage rendering. Defaults to 1. * `pageSize` string | Size (optional) - Specify page size of the generated PDF. Can be `A0`, `A1`, `A2`, `A3`, `A4`, `A5`, `A6`, `Legal`, `Letter`, `Tabloid`, `Ledger`, or an Object containing `height` and `width` in inches. Defaults to `Letter`. * `margins` Object (optional) * `top` number (optional) - Top margin in inches. Defaults to 1cm (~0.4 inches). * `bottom` number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches). * `left` number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches). * `right` number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches). * `pageRanges` string (optional) - Page ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages. * `headerTemplate` string (optional) - HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: `date` (formatted print date), `title` (document title), `url` (document location), `pageNumber` (current page number) and `totalPages` (total pages in the document). For example, `<span class=title></span>` would generate span containing the title. * `footerTemplate` string (optional) - HTML template for the print footer. Should use the same format as the `headerTemplate`. * `preferCSSPageSize` boolean (optional) - Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size. * `generateTaggedPDF` boolean (optional) _Experimental_ - Whether or not to generate a tagged (accessible) PDF. Defaults to false. As this property is experimental, the generated PDF may not adhere fully to PDF/UA and WCAG standards. 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. ```js @ts-expect-error=[3] 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. ```js @ts-expect-error=[3,6] const webview = document.querySelector('webview') webview.addEventListener('found-in-page', (e) => { webview.stopFindInPage('keepSelection') }) const requestId = webview.findInPage('test') console.log(requestId) ``` ### 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: 'will-frame-navigate' Returns: * `url` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a user or the page wants to start navigation anywhere in the `<webview>` or any frames embedded within. 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. ```js @ts-expect-error=[3] 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: ```js @ts-expect-error=[4,7] // In embedder page. const webview = document.querySelector('webview') webview.addEventListener('ipc-message', (event) => { console.log(event.channel) // Prints "pong" }) webview.send('ping') ``` ```js // In guest page. const { ipcRenderer } = require('electron') ipcRenderer.on('ping', () => { ipcRenderer.sendToHost('pong') }) ``` ### Event: 'render-process-gone' Returns: * `details` [RenderProcessGoneDetails](structures/render-process-gone-details.md) Fired when the renderer process unexpectedly disappears. This is normally because it was crashed or killed. ### 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-open-url' Returns: * `url` string - URL of the link that was clicked or selected. Emitted when a link is clicked in DevTools or 'Open in new tab' is selected for a link in its context menu. ### 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://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/runtime_enabled_features.json5 [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. * `formControlType` string - The source that the context menu was invoked on. Possible values include `none`, `button-button`, `field-set`, `input-button`, `input-checkbox`, `input-color`, `input-date`, `input-datetime-local`, `input-email`, `input-file`, `input-hidden`, `input-image`, `input-month`, `input-number`, `input-password`, `input-radio`, `input-range`, `input-reset`, `input-search`, `input-submit`, `input-telephone`, `input-text`, `input-time`, `input-url`, `input-week`, `output`, `reset-button`, `select-list`, `select-list`, `select-multiple`, `select-one`, `submit-button`, and `text-area`, * `inputFieldType` string _Deprecated_ - If the context menu was invoked on an input field, the type of that field. Possible values include `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
40,207
[Bug]: Setting color-scheme to dark changes text color but not background color for webviews
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior The background colour of the webview should be black and the text colour should be white. ### Actual Behavior The background colour of the webview is white and the text colour is also white, making it impossible to read the text. ### Testcase Gist URL https://gist.github.com/BrandonXLF/4a6f65cba592bece8d1413f7a8730dca ### Additional Information Continuation of #36122 as it became stale Issue applies to both the `color-scheme` CSS property when it's applied to `:root`/`html` and the `color-scheme` meta tag, but it works fine when applied to other elements like `textarea`. The issue is not present in iframes.
https://github.com/electron/electron/issues/40207
https://github.com/electron/electron/pull/40301
8c71e2adc9b47f8d9e9ad07be9e6a9b3a764a670
50860712943da0feabcb668b264c35b7837286c0
2023-10-15T09:46:05Z
c++
2024-01-05T04:00:27Z
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 <utility> #include <vector> #include "base/containers/contains.h" #include "base/containers/fixed_flat_map.h" #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/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.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/embedder_support/user_agent_utils.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/navigation_controller_impl.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/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/input/native_web_keyboard_event.h" #include "content/public/common/referrer_type_converters.h" #include "content/public/common/result_codes.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 "media/base/mime_util.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_navigation_throttle.h" #include "shell/browser/file_select_helper.h" #include "shell/browser/native_window.h" #include "shell/browser/osr/osr_render_widget_host_view.h" #include "shell/browser/osr/osr_web_contents_view.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/optional_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/language_util.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "shell/common/thread_restrictions.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(IS_WIN) #include "shell/browser/native_window_views.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/linux/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 "chrome/browser/printing/print_view_manager_base.h" #include "components/printing/browser/print_manager_utils.h" #include "components/printing/browser/print_to_pdf/pdf_print_result.h" #include "components/printing/browser/print_to_pdf/pdf_print_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" // nogncheck #include "printing/page_range.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #endif #endif // BUILDFLAG(ENABLE_PRINTING) #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_document_helper.h" // nogncheck #include "shell/browser/electron_pdf_document_helper_client.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif #if !IS_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) { using Val = printing::mojom::MarginType; static constexpr auto Lookup = base::MakeFixedFlatMap<base::StringPiece, Val>({ {"custom", Val::kCustomMargins}, {"default", Val::kDefaultMargins}, {"none", Val::kNoMargins}, {"printableArea", Val::kPrintableAreaMargins}, }); return FromV8WithLookup(isolate, val, Lookup, out); } }; template <> struct Converter<printing::mojom::DuplexMode> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::DuplexMode* out) { using Val = printing::mojom::DuplexMode; static constexpr auto Lookup = base::MakeFixedFlatMap<base::StringPiece, Val>({ {"longEdge", Val::kLongEdge}, {"shortEdge", Val::kShortEdge}, {"simplex", Val::kSimplex}, }); return FromV8WithLookup(isolate, val, Lookup, out); } }; #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::JavaScriptDialogType> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, content::JavaScriptDialogType val) { switch (val) { case content::JAVASCRIPT_DIALOG_TYPE_ALERT: return gin::ConvertToV8(isolate, "alert"); case content::JAVASCRIPT_DIALOG_TYPE_CONFIRM: return gin::ConvertToV8(isolate, "confirm"); case content::JAVASCRIPT_DIALOG_TYPE_PROMPT: return gin::ConvertToV8(isolate, "prompt"); } } }; template <> struct Converter<content::SavePageType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::SavePageType* out) { using Val = content::SavePageType; static constexpr auto Lookup = base::MakeFixedFlatMap<base::StringPiece, Val>({ {"htmlcomplete", Val::SAVE_PAGE_TYPE_AS_COMPLETE_HTML}, {"htmlonly", Val::SAVE_PAGE_TYPE_AS_ONLY_HTML}, {"mhtml", Val::SAVE_PAGE_TYPE_AS_MHTML}, }); return FromV8WithLowerLookup(isolate, val, Lookup, out); } }; 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 Val = electron::api::WebContents::Type; static constexpr auto Lookup = base::MakeFixedFlatMap<base::StringPiece, Val>({ {"backgroundPage", Val::kBackgroundPage}, {"browserView", Val::kBrowserView}, {"offscreen", Val::kOffScreen}, {"webview", Val::kWebView}, }); return FromV8WithLookup(isolate, val, Lookup, out); } }; 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::api { namespace { constexpr base::StringPiece CursorTypeToString( ui::mojom::CursorType cursor_type) { switch (cursor_type) { case ui::mojom::CursorType::kPointer: return "pointer"; case ui::mojom::CursorType::kCross: return "crosshair"; case ui::mojom::CursorType::kHand: return "hand"; case ui::mojom::CursorType::kIBeam: return "text"; case ui::mojom::CursorType::kWait: return "wait"; case ui::mojom::CursorType::kHelp: return "help"; case ui::mojom::CursorType::kEastResize: return "e-resize"; case ui::mojom::CursorType::kNorthResize: return "n-resize"; case ui::mojom::CursorType::kNorthEastResize: return "ne-resize"; case ui::mojom::CursorType::kNorthWestResize: return "nw-resize"; case ui::mojom::CursorType::kSouthResize: return "s-resize"; case ui::mojom::CursorType::kSouthEastResize: return "se-resize"; case ui::mojom::CursorType::kSouthWestResize: return "sw-resize"; case ui::mojom::CursorType::kWestResize: return "w-resize"; case ui::mojom::CursorType::kNorthSouthResize: return "ns-resize"; case ui::mojom::CursorType::kEastWestResize: return "ew-resize"; case ui::mojom::CursorType::kNorthEastSouthWestResize: return "nesw-resize"; case ui::mojom::CursorType::kNorthWestSouthEastResize: return "nwse-resize"; case ui::mojom::CursorType::kColumnResize: return "col-resize"; case ui::mojom::CursorType::kRowResize: return "row-resize"; case ui::mojom::CursorType::kMiddlePanning: return "m-panning"; case ui::mojom::CursorType::kMiddlePanningVertical: return "m-panning-vertical"; case ui::mojom::CursorType::kMiddlePanningHorizontal: return "m-panning-horizontal"; case ui::mojom::CursorType::kEastPanning: return "e-panning"; case ui::mojom::CursorType::kNorthPanning: return "n-panning"; case ui::mojom::CursorType::kNorthEastPanning: return "ne-panning"; case ui::mojom::CursorType::kNorthWestPanning: return "nw-panning"; case ui::mojom::CursorType::kSouthPanning: return "s-panning"; case ui::mojom::CursorType::kSouthEastPanning: return "se-panning"; case ui::mojom::CursorType::kSouthWestPanning: return "sw-panning"; case ui::mojom::CursorType::kWestPanning: return "w-panning"; case ui::mojom::CursorType::kMove: return "move"; case ui::mojom::CursorType::kVerticalText: return "vertical-text"; case ui::mojom::CursorType::kCell: return "cell"; case ui::mojom::CursorType::kContextMenu: return "context-menu"; case ui::mojom::CursorType::kAlias: return "alias"; case ui::mojom::CursorType::kProgress: return "progress"; case ui::mojom::CursorType::kNoDrop: return "nodrop"; case ui::mojom::CursorType::kCopy: return "copy"; case ui::mojom::CursorType::kNone: return "none"; case ui::mojom::CursorType::kNotAllowed: return "not-allowed"; case ui::mojom::CursorType::kZoomIn: return "zoom-in"; case ui::mojom::CursorType::kZoomOut: return "zoom-out"; case ui::mojom::CursorType::kGrab: return "grab"; case ui::mojom::CursorType::kGrabbing: return "grabbing"; case ui::mojom::CursorType::kCustom: return "custom"; case ui::mojom::CursorType::kNull: return "null"; case ui::mojom::CursorType::kDndNone: return "drag-drop-none"; case ui::mojom::CursorType::kDndMove: return "drag-drop-move"; case ui::mojom::CursorType::kDndCopy: return "drag-drop-copy"; case ui::mojom::CursorType::kDndLink: return "drag-drop-link"; case ui::mojom::CursorType::kNorthSouthNoResize: return "ns-no-resize"; case ui::mojom::CursorType::kEastWestNoResize: return "ew-no-resize"; case ui::mojom::CursorType::kNorthEastSouthWestNoResize: return "nesw-no-resize"; case ui::mojom::CursorType::kNorthWestSouthEastNoResize: return "nwse-no-resize"; default: return "default"; } } base::IDMap<WebContents*>& GetAllWebContents() { static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents; return *s_all_web_contents; } void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, base::ScopedClosureRunner capture_handle, const SkBitmap& bitmap) { auto ui_task_runner = content::GetUIThreadTaskRunner({}); if (!ui_task_runner->RunsTasksInCurrentSequence()) { ui_task_runner->PostTask( FROM_HERE, base::BindOnce(&OnCapturePageDone, std::move(promise), std::move(capture_handle), bitmap)); return; } // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); capture_handle.RunAndReset(); } 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 = ui::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::apple::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; #else scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name)); #endif } // This function returns a validated device name. // If the user passed one to webContents.print(), we check that it's valid and // return it or fail if the network doesn't recognize it. If the user didn't // pass a device name, we first try to return the system default printer. If one // isn't set, then pull all the printers and use the first one or fail if none // exist. std::pair<std::string, std::u16string> GetDeviceNameToUse( const std::u16string& device_name) { #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. ScopedAllowBlockingForElectron allow_blocking; #endif if (!device_name.empty()) { if (!IsDeviceNameValid(device_name)) return std::make_pair("Invalid deviceName provided", std::u16string()); return std::make_pair(std::string(), device_name); } 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"; 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()) return std::make_pair("No printers available on the network", std::u16string()); 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::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); } base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) { base::Value::Dict value; value.Set("type", file_system.type); value.Set("fileSystemName", file_system.file_system_name); value.Set("rootURL", file_system.root_url); value.Set("fileSystemPath", file_system.file_system_path); return 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::Dict& file_system_paths = pref_service->GetDict(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; for (auto it : file_system_paths) { 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) { return base::Contains(GetAddedFileSystemPaths(web_contents), file_system_path); } content::RenderFrameHost* GetRenderFrameHost( content::NavigationHandle* navigation_handle) { 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(); } return frame_host; } } // 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::kExtensionPopup: case extensions::mojom::ViewType::kBackgroundContents: case extensions::mojom::ViewType::kExtensionGuest: case extensions::mojom::ViewType::kTabContents: case extensions::mojom::ViewType::kOffscreenDocument: case extensions::mojom::ViewType::kExtensionSidePanel: 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)) #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()); SetUserAgent(GetBrowserContext()->GetUserAgent()); 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)) #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)) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { // Read options. options.Get("backgroundThrottling", &background_throttling_); // Get type options.Get("type", &type_); bool b = false; if (options.Get(options::kOffscreen, &b) && b) type_ = Type::kOffScreen; // Init embedder earlier options.Get("embedder", &embedder_); // Whether to enable DevTools. options.Get("devTools", &enable_devtools_); bool initially_shown = true; 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 (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 { web_contents = content::WebContents::Create(params); } } 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()); } 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); // Nothing to do with ZoomController, but this function gets called in all // init cases! content::RenderViewHost* host = web_contents->GetRenderViewHost(); if (host) host->GetWidget()->AddInputEventObserver(this); } 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()); SetUserAgent(GetBrowserContext()->GetUserAgent()); 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) PrintViewManagerElectron::CreateForWebContents(web_contents.get()); #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() { if (owner_window_) { owner_window_->RemoveBackgroundThrottlingSource(this); } if (web_contents()) { content::RenderViewHost* host = web_contents()->GetRenderViewHost(); if (host) host->GetWidget()->RemoveInputEventObserver(this); } 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 asynchronously 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(&WebContents::DeleteThisIfAlive, GetWeakPtr())); } } void WebContents::Close(absl::optional<gin_helper::Dictionary> options) { bool dispatch_beforeunload = false; if (options) options->Get("waitForBeforeUnload", &dispatch_beforeunload); if (dispatch_beforeunload && web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) { NotifyUserActivation(); web_contents()->DispatchBeforeUnload(false /* auto_cancel */); } else { web_contents()->Close(); } } 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 blink::mojom::WindowFeatures& window_features, 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, window_features.bounds.x(), window_features.bounds.y(), window_features.bounds.width(), window_features.bounds.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) { // Note that Chromium does not emit this for navigations. // Emit returns true if preventDefault() was called, so !Emit will be true if // the event should proceed. *proceed_to_fire_unload = !Emit("-before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { if (!Emit("content-bounds-updated", 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(); } Destroy(); } 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) { // 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) { // For backwards compatibility, pretend that `kRawKeyDown` events are // actually `kKeyDown`. content::NativeWebKeyboardEvent tweaked_event(event); if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown) tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown); bool prevent_default = Emit("before-input-event", tweaked_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 { if (!owner_window()) return false; return owner_window()->IsFullscreen() || is_html_fullscreen(); } 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 notify_download, 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(requesting_frame, callback); } 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; } owner_window()->set_fullscreen_transition_type( NativeWindow::FullScreenTransitionType::kHTML); exclusive_access_manager_.fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); 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; } 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); auto result = gin_helper::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::OnRequestToLockMouse(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::OnRequestToLockMouse, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_.mouse_lock_controller()->LostMouseLock(); } void WebContents::OnRequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked, bool allowed) { if (allowed) { exclusive_access_manager_.keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } else { web_contents->GotResponseToKeyboardLockRequest(false); } } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestKeyboardLockPermission( esc_key_locked, base::BindOnce(&WebContents::OnRequestKeyboardLock, base::Unretained(this))); } 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 url::Origin& 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)); } const void* const kJavaScriptDialogManagerKey = &kJavaScriptDialogManagerKey; content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { // Indirect these delegate methods through a helper object whose lifetime is // bound to that of the content::WebContents. This prevents the // content::WebContents from calling methods on the Electron WebContents in // the event that the Electron one is destroyed before the content one, as // happens sometimes during shutdown or when webviews are involved. class JSDialogManagerHelper : public content::JavaScriptDialogManager, public base::SupportsUserData::Data { public: void RunJavaScriptDialog(content::WebContents* web_contents, content::RenderFrameHost* rfh, content::JavaScriptDialogType dialog_type, const std::u16string& message_text, const std::u16string& default_prompt_text, DialogClosedCallback callback, bool* did_suppress_message) override { auto* wc = WebContents::From(web_contents); if (wc) wc->RunJavaScriptDialog(web_contents, rfh, dialog_type, message_text, default_prompt_text, std::move(callback), did_suppress_message); } void RunBeforeUnloadDialog(content::WebContents* web_contents, content::RenderFrameHost* rfh, bool is_reload, DialogClosedCallback callback) override { auto* wc = WebContents::From(web_contents); if (wc) wc->RunBeforeUnloadDialog(web_contents, rfh, is_reload, std::move(callback)); } void CancelDialogs(content::WebContents* web_contents, bool reset_state) override { auto* wc = WebContents::From(web_contents); if (wc) wc->CancelDialogs(web_contents, reset_state); } }; if (!source->GetUserData(kJavaScriptDialogManagerKey)) source->SetUserData(kJavaScriptDialogManagerKey, std::make_unique<JSDialogManagerHelper>()); return static_cast<JSDialogManagerHelper*>( source->GetUserData(kJavaScriptDialogManagerKey)); } void WebContents::OnAudioStateChanged(bool audible) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>(); gin::Dictionary dict(isolate, event_object); dict.Set("audible", audible); EmitWithoutEvent("audio-state-changed", event); } void WebContents::BeforeUnloadFired(bool proceed) { // 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) SetBackgroundColor(web_preferences->GetBackgroundColor()); 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->MaybeSetupMojoConnection(); } 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); auto 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. // // 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) { if (new_host->IsInPrimaryMainFrame()) { if (old_host) old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this); if (new_host) new_host->GetRenderWidgetHost()->AddInputEventObserver(this); } // 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::FromRenderFrameHost(new_host); 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) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto 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) { // See DocumentLoader::StartLoadingResponse() - when we navigate to a media // resource the original request for the media resource, which resulted in a // committed navigation, is simply discarded. The media element created // inside the MediaDocument then makes *another new* request for the same // media resource. bool is_media_document = media::IsSupportedMediaMimeType(web_contents()->GetContentsMimeType()); if (error_code == net::ERR_ABORTED && is_media_document) return; 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_name, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_process_id = -1, frame_routing_id = -1; content::RenderFrameHost* frame_host = GetRenderFrameHost(navigation_handle); 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(); content::RenderFrameHost* initiator_frame_host = navigation_handle->GetInitiatorFrameToken().has_value() ? content::RenderFrameHost::FromFrameToken( content::GlobalRenderFrameHostToken( navigation_handle->GetInitiatorProcessId(), navigation_handle->GetInitiatorFrameToken().value())) : nullptr; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>(); gin_helper::Dictionary dict(isolate, event_object); dict.Set("url", url); dict.Set("isSameDocument", is_same_document); dict.Set("isMainFrame", is_main_frame); dict.SetGetter("frame", frame_host); dict.SetGetter("initiator", initiator_frame_host); EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); return event->GetDefaultPrevented(); } 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()->GetPrimaryMainFrame()) { Emit("ready-to-show"); } } // This object wraps the InvokeCallback so that if it gets GC'd by V8, we can // still call the callback and send an error. Not doing so causes a Mojo DCHECK, // since Mojo requires callbacks to be called before they are destroyed. class ReplyChannel : public gin::Wrappable<ReplyChannel> { public: using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback; static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate, InvokeCallback callback) { return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback))); } // gin::Wrappable static gin::WrapperInfo kWrapperInfo; gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override { return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate) .SetMethod("sendReply", &ReplyChannel::SendReply); } const char* GetTypeName() override { return "ReplyChannel"; } void SendError(const std::string& msg) { v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate(); // If there's no current context, it means we're shutting down, so we // don't need to send an event. if (!isolate->GetCurrentContext().IsEmpty()) { v8::HandleScope scope(isolate); auto message = gin::DataObjectBuilder(isolate).Set("error", msg).Build(); SendReply(isolate, message); } } private: explicit ReplyChannel(InvokeCallback callback) : callback_(std::move(callback)) {} ~ReplyChannel() override { if (callback_) SendError("reply was never sent"); } bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) { if (!callback_) return false; blink::CloneableMessage message; if (!gin::ConvertFromV8(isolate, arg, &message)) { return false; } std::move(callback_).Run(std::move(message)); return true; } InvokeCallback callback_; }; gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin}; gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender( v8::Isolate* isolate, content::RenderFrameHost* frame, electron::mojom::ElectronApiIPC::InvokeCallback callback) { v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) { if (callback) { // We must always invoke the callback if present. ReplyChannel::Create(isolate, std::move(callback)) ->SendError("WebContents was destroyed"); } return gin::Handle<gin_helper::internal::Event>(); } gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>()); if (callback) dict.Set("_replyChannel", ReplyChannel::Create(isolate, std::move(callback))); if (frame) { dict.Set("frameId", frame->GetRoutingID()); dict.Set("processId", frame->GetProcess()->GetID()); } return event; } 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::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) { if (owner_window() && owner_window()->has_frame()) return; draggable_region_ = DraggableRegionsToSkRegion(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. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "setInspectedTabId", base::Value(ID())); // 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::SetOwnerBaseWindow(absl::optional<BaseWindow*> owner_window) { SetOwnerWindow(GetWebContents(), owner_window ? (*owner_window)->window() : nullptr); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window_) { owner_window_->RemoveBackgroundThrottlingSource(this); } if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); owner_window_->AddBackgroundThrottlingSource(this); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); } 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; if (owner_window_) { owner_window_->UpdateBackgroundThrottlingState(); } auto* rfh = web_contents()->GetPrimaryMainFrame(); 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()->GetPrimaryMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents() ->GetPrimaryMainFrame() ->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)) SetUserAgent(user_agent); 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; // It's not safe to start a new navigation or otherwise discard the current // one while the call that started it is still on the stack. See // http://crbug.com/347742. auto& ctrl_impl = static_cast<content::NavigationControllerImpl&>( web_contents()->GetController()); if (ctrl_impl.in_navigate_to_pending_entry()) { Emit("did-fail-load", static_cast<int>(net::ERR_FAILED), net::ErrorToShortString(net::ERR_FAILED), url.possibly_invalid_spec(), true); return; } // Discard non-committed entries to ensure 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, gin::Arguments* args) { std::map<std::string, std::string> headers; gin_helper::Dictionary options; if (args->GetNext(&options)) { if (options.Has("headers") && !options.Get("headers", &headers)) { args->ThrowTypeError("Invalid value for headers - must be an object"); return; } } std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); for (const auto& [name, value] : headers) { download_params->add_request_header(name, value); } auto* download_manager = web_contents()->GetBrowserContext()->GetDownloadManager(); 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(); } v8::Local<v8::Value> WebContents::GetWebRTCUDPPortRange( v8::Isolate* isolate) const { auto* prefs = web_contents()->GetMutableRendererPrefs(); auto dict = gin_helper::Dictionary::CreateEmpty(isolate); dict.Set("min", static_cast<uint32_t>(prefs->webrtc_udp_min_port)); dict.Set("max", static_cast<uint32_t>(prefs->webrtc_udp_max_port)); return dict.GetHandle(); } void WebContents::SetWebRTCUDPPortRange(gin::Arguments* args) { uint32_t min = 0, max = 0; gin_helper::Dictionary range; if (!args->GetNext(&range) || !range.Get("min", &min) || !range.Get("max", &max)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'min' and 'max' are both required"); return; } if ((0 == min && 0 != max) || max > UINT16_MAX) { gin_helper::ErrorThrower(args->isolate()) .ThrowError( "'min' and 'max' must be in the (0, 65535] range or [0, 0]"); return; } if (min > max) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'max' must be greater than or equal to 'min'"); return; } auto* prefs = web_contents()->GetMutableRendererPrefs(); if (prefs->webrtc_udp_min_port == static_cast<uint16_t>(min) && prefs->webrtc_udp_max_port == static_cast<uint16_t>(max)) { return; } prefs->webrtc_udp_min_port = min; prefs->webrtc_udp_max_port = max; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetPrimaryMainFrame(); 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->GetPrimaryMainFrame(); 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. #if !IS_MAS_BUILD() CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { blink::UserAgentOverride ua_override; ua_override.ua_string_override = user_agent; if (!user_agent.empty()) ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata(); web_contents()->SetUserAgentOverride(ua_override, 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; std::string title; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); options.Get("title", &title); } } DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->SetDevToolsTitle(base::UTF8ToUTF16(title)); 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(); } std::u16string WebContents::GetDevToolsTitle() { if (type_ == Type::kRemote) return std::u16string(); DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetDevToolsTitle(); } void WebContents::SetDevToolsTitle(const std::u16string& title) { inspectable_web_contents_->SetDevToolsTitle(title); } 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()->GetPrimaryMainFrame(); 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()->GetPrimaryMainFrame(); 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::OnGetDeviceNameToUse( base::Value::Dict print_settings, printing::CompletionCallback print_callback, bool silent, // <error, device_name> 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. print_settings.Set(printing::kSettingDeviceName, info.second); 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()->GetPrimaryMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { auto options = gin_helper::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 auto margins = gin_helper::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); 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_dict; // Chromium uses 1-based page ranges, so increment each by 1. range_dict.Set(printing::kSettingPageRangeFrom, from + 1); range_dict.Set(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range_dict)); } 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::DICT); 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(&GetDeviceNameToUse, device_name), base::BindOnce(&WebContents::OnGetDeviceNameToUse, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), silent)); } // Partially duplicated and modified from // headless/lib/browser/protocol/page_handler.cc;l=41 v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); // This allows us to track headless printing calls. auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID); auto landscape = settings.GetDict().FindBool("landscape"); auto display_header_footer = settings.GetDict().FindBool("displayHeaderFooter"); auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds"); auto scale = settings.GetDict().FindDouble("scale"); auto paper_width = settings.GetDict().FindDouble("paperWidth"); auto paper_height = settings.GetDict().FindDouble("paperHeight"); auto margin_top = settings.GetDict().FindDouble("marginTop"); auto margin_bottom = settings.GetDict().FindDouble("marginBottom"); auto margin_left = settings.GetDict().FindDouble("marginLeft"); auto margin_right = settings.GetDict().FindDouble("marginRight"); auto page_ranges = *settings.GetDict().FindString("pageRanges"); auto header_template = *settings.GetDict().FindString("headerTemplate"); auto footer_template = *settings.GetDict().FindString("footerTemplate"); auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize"); auto generate_tagged_pdf = settings.GetDict().FindBool("generateTaggedPDF"); auto generate_document_outline = settings.GetDict().FindBool("generateDocumentOutline"); absl::variant<printing::mojom::PrintPagesParamsPtr, std::string> print_pages_params = print_to_pdf::GetPrintPagesParams( web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(), landscape, display_header_footer, print_background, scale, paper_width, paper_height, margin_top, margin_bottom, margin_left, margin_right, absl::make_optional(header_template), absl::make_optional(footer_template), prefer_css_page_size, generate_tagged_pdf, generate_document_outline); if (absl::holds_alternative<std::string>(print_pages_params)) { auto error = absl::get<std::string>(print_pages_params); promise.RejectWithErrorMessage("Invalid print parameters: " + error); return handle; } auto* manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!manager) { promise.RejectWithErrorMessage("Failed to find print manager"); return handle; } auto params = std::move( absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params)); params->params->document_cookie = unique_id.value_or(0); manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges, std::move(params), base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(), std::move(promise))); return handle; } void WebContents::OnPDFCreated( gin_helper::Promise<v8::Local<v8::Value>> promise, print_to_pdf::PdfPrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + print_to_pdf::PdfPrintResultToString(print_result)); return; } v8::Isolate* isolate = promise.isolate(); gin_helper::Locker locker(isolate); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope( v8::Local<v8::Context>::New(isolate, promise.GetContext())); v8::Local<v8::Value> buffer = node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()), data->size()) .ToLocalChecked(); promise.Resolve(buffer); } #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::CenterSelection() { web_contents()->CenterSelection(); } 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::ScrollToTopOfDocument() { web_contents()->ScrollToTopOfDocument(); } void WebContents::ScrollToBottomOfDocument() { web_contents()->ScrollToBottomOfDocument(); } void WebContents::AdjustSelectionByCharacterOffset(gin::Arguments* args) { int start_adjust = 0; int end_adjust = 0; gin_helper::Dictionary dict; if (args->GetNext(&dict)) { dict.Get("start", &start_adjust); dict.Get("matchCase", &end_adjust); } // The selection menu is a Chrome-specific piece of UI. // TODO(codebytere): maybe surface as an event in the future? web_contents()->AdjustSelectionByCharacterOffset( start_adjust, end_adjust, false /* show_selection_menu */); } 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()->GetPrimaryMainFrame(); 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()) { GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); } 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)) { // For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`. if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown) keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown); 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()) { GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); } 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::ScopedAllowApplicationTasksInNativeNestedLoop 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) { gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); gfx::Rect rect; args->GetNext(&rect); bool stay_hidden = false; bool stay_awake = false; if (args && args->Length() == 2) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("stayHidden", &stay_hidden); options.Get("stayAwake", &stay_awake); } } auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view || view->GetViewBounds().size().IsEmpty()) { promise.Resolve(gfx::Image()); return handle; } if (!view->IsSurfaceAvailableForCopy()) { promise.RejectWithErrorMessage( "Current display surface not available for capture"); return handle; } auto capture_handle = web_contents()->IncrementCapturerCount( rect.size(), stay_hidden, stay_awake); // 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), std::move(capture_handle))); return handle; } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const ui::Cursor& cursor) { if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor.type()), 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.type())); } } 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 { return type_ == Type::kOffScreen; } 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; } void WebContents::Invalidate() { if (IsOffScreen()) { auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); } 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()->GetPrimaryMainFrame(); } content::RenderFrameHost* WebContents::Opener() { return web_contents()->GetOpener(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame(); 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(); } void WebContents::SetBackgroundColor(absl::optional<SkColor> maybe_color) { SkColor color = maybe_color.value_or(type_ == Type::kWebView || type_ == Type::kBrowserView ? SK_ColorTRANSPARENT : SK_ColorWHITE); web_contents()->SetPageBaseBackgroundColor(color); content::RenderFrameHost* rfh = web_contents()->GetPrimaryMainFrame(); if (!rfh) return; content::RenderWidgetHostView* rwhv = rfh->GetView(); if (rwhv) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } void WebContents::OnInputEvent(const blink::WebInputEvent& event) { Emit("input-event", event); } void WebContents::RunJavaScriptDialog(content::WebContents* web_contents, content::RenderFrameHost* rfh, content::JavaScriptDialogType dialog_type, const std::u16string& message_text, const std::u16string& default_prompt_text, DialogClosedCallback callback, bool* did_suppress_message) { CHECK_EQ(web_contents, this->web_contents()); auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto info = gin::DataObjectBuilder(isolate) .Set("frame", rfh) .Set("dialogType", dialog_type) .Set("messageText", message_text) .Set("defaultPromptText", default_prompt_text) .Build(); EmitWithoutEvent("-run-dialog", info, std::move(callback)); } void WebContents::RunBeforeUnloadDialog(content::WebContents* web_contents, content::RenderFrameHost* rfh, bool is_reload, DialogClosedCallback callback) { // TODO: asyncify? bool default_prevented = Emit("will-prevent-unload"); std::move(callback).Run(default_prevented, std::u16string()); } void WebContents::CancelDialogs(content::WebContents* web_contents, bool reset_state) { auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitWithoutEvent( "-cancel-dialogs", gin::DataObjectBuilder(isolate).Set("resetState", reset_state).Build()); } 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()->GetPrimaryMainFrame(); 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(); ScopedAllowBlockingForElectron allow_blocking; uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE; // The snapshot file is passed to an untrusted process. flags = base::File::AddFlagsForPassingToUntrustedProcess(flags); base::File file(file_path, flags); if (!file.IsValid()) { promise.RejectWithErrorMessage( "Failed to take heap snapshot with invalid file path " + #if BUILDFLAG(IS_WIN) base::WideToUTF8(file_path.value())); #else file_path.value()); #endif return handle; } auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage( "Failed to take heap snapshot with invalid webContents main frame"); return handle; } if (!frame_host->IsRenderFrameLive()) { promise.RejectWithErrorMessage( "Failed to take heap snapshot with nonexistent render frame"); 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("Failed to take heap snapshot"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } 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) { if (!owner_window()) return is_html_fullscreen(); bool in_transition = owner_window()->fullscreen_transition_state() != NativeWindow::FullScreenTransitionState::kNone; bool is_html_transition = owner_window()->fullscreen_transition_type() == NativeWindow::FullScreenTransitionType::kHTML; return is_html_fullscreen() || (in_transition && is_html_transition); } content::FullscreenState WebContents::GetFullscreenState( const content::WebContents* source) const { // `const_cast` here because EAM does not have const getters return const_cast<ExclusiveAccessManager*>(&exclusive_access_manager_) ->fullscreen_controller() ->GetFullscreenState(source); } 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) { return PictureInPictureWindowManager::GetInstance() ->EnterVideoPictureInPicture(web_contents); } void WebContents::ExitPictureInPicture() { PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); } 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)) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "canceledSaveURL", base::Value(url)); return; } } saved_files_[url] = path; // Notify DevTools. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "savedURL", base::Value(url), base::Value(path.AsUTF8Unsafe())); 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. inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL", base::Value(url)); 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()) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List())); 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::Value::List file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(std::move(file_system_value))); } 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); base::Value::Dict file_system_value = CreateFileSystemValue(file_system); auto* pref_service = GetPrefService(GetDevToolsWebContents()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Set(path.AsUTF8Unsafe(), type); std::string error = ""; // No error inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemAdded", base::Value(error), base::Value(std::move(file_system_value))); } 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()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Remove(path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemRemoved", base::Value(path)); } 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; absl::optional<base::Value> parsed_excluded_folders = base::JSONReader::Read(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetList()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsOpenInNewTab(const std::string& url) { Emit("devtools-open-url", url); } 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::Value::Dict color; color.Set("r", r); color.Set("g", g); color.Set("b", b); color.Set("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color))); } #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) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id), base::Value(file_system_path), base::Value(total_work)); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingWorked", base::Value(request_id), base::Value(file_system_path), base::Value(worked)); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone", base::Value(request_id), base::Value(file_system_path)); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::Value::List file_paths_value; for (const auto& file_path : file_paths) file_paths_value.Append(file_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "searchCompleted", base::Value(request_id), base::Value(file_system_path), base::Value(std::move(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(), [&](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; }); } } // static void WebContents::FillObjectTemplate(v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = GetClassName(); 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. gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("close", &WebContents::Close) .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("getDevToolsTitle", &WebContents::GetDevToolsTitle) .SetMethod("setDevToolsTitle", &WebContents::SetDevToolsTitle) .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("centerSelection", &WebContents::CenterSelection) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("scrollToTop", &WebContents::ScrollToTopOfDocument) .SetMethod("scrollToBottom", &WebContents::ScrollToBottomOfDocument) .SetMethod("adjustSelection", &WebContents::AdjustSelectionByCharacterOffset) .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) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) .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("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("setWebRTCUDPPortRange", &WebContents::SetWebRTCUDPPortRange) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("getWebRTCUDPPortRange", &WebContents::GetWebRTCUDPPortRange) .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) .SetProperty("opener", &WebContents::Opener) .SetMethod("_setOwnerWindow", &WebContents::SetOwnerBaseWindow) .Build(); } const char* WebContents::GetTypeName() { return GetClassName(); } 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); web_contents->SetBackgroundColor( existing_preferences->GetBackgroundColor()); } } 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 std::list<WebContents*> WebContents::GetWebContentsList() { std::list<WebContents*> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(iter.GetCurrentValue()); } return list; } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace electron::api namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; using electron::api::WebFrameMain; 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> WebContentsFromFrame(v8::Isolate* isolate, WebFrameMain* web_frame) { content::RenderFrameHost* rfh = web_frame->render_frame_host(); content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh); WebContents* contents = WebContents::From(source); 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("fromFrame", &WebContentsFromFrame); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
40,207
[Bug]: Setting color-scheme to dark changes text color but not background color for webviews
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior The background colour of the webview should be black and the text colour should be white. ### Actual Behavior The background colour of the webview is white and the text colour is also white, making it impossible to read the text. ### Testcase Gist URL https://gist.github.com/BrandonXLF/4a6f65cba592bece8d1413f7a8730dca ### Additional Information Continuation of #36122 as it became stale Issue applies to both the `color-scheme` CSS property when it's applied to `:root`/`html` and the `color-scheme` meta tag, but it works fine when applied to other elements like `textarea`. The issue is not present in iframes.
https://github.com/electron/electron/issues/40207
https://github.com/electron/electron/pull/40301
8c71e2adc9b47f8d9e9ad07be9e6a9b3a764a670
50860712943da0feabcb668b264c35b7837286c0
2023-10-15T09:46:05Z
c++
2024-01-05T04:00:27Z
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/raw_ptr.h" #include "base/memory/raw_ptr_exclusion.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/observer_list_types.h" #include "base/task/thread_pool.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 "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "content/common/frame.mojom.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/javascript_dialog_manager.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/background_throttling_source.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 "ui/base/cursor/cursor.h" #include "ui/base/models/image_model.h" #include "ui/gfx/image/image.h" #if BUILDFLAG(ENABLE_PRINTING) #include "components/printing/browser/print_to_pdf/pdf_print_result.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 SkRegion; namespace electron { class ElectronBrowserContext; class InspectableWebContents; class WebContentsZoomController; class WebViewGuestDelegate; class FrameSubscriber; class WebDialogHelper; class NativeWindow; class OffScreenRenderWidgetHostView; class OffScreenWebContentsView; namespace api { class BaseWindow; // 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 content::RenderWidgetHost::InputEventObserver, public content::JavaScriptDialogManager, public InspectableWebContentsDelegate, public InspectableWebContentsViewDelegate, public BackgroundThrottlingSource { public: enum class Type { kBackgroundPage, // An extension background page. kBrowserWindow, // Used by BrowserWindow. kBrowserView, // Used by the JS implementation of BrowserView for // backwards compatibility. Otherwise identical to // kBrowserWindow. 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); static std::list<WebContents*> GetWebContentsList(); // 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_helper::Constructible static void FillObjectTemplate(v8::Isolate*, v8::Local<v8::ObjectTemplate>); static const char* GetClassName() { return "WebContents"; } // gin::Wrappable static gin::WrapperInfo kWrapperInfo; const char* GetTypeName() override; void Destroy(); void Close(absl::optional<gin_helper::Dictionary> options); base::WeakPtr<WebContents> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } bool GetBackgroundThrottling() const override; 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, gin::Arguments* args); 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); v8::Local<v8::Value> GetWebRTCUDPPortRange(v8::Isolate* isolate) const; void SetWebRTCUDPPortRange(gin::Arguments* args); 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(); std::u16string GetDevToolsTitle(); void SetDevToolsTitle(const std::u16string& title); 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; bool IsBeingCaptured(); void HandleNewRenderFrame(content::RenderFrameHost* render_frame_host); #if BUILDFLAG(ENABLE_PRINTING) void OnGetDeviceNameToUse(base::Value::Dict print_settings, printing::CompletionCallback print_callback, bool silent, // <error, device_name> std::pair<std::string, std::u16string> info); void Print(gin::Arguments* args); // Print current page as PDF. v8::Local<v8::Promise> PrintToPDF(const base::Value& settings); void OnPDFCreated(gin_helper::Promise<v8::Local<v8::Value>> promise, print_to_pdf::PdfPrintResult print_result, scoped_refptr<base::RefCountedMemory> data); #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 CenterSelection(); void Paste(); void PasteAndMatchStyle(); void Delete(); void SelectAll(); void Unselect(); void ScrollToTopOfDocument(); void ScrollToBottomOfDocument(); void AdjustSelectionByCharacterOffset(gin::Arguments* args); 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; 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; 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); bool HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) override; // 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(); content::RenderFrameHost* Opener(); 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* frame, electron::mojom::ElectronApiIPC::InvokeCallback callback, Args&&... args) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin::Handle<gin_helper::internal::Event> event = MakeEventWithSender(isolate, frame, std::move(callback)); if (event.IsEmpty()) return false; EmitWithoutEvent(name, event, std::forward<Args>(args)...); return event->GetDefaultPrevented(); } gin::Handle<gin_helper::internal::Event> MakeEventWithSender( v8::Isolate* isolate, content::RenderFrameHost* frame, electron::mojom::ElectronApiIPC::InvokeCallback callback); 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); void SetOwnerBaseWindow(absl::optional<BaseWindow*> 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 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); // content::RenderWidgetHost::InputEventObserver: void OnInputEvent(const blink::WebInputEvent& event) override; // content::JavaScriptDialogManager: void RunJavaScriptDialog(content::WebContents* web_contents, content::RenderFrameHost* rfh, content::JavaScriptDialogType dialog_type, const std::u16string& message_text, const std::u16string& default_prompt_text, DialogClosedCallback callback, bool* did_suppress_message) override; void RunBeforeUnloadDialog(content::WebContents* web_contents, content::RenderFrameHost* rfh, bool is_reload, DialogClosedCallback callback) override; void CancelDialogs(content::WebContents* web_contents, bool reset_state) override; void SetBackgroundColor(absl::optional<SkColor> color); SkRegion* draggable_region() { return force_non_draggable_ ? nullptr : draggable_region_.get(); } void SetForceNonDraggable(bool force_non_draggable) { force_non_draggable_ = force_non_draggable; } // 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 blink::mojom::WindowFeatures& window_features, 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; 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 OnRequestToLockMouse(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 OnRequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked, bool allowed); 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 url::Origin& 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) 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 ui::Cursor& 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(); OffScreenWebContentsView* GetOffScreenWebContentsView() const; OffScreenRenderWidgetHostView* GetOffScreenRenderWidgetHostView() const; // 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 notify_download, bool force_update) override; void OnExclusiveAccessUserInput() override; content::WebContents* GetActiveWebContents() override; bool CanUserExitFullscreen() const override; bool IsExclusiveAccessBubbleDisplayed() const override; // content::WebContentsDelegate bool IsFullscreenForTabOrPending(const content::WebContents* source) override; content::FullscreenState GetFullscreenState( const content::WebContents* web_contents) const 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 DevToolsOpenInNewTab(const std::string& url) 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<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. RAW_PTR_EXCLUSION WebContents* embedder_ = nullptr; // Whether the guest view has been attached. bool attached_ = false; // 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; const scoped_refptr<DevToolsFileSystemIndexer> devtools_file_system_indexer_ = base::MakeRefCounted<DevToolsFileSystemIndexer>(); ExclusiveAccessManager exclusive_access_manager_{this}; std::unique_ptr<DevToolsEyeDropper> eye_dropper_; raw_ptr<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_; // The zoom controller for this webContents. // Note: owned by inspectable_web_contents_, so declare this *after* // that field to ensure the dtor destroys them in the right order. raw_ptr<WebContentsZoomController> zoom_controller_ = nullptr; // 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_; const scoped_refptr<base::SequencedTaskRunner> file_task_runner_ = base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}); #if BUILDFLAG(ENABLE_PRINTING) const scoped_refptr<base::TaskRunner> print_task_runner_; #endif // Stores the frame thats currently in fullscreen, nullptr if there is none. raw_ptr<content::RenderFrameHost> fullscreen_frame_ = nullptr; std::unique_ptr<SkRegion> draggable_region_; bool force_non_draggable_ = false; 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
40,207
[Bug]: Setting color-scheme to dark changes text color but not background color for webviews
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior The background colour of the webview should be black and the text colour should be white. ### Actual Behavior The background colour of the webview is white and the text colour is also white, making it impossible to read the text. ### Testcase Gist URL https://gist.github.com/BrandonXLF/4a6f65cba592bece8d1413f7a8730dca ### Additional Information Continuation of #36122 as it became stale Issue applies to both the `color-scheme` CSS property when it's applied to `:root`/`html` and the `color-scheme` meta tag, but it works fine when applied to other elements like `textarea`. The issue is not present in iframes.
https://github.com/electron/electron/issues/40207
https://github.com/electron/electron/pull/40301
8c71e2adc9b47f8d9e9ad07be9e6a9b3a764a670
50860712943da0feabcb668b264c35b7837286c0
2023-10-15T09:46:05Z
c++
2024-01-05T04:00:27Z
spec/fixtures/pages/flex-webview.html
closed
electron/electron
https://github.com/electron/electron
40,207
[Bug]: Setting color-scheme to dark changes text color but not background color for webviews
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior The background colour of the webview should be black and the text colour should be white. ### Actual Behavior The background colour of the webview is white and the text colour is also white, making it impossible to read the text. ### Testcase Gist URL https://gist.github.com/BrandonXLF/4a6f65cba592bece8d1413f7a8730dca ### Additional Information Continuation of #36122 as it became stale Issue applies to both the `color-scheme` CSS property when it's applied to `:root`/`html` and the `color-scheme` meta tag, but it works fine when applied to other elements like `textarea`. The issue is not present in iframes.
https://github.com/electron/electron/issues/40207
https://github.com/electron/electron/pull/40301
8c71e2adc9b47f8d9e9ad07be9e6a9b3a764a670
50860712943da0feabcb668b264c35b7837286c0
2023-10-15T09:46:05Z
c++
2024-01-05T04:00:27Z
spec/webview-spec.ts
import * as path from 'node:path'; import * as url from 'node:url'; import { BrowserWindow, session, ipcMain, app, WebContents } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import { emittedUntil } from './lib/events-helpers'; import { ifit, ifdescribe, defer, itremote, useRemoteContext, listen } from './lib/spec-helpers'; import { expect } from 'chai'; import * as http from 'node:http'; import * as auth from 'basic-auth'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; declare let WebView: any; const features = process._linkedBinding('electron_common_features'); async function loadWebView (w: WebContents, attributes: Record<string, string>, opts?: {openDevTools?: boolean}): Promise<void> { const { openDevTools } = { openDevTools: false, ...opts }; await w.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView() webview.id = 'webview' for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) { webview.setAttribute(k, v) } document.body.appendChild(webview) webview.addEventListener('dom-ready', () => { if (${openDevTools}) { webview.openDevTools() } }) webview.addEventListener('did-finish-load', () => { resolve() }) }) `); } async function loadWebViewAndWaitForEvent (w: WebContents, attributes: Record<string, string>, eventName: string): Promise<any> { return await w.executeJavaScript(`new Promise((resolve, reject) => { const webview = new WebView() webview.id = 'webview' for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) { webview.setAttribute(k, v) } webview.addEventListener(${JSON.stringify(eventName)}, (e) => resolve({...e}), {once: true}) document.body.appendChild(webview) })`); }; async function loadWebViewAndWaitForMessage (w: WebContents, attributes: Record<string, string>): Promise<string> { const { message } = await loadWebViewAndWaitForEvent(w, attributes, 'console-message'); return message; }; describe('<webview> tag', function () { const fixtures = path.join(__dirname, 'fixtures'); const blankPageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'blank.html')).toString(); function hideChildWindows (e: any, wc: WebContents) { wc.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false } })); } before(() => { app.on('web-contents-created', hideChildWindows); }); after(() => { app.off('web-contents-created', hideChildWindows); }); describe('behavior', () => { afterEach(closeAllWindows); it('works without script tag in page', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html')); await once(ipcMain, 'pong'); }); it('works with sandbox', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, sandbox: true } }); w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html')); await once(ipcMain, 'pong'); }); it('works with contextIsolation', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, contextIsolation: true } }); w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html')); await once(ipcMain, 'pong'); }); it('works with contextIsolation + sandbox', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, contextIsolation: true, sandbox: true } }); w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html')); await once(ipcMain, 'pong'); }); it('works with Trusted Types', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadFile(path.join(fixtures, 'pages', 'webview-trusted-types.html')); await once(ipcMain, 'pong'); }); it('is disabled by default', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'module', 'preload-webview.js'), nodeIntegration: true } }); const webview = once(ipcMain, 'webview'); w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html')); const [, type] = await webview; expect(type).to.equal('undefined', 'WebView still exists'); }); }); // FIXME(deepak1556): Ch69 follow up. xdescribe('document.visibilityState/hidden', () => { afterEach(() => { ipcMain.removeAllListeners('pong'); }); afterEach(closeAllWindows); it('updates when the window is shown after the ready-to-show event', async () => { const w = new BrowserWindow({ show: false }); const readyToShowSignal = once(w, 'ready-to-show'); const pongSignal1 = once(ipcMain, 'pong'); w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html')); await pongSignal1; const pongSignal2 = once(ipcMain, 'pong'); await readyToShowSignal; w.show(); const [, visibilityState, hidden] = await pongSignal2; expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false(); }); it('inherits the parent window visibility state and receives visibilitychange events', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true(); // We have to start waiting for the event // before we ask the webContents to resize. const getResponse = once(ipcMain, 'pong'); w.webContents.emit('-window-visibility-change', 'visible'); return getResponse.then(([, visibilityState, hidden]) => { expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false(); }); }); }); describe('did-attach-webview event', () => { afterEach(closeAllWindows); it('is emitted when a webview has been attached', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('did-attach event', () => { afterEach(closeAllWindows); it('is emitted when a webview has been attached', async () => { const w = new BrowserWindow({ webPreferences: { webviewTag: true } }); await w.loadURL('about:blank'); const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { const webview = new WebView() webview.setAttribute('src', 'about:blank') webview.addEventListener('did-attach', (e) => { resolve('ok') }) document.body.appendChild(webview) })`); expect(message).to.equal('ok'); }); }); describe('did-change-theme-color event', () => { afterEach(closeAllWindows); it('emits when theme color changes', async () => { const w = new BrowserWindow({ webPreferences: { webviewTag: true } }); await w.loadURL('about:blank'); const src = url.format({ pathname: `${fixtures.replaceAll('\\', '/')}/pages/theme-color.html`, protocol: 'file', slashes: true }); const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { const webview = new WebView() webview.setAttribute('src', '${src}') webview.addEventListener('did-change-theme-color', (e) => { resolve('ok') }) document.body.appendChild(webview) })`); expect(message).to.equal('ok'); }); }); describe('devtools', () => { afterEach(closeAllWindows); // FIXME: This test is flaky on WOA, so skip it there. ifit(process.platform !== 'win32' || process.arch !== 'arm64')('loads devtools extensions registered on the parent window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); w.webContents.session.removeExtension('foo'); const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo'); await w.webContents.session.loadExtension(extensionPath, { allowFileAccess: true }); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'webview-devtools.html')); loadWebView(w.webContents, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${path.join(__dirname, 'fixtures', 'blank.html')}` }, { openDevTools: true }); let childWebContentsId = 0; app.once('web-contents-created', (e, webContents) => { childWebContentsId = webContents.id; webContents.on('devtools-opened', function () { const showPanelIntervalId = setInterval(function () { if (!webContents.isDestroyed() && webContents.devToolsWebContents) { webContents.devToolsWebContents.executeJavaScript('(' + function () { const { EUI } = (window as any); const instance = EUI.InspectorView.InspectorView.instance(); const tabs = instance.tabbedPane.tabs; const lastPanelId: any = tabs[tabs.length - 1].id; instance.showPanel(lastPanelId); }.toString() + ')()'); } else { clearInterval(showPanelIntervalId); } }, 100); }); }); const [, { runtimeId, tabId }] = await once(ipcMain, 'answer'); expect(runtimeId).to.match(/^[a-z]{32}$/); expect(tabId).to.equal(childWebContentsId); await w.webContents.executeJavaScript('webview.closeDevTools()'); }); }); describe('zoom behavior', () => { const zoomScheme = standardScheme; const webviewSession = session.fromPartition('webview-temp'); afterEach(closeAllWindows); before(() => { const protocol = webviewSession.protocol; protocol.registerStringProtocol(zoomScheme, (request, callback) => { callback('hello'); }); }); after(() => { const protocol = webviewSession.protocol; protocol.unregisterProtocol(zoomScheme); }); it('inherits the zoomFactor of the parent window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, zoomFactor: 1.2, contextIsolation: false } }); const zoomEventPromise = once(ipcMain, 'webview-parent-zoom-level'); w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-factor.html')); const [, zoomFactor, zoomLevel] = await zoomEventPromise; expect(zoomFactor).to.equal(1.2); expect(zoomLevel).to.equal(1); }); it('maintains the zoom level for a given host in the same session after navigation', () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); const zoomPromise = new Promise<void>((resolve) => { ipcMain.on('webview-zoom-persist-level', (_event, values) => { resolve(values); }); }); w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-change-persist-host.html')); expect(zoomPromise).to.eventually.deep.equal({ initialZoomLevel: 2, switchZoomLevel: 3, finalZoomLevel: 2 }); }); it('maintains zoom level on navigation', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, zoomFactor: 1.2, contextIsolation: false } }); const promise = new Promise<void>((resolve) => { ipcMain.on('webview-zoom-level', (event, zoomLevel, zoomFactor, newHost, final) => { if (!newHost) { expect(zoomFactor).to.equal(1.44); expect(zoomLevel).to.equal(2.0); } else { expect(zoomFactor).to.equal(1.2); expect(zoomLevel).to.equal(1); } if (final) { resolve(); } }); }); w.loadFile(path.join(fixtures, 'pages', 'webview-custom-zoom-level.html')); await promise; }); it('maintains zoom level when navigating within same page', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, zoomFactor: 1.2, contextIsolation: false } }); const promise = new Promise<void>((resolve) => { ipcMain.on('webview-zoom-in-page', (event, zoomLevel, zoomFactor, final) => { expect(zoomFactor).to.equal(1.44); expect(zoomLevel).to.equal(2.0); if (final) { resolve(); } }); }); w.loadFile(path.join(fixtures, 'pages', 'webview-in-page-navigate.html')); await promise; }); it('inherits zoom level for the origin when available', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, zoomFactor: 1.2, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'webview-origin-zoom-level.html')); const [, zoomLevel] = await once(ipcMain, 'webview-origin-zoom-level'); expect(zoomLevel).to.equal(2.0); }); it('does not crash when navigating with zoom level inherited from parent', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, zoomFactor: 1.2, session: webviewSession, contextIsolation: false } }); const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const readyPromise = once(ipcMain, 'dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html')); const [, webview] = await attachPromise; await readyPromise; expect(webview.getZoomFactor()).to.equal(1.2); await w.loadURL(`${zoomScheme}://host1`); }); it('does not crash when changing zoom level after webview is destroyed', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, session: webviewSession, contextIsolation: false } }); const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; await w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html')); await attachPromise; await w.webContents.executeJavaScript('view.remove()'); w.webContents.setZoomLevel(0.5); }); }); describe('requestFullscreen from webview', () => { afterEach(closeAllWindows); async function loadWebViewWindow (): Promise<[BrowserWindow, WebContents]> { const w = new BrowserWindow({ webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const loadPromise = once(w.webContents, 'did-finish-load'); const readyPromise = once(ipcMain, 'webview-ready'); w.loadFile(path.join(__dirname, 'fixtures', 'webview', 'fullscreen', 'main.html')); const [, webview] = await attachPromise; await Promise.all([readyPromise, loadPromise]); return [w, webview]; }; afterEach(async () => { // The leaving animation is un-observable but can interfere with future tests // Specifically this is async on macOS but can be on other platforms too await setTimeout(1000); closeAllWindows(); }); ifit(process.platform !== 'darwin')('should make parent frame element fullscreen too (non-macOS)', async () => { const [w, webview] = await loadWebViewWindow(); expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false(); const parentFullscreen = once(ipcMain, 'fullscreenchange'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await parentFullscreen; expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true(); const close = once(w, 'closed'); w.close(); await close; }); ifit(process.platform === 'darwin')('should make parent frame element fullscreen too (macOS)', async () => { const [w, webview] = await loadWebViewWindow(); expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false(); const parentFullscreen = once(ipcMain, 'fullscreenchange'); const enterHTMLFS = once(w.webContents, 'enter-html-full-screen'); const leaveHTMLFS = once(w.webContents, 'leave-html-full-screen'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true(); await webview.executeJavaScript('document.exitFullscreen()'); await Promise.all([enterHTMLFS, leaveHTMLFS, parentFullscreen]); const close = once(w, 'closed'); w.close(); await close; }); // FIXME(zcbenz): Fullscreen events do not work on Linux. ifit(process.platform !== 'linux')('exiting fullscreen should unfullscreen window', async () => { const [w, webview] = await loadWebViewWindow(); const enterFullScreen = once(w, 'enter-full-screen'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); await webview.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; await setTimeout(); expect(w.isFullScreen()).to.be.false(); const close = once(w, 'closed'); w.close(); await close; }); it('pressing ESC should unfullscreen window', async () => { const [w, webview] = await loadWebViewWindow(); const enterFullScreen = once(w, 'enter-full-screen'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); webview.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); await leaveFullScreen; await setTimeout(1000); expect(w.isFullScreen()).to.be.false(); const close = once(w, 'closed'); w.close(); await close; }); it('pressing ESC should emit the leave-html-full-screen event', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const enterFSWindow = once(w, 'enter-html-full-screen'); const enterFSWebview = once(webContents, 'enter-html-full-screen'); await webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFSWindow; await enterFSWebview; const leaveFSWindow = once(w, 'leave-html-full-screen'); const leaveFSWebview = once(webContents, 'leave-html-full-screen'); webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); await leaveFSWebview; await leaveFSWindow; const close = once(w, 'closed'); w.close(); await close; }); it('should support user gesture', async () => { const [w, webview] = await loadWebViewWindow(); const waitForEnterHtmlFullScreen = once(webview, 'enter-html-full-screen'); const jsScript = "document.querySelector('video').webkitRequestFullscreen()"; webview.executeJavaScript(jsScript, true); await waitForEnterHtmlFullScreen; const close = once(w, 'closed'); w.close(); await close; }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('opens window of about:blank with cross-scripting enabled', async () => { // Don't wait for loading to finish. loadWebView(w.webContents, { allowpopups: 'on', nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${path.join(fixtures, 'api', 'native-window-open-blank.html')}` }); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { // Don't wait for loading to finish. loadWebView(w.webContents, { allowpopups: 'on', nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${path.join(fixtures, 'api', 'native-window-open-file.html')}` }); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); it('returns null from window.open when allowpopups is not set', async () => { // Don't wait for loading to finish. loadWebView(w.webContents, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${path.join(fixtures, 'api', 'native-window-open-no-allowpopups.html')}` }); const [, { windowOpenReturnedNull }] = await once(ipcMain, 'answer'); expect(windowOpenReturnedNull).to.be.true(); }); it('blocks accessing cross-origin frames', async () => { // Don't wait for loading to finish. loadWebView(w.webContents, { allowpopups: 'on', nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${path.join(fixtures, 'api', 'native-window-open-cross-origin.html')}` }); const [, content] = await once(ipcMain, 'answer'); const expectedContent = /Failed to read a named property 'toString' from 'Location': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./; expect(content).to.match(expectedContent); }); it('emits a browser-window-created event', async () => { // Don't wait for loading to finish. loadWebView(w.webContents, { allowpopups: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/window-open.html` }); await once(app, 'browser-window-created'); }); it('emits a web-contents-created event', async () => { const webContentsCreated = emittedUntil(app, 'web-contents-created', (event: Electron.Event, contents: Electron.WebContents) => contents.getType() === 'window'); loadWebView(w.webContents, { allowpopups: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/window-open.html` }); await webContentsCreated; }); it('does not crash when creating window with noopener', async () => { loadWebView(w.webContents, { allowpopups: 'on', src: `file://${path.join(fixtures, 'api', 'native-window-open-noopener.html')}` }); await once(app, 'browser-window-created'); }); }); describe('webpreferences attribute', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('can enable context isolation', async () => { loadWebView(w.webContents, { allowpopups: 'yes', preload: `file://${fixtures}/api/isolated-preload.js`, src: `file://${fixtures}/api/isolated.html`, webpreferences: 'contextIsolation=yes' }); const [, data] = await once(ipcMain, 'isolated-world'); expect(data).to.deep.equal({ 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' } }); }); }); describe('permission request handlers', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); const partition = 'permissionTest'; function setUpRequestHandler (webContentsId: number, requestedPermission: string) { return new Promise<void>((resolve, reject) => { session.fromPartition(partition).setPermissionRequestHandler(function (webContents, permission, callback) { if (webContents.id === webContentsId) { // requestMIDIAccess with sysex requests both midi and midiSysex so // grant the first midi one and then reject the midiSysex one if (requestedPermission === 'midiSysex' && permission === 'midi') { return callback(true); } try { expect(permission).to.equal(requestedPermission); } catch (e) { return reject(e); } callback(false); resolve(); } }); }); } afterEach(() => { session.fromPartition(partition).setPermissionRequestHandler(null); }); // This is disabled because CI machines don't have cameras or microphones, // so Chrome responds with "NotFoundError" instead of // "PermissionDeniedError". It should be re-enabled if we find a way to mock // the presence of a microphone & camera. xit('emits when using navigator.getUserMedia api', async () => { const errorFromRenderer = once(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/media.html`, partition, nodeintegration: 'on' }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; setUpRequestHandler(webViewContents.id, 'media'); const [, errorName] = await errorFromRenderer; expect(errorName).to.equal('PermissionDeniedError'); }); it('emits when using navigator.geolocation api', async () => { const errorFromRenderer = once(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/geolocation.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; setUpRequestHandler(webViewContents.id, 'geolocation'); const [, error] = await errorFromRenderer; expect(error).to.equal('User denied Geolocation'); }); it('emits when using navigator.requestMIDIAccess without sysex api', async () => { const errorFromRenderer = once(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/midi.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; setUpRequestHandler(webViewContents.id, 'midi'); const [, error] = await errorFromRenderer; expect(error).to.equal('SecurityError'); }); it('emits when using navigator.requestMIDIAccess with sysex api', async () => { const errorFromRenderer = once(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/midi-sysex.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; setUpRequestHandler(webViewContents.id, 'midiSysex'); const [, error] = await errorFromRenderer; expect(error).to.equal('SecurityError'); }); it('emits when accessing external protocol', async () => { loadWebView(w.webContents, { src: 'magnet:test', partition }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; await setUpRequestHandler(webViewContents.id, 'openExternal'); }); it('emits when using Notification.requestPermission', async () => { const errorFromRenderer = once(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/notification.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents]; await setUpRequestHandler(webViewContents.id, 'notifications'); const [, error] = await errorFromRenderer; expect(error).to.equal('denied'); }); }); describe('DOM events', () => { afterEach(closeAllWindows); it('receives extra properties on DOM events when contextIsolation is enabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, contextIsolation: true } }); await w.loadURL('about:blank'); const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { const webview = new WebView() webview.setAttribute('src', 'data:text/html,<script>console.log("hi")</script>') webview.addEventListener('console-message', (e) => { resolve(e.message) }) document.body.appendChild(webview) })`); expect(message).to.equal('hi'); }); it('emits focus event when contextIsolation is enabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, contextIsolation: true } }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { const webview = new WebView() webview.setAttribute('src', 'about:blank') webview.addEventListener('dom-ready', () => { webview.focus() }) webview.addEventListener('focus', () => { resolve(); }) document.body.appendChild(webview) })`); }); }); describe('attributes', () => { let w: WebContents; before(async () => { const window = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); await window.loadURL(`file://${fixtures}/pages/blank.html`); w = window.webContents; }); afterEach(async () => { await w.executeJavaScript(`{ for (const el of document.querySelectorAll('webview')) el.remove(); }`); }); after(closeAllWindows); describe('src attribute', () => { it('specifies the page to load', async () => { const message = await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/a.html` }); expect(message).to.equal('a'); }); it('navigates to new page when changed', async () => { await loadWebView(w, { src: `file://${fixtures}/pages/a.html` }); const { message } = await w.executeJavaScript(`new Promise(resolve => { webview.addEventListener('console-message', e => resolve({message: e.message})) webview.src = ${JSON.stringify(`file://${fixtures}/pages/b.html`)} })`); expect(message).to.equal('b'); }); it('resolves relative URLs', async () => { const message = await loadWebViewAndWaitForMessage(w, { src: './e.html' }); expect(message).to.equal('Window script is loaded before preload script'); }); it('ignores empty values', async () => { loadWebView(w, {}); for (const emptyValue of ['""', 'null', 'undefined']) { const src = await w.executeJavaScript(`webview.src = ${emptyValue}, webview.src`); expect(src).to.equal(''); } }); it('does not wait until loadURL is resolved', async () => { await loadWebView(w, { src: 'about:blank' }); const delay = await w.executeJavaScript(`new Promise(resolve => { const before = Date.now(); webview.src = 'file://${fixtures}/pages/blank.html'; const now = Date.now(); resolve(now - before); })`); // Setting src is essentially sending a sync IPC message, which should // not exceed more than a few ms. // // This is for testing #18638. expect(delay).to.be.below(100); }); }); describe('nodeintegration attribute', () => { it('inserts no node symbols when not set', async () => { const message = await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/c.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'undefined', module: 'undefined', process: 'undefined', global: 'undefined' }); }); it('inserts node symbols when set', async () => { const message = await loadWebViewAndWaitForMessage(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/d.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object' }); }); it('loads node symbols after POST navigation when set', async function () { const message = await loadWebViewAndWaitForMessage(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/post.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object' }); }); it('disables node integration on child windows when it is disabled on the webview', async () => { const src = url.format({ pathname: `${fixtures}/pages/webview-opener-no-node-integration.html`, protocol: 'file', query: { p: `${fixtures}/pages/window-opener-node.html` }, slashes: true }); const message = await loadWebViewAndWaitForMessage(w, { allowpopups: 'on', webpreferences: 'contextIsolation=no', src }); expect(JSON.parse(message).isProcessGlobalUndefined).to.be.true(); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native modules when navigation happens', async function () { await loadWebView(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/native-module.html` }); const message = await w.executeJavaScript(`new Promise(resolve => { webview.addEventListener('console-message', e => resolve(e.message)) webview.reload(); })`); expect(message).to.equal('function'); }); }); describe('preload attribute', () => { useRemoteContext({ webPreferences: { webviewTag: true } }); it('loads the script before other scripts in window', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: `${fixtures}/module/preload.js`, src: `file://${fixtures}/pages/e.html` }); expect(message).to.be.a('string'); expect(message).to.be.not.equal('Window script is loaded before preload script'); }); it('preload script can still use "process" and "Buffer" when nodeintegration is off', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: `${fixtures}/module/preload-node-off.js`, src: `file://${fixtures}/api/blank.html` }); const types = JSON.parse(message); expect(types).to.include({ process: 'object', Buffer: 'function' }); }); it('runs in the correct scope when sandboxed', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: `${fixtures}/module/preload-context.js`, src: `file://${fixtures}/api/blank.html`, webpreferences: 'sandbox=yes' }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', // arguments passed to it should be available electron: 'undefined', // objects from the scope it is called from should not be available window: 'object', // the window object should be available localVar: 'undefined' // but local variables should not be exposed to the window }); }); it('preload script can require modules that still use "process" and "Buffer" when nodeintegration is off', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: `${fixtures}/module/preload-node-off-wrapper.js`, webpreferences: 'sandbox=no', src: `file://${fixtures}/api/blank.html` }); const types = JSON.parse(message); expect(types).to.include({ process: 'object', Buffer: 'function' }); }); it('receives ipc message in preload script', async () => { await loadWebView(w, { preload: `${fixtures}/module/preload-ipc.js`, src: `file://${fixtures}/pages/e.html` }); const message = 'boom!'; const { channel, args } = await w.executeJavaScript(`new Promise(resolve => { webview.send('ping', ${JSON.stringify(message)}) webview.addEventListener('ipc-message', ({channel, args}) => resolve({channel, args})) })`); expect(channel).to.equal('pong'); expect(args).to.deep.equal([message]); }); itremote('<webview>.sendToFrame()', async (fixtures: string) => { const w = new WebView(); w.setAttribute('nodeintegration', 'on'); w.setAttribute('webpreferences', 'contextIsolation=no'); w.setAttribute('preload', `file://${fixtures}/module/preload-ipc.js`); w.setAttribute('src', `file://${fixtures}/pages/ipc-message.html`); document.body.appendChild(w); const { frameId } = await new Promise<any>(resolve => w.addEventListener('ipc-message', resolve, { once: true })); const message = 'boom!'; w.sendToFrame(frameId, 'ping', message); const { channel, args } = await new Promise<any>(resolve => w.addEventListener('ipc-message', resolve, { once: true })); expect(channel).to.equal('pong'); expect(args).to.deep.equal([message]); }, [fixtures]); it('works without script tag in page', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: `${fixtures}/module/preload.js`, webpreferences: 'sandbox=no', src: `file://${fixtures}/pages/base-page.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object', Buffer: 'function' }); }); it('resolves relative URLs', async () => { const message = await loadWebViewAndWaitForMessage(w, { preload: '../module/preload.js', webpreferences: 'sandbox=no', src: `file://${fixtures}/pages/e.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object', Buffer: 'function' }); }); itremote('ignores empty values', async () => { const webview = new WebView(); for (const emptyValue of ['', null, undefined]) { webview.preload = emptyValue; expect(webview.preload).to.equal(''); } }); }); describe('httpreferrer attribute', () => { it('sets the referrer url', async () => { const referrer = 'http://github.com/'; const received = await new Promise<string | undefined>((resolve, reject) => { const server = http.createServer((req, res) => { try { resolve(req.headers.referer); } catch (e) { reject(e); } finally { res.end(); server.close(); } }); listen(server).then(({ url }) => { loadWebView(w, { httpreferrer: referrer, src: url }); }); }); expect(received).to.equal(referrer); }); }); describe('useragent attribute', () => { it('sets the user agent', async () => { const referrer = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko'; const message = await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/useragent.html`, useragent: referrer }); expect(message).to.equal(referrer); }); }); describe('disablewebsecurity attribute', () => { it('does not disable web security when not set', async () => { await loadWebView(w, { src: 'about:blank' }); const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`); expect(result).to.equal('failed'); }); it('disables web security when set', async () => { await loadWebView(w, { src: 'about:blank', disablewebsecurity: '' }); const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`); expect(result).to.equal('ok'); }); it('does not break node integration', async () => { const message = await loadWebViewAndWaitForMessage(w, { disablewebsecurity: '', nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/d.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object' }); }); it('does not break preload script', async () => { const message = await loadWebViewAndWaitForMessage(w, { disablewebsecurity: '', preload: `${fixtures}/module/preload.js`, webpreferences: 'sandbox=no', src: `file://${fixtures}/pages/e.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object', Buffer: 'function' }); }); }); describe('partition attribute', () => { it('inserts no node symbols when not set', async () => { const message = await loadWebViewAndWaitForMessage(w, { partition: 'test1', src: `file://${fixtures}/pages/c.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'undefined', module: 'undefined', process: 'undefined', global: 'undefined' }); }); it('inserts node symbols when set', async () => { const message = await loadWebViewAndWaitForMessage(w, { nodeintegration: 'on', partition: 'test2', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/d.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object' }); }); it('isolates storage for different id', async () => { await w.executeJavaScript('localStorage.setItem(\'test\', \'one\')'); const message = await loadWebViewAndWaitForMessage(w, { partition: 'test3', src: `file://${fixtures}/pages/partition/one.html` }); const parsedMessage = JSON.parse(message); expect(parsedMessage).to.include({ numberOfEntries: 0, testValue: null }); }); it('uses current session storage when no id is provided', async () => { await w.executeJavaScript('localStorage.setItem(\'test\', \'two\')'); const testValue = 'two'; const message = await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/partition/one.html` }); const parsedMessage = JSON.parse(message); expect(parsedMessage).to.include({ testValue }); }); }); describe('allowpopups attribute', () => { const generateSpecs = (description: string, webpreferences = '') => { describe(description, () => { it('can not open new window when not set', async () => { const message = await loadWebViewAndWaitForMessage(w, { webpreferences, src: `file://${fixtures}/pages/window-open-hide.html` }); expect(message).to.equal('null'); }); it('can open new window when set', async () => { const message = await loadWebViewAndWaitForMessage(w, { webpreferences, allowpopups: 'on', src: `file://${fixtures}/pages/window-open-hide.html` }); expect(message).to.equal('window'); }); }); }; generateSpecs('without sandbox'); generateSpecs('with sandbox', 'sandbox=yes'); }); describe('webpreferences attribute', () => { it('can enable nodeintegration', async () => { const message = await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/d.html`, webpreferences: 'nodeIntegration,contextIsolation=no' }); const types = JSON.parse(message); expect(types).to.include({ require: 'function', module: 'object', process: 'object' }); }); it('can disable web security and enable nodeintegration', async () => { await loadWebView(w, { src: 'about:blank', webpreferences: 'webSecurity=no, nodeIntegration=yes, contextIsolation=no' }); const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`); expect(result).to.equal('ok'); const type = await w.executeJavaScript('webview.executeJavaScript("typeof require")'); expect(type).to.equal('function'); }); }); }); describe('events', () => { useRemoteContext({ webPreferences: { webviewTag: true } }); let w: WebContents; before(async () => { const window = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); await window.loadURL(`file://${fixtures}/pages/blank.html`); w = window.webContents; }); afterEach(async () => { await w.executeJavaScript(`{ for (const el of document.querySelectorAll('webview')) el.remove(); }`); }); after(closeAllWindows); describe('ipc-message event', () => { it('emits when guest sends an ipc message to browser', async () => { const { frameId, channel, args } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/ipc-message.html`, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }, 'ipc-message'); expect(frameId).to.be.an('array').that.has.lengthOf(2); expect(channel).to.equal('channel'); expect(args).to.deep.equal(['arg1', 'arg2']); }); }); describe('page-title-updated event', () => { it('emits when title is set', async () => { const { title, explicitSet } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/a.html` }, 'page-title-updated'); expect(title).to.equal('test'); expect(explicitSet).to.be.true(); }); }); describe('page-favicon-updated event', () => { it('emits when favicon urls are received', async () => { const { favicons } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/a.html` }, 'page-favicon-updated'); expect(favicons).to.be.an('array').of.length(2); if (process.platform === 'win32') { expect(favicons[0]).to.match(/^file:\/\/\/[A-Z]:\/favicon.png$/i); } else { expect(favicons[0]).to.equal('file:///favicon.png'); } }); }); describe('did-redirect-navigation event', () => { it('is emitted on redirects', async () => { const server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } }); const { url } = await listen(server); defer(() => { server.close(); }); const event = await loadWebViewAndWaitForEvent(w, { src: `${url}/302` }, 'did-redirect-navigation'); expect(event.url).to.equal(`${url}/200`); expect(event.isInPlace).to.be.false(); expect(event.isMainFrame).to.be.true(); expect(event.frameProcessId).to.be.a('number'); expect(event.frameRoutingId).to.be.a('number'); }); }); describe('will-navigate event', () => { it('emits when a url that leads to outside of the page is loaded', async () => { const { url } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/webview-will-navigate.html` }, 'will-navigate'); expect(url).to.equal('http://host/'); }); }); describe('will-frame-navigate event', () => { it('emits when a link that leads to outside of the page is loaded', async () => { const { url, isMainFrame } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/webview-will-navigate.html` }, 'will-frame-navigate'); expect(url).to.equal('http://host/'); expect(isMainFrame).to.be.true(); }); it('emits when a link within an iframe, which leads to outside of the page, is loaded', async () => { await loadWebView(w, { src: `file://${fixtures}/pages/webview-will-navigate-in-frame.html`, nodeIntegration: '' }); const { url, frameProcessId, frameRoutingId } = await w.executeJavaScript(` new Promise((resolve, reject) => { let hasFrameNavigatedOnce = false; const webview = document.getElementById('webview'); webview.addEventListener('will-frame-navigate', ({url, isMainFrame, frameProcessId, frameRoutingId}) => { if (isMainFrame) return; if (hasFrameNavigatedOnce) resolve({ url, isMainFrame, frameProcessId, frameRoutingId, }); // First navigation is the initial iframe load within the <webview> hasFrameNavigatedOnce = true; }); webview.executeJavaScript('loadSubframe()'); }); `); expect(url).to.equal('http://host/'); expect(frameProcessId).to.be.a('number'); expect(frameRoutingId).to.be.a('number'); }); }); describe('did-navigate event', () => { it('emits when a url that leads to outside of the page is clicked', async () => { const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-will-navigate.html')).toString(); const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate'); expect(event.url).to.equal(pageUrl); }); }); describe('did-navigate-in-page event', () => { it('emits when an anchor link is clicked', async () => { const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-did-navigate-in-page.html')).toString(); const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate-in-page'); expect(event.url).to.equal(`${pageUrl}#test_content`); }); it('emits when window.history.replaceState is called', async () => { const { url } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/webview-did-navigate-in-page-with-history.html` }, 'did-navigate-in-page'); expect(url).to.equal('http://host/'); }); it('emits when window.location.hash is changed', async () => { const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-did-navigate-in-page-with-hash.html')).toString(); const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate-in-page'); expect(event.url).to.equal(`${pageUrl}#test`); }); }); describe('close event', () => { it('should fire when interior page calls window.close', async () => { await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/close.html` }, 'close'); }); }); describe('devtools-opened event', () => { it('should fire when webview.openDevTools() is called', async () => { await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/base-page.html` }, 'dom-ready'); await w.executeJavaScript(`new Promise((resolve) => { webview.openDevTools() webview.addEventListener('devtools-opened', () => resolve(), {once: true}) })`); await w.executeJavaScript('webview.closeDevTools()'); }); }); describe('devtools-closed event', () => { itremote('should fire when webview.closeDevTools() is called', async (fixtures: string) => { const webview = new WebView(); webview.src = `file://${fixtures}/pages/base-page.html`; document.body.appendChild(webview); await new Promise(resolve => webview.addEventListener('dom-ready', resolve, { once: true })); webview.openDevTools(); await new Promise(resolve => webview.addEventListener('devtools-opened', resolve, { once: true })); webview.closeDevTools(); await new Promise(resolve => webview.addEventListener('devtools-closed', resolve, { once: true })); }, [fixtures]); }); describe('devtools-focused event', () => { itremote('should fire when webview.openDevTools() is called', async (fixtures: string) => { const webview = new WebView(); webview.src = `file://${fixtures}/pages/base-page.html`; document.body.appendChild(webview); const waitForDevToolsFocused = new Promise(resolve => webview.addEventListener('devtools-focused', resolve, { once: true })); await new Promise(resolve => webview.addEventListener('dom-ready', resolve, { once: true })); webview.openDevTools(); await waitForDevToolsFocused; webview.closeDevTools(); }, [fixtures]); }); describe('dom-ready event', () => { it('emits when document is loaded', async () => { const server = http.createServer(() => {}); const { port } = await listen(server); await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/dom-ready.html?port=${port}` }, 'dom-ready'); }); itremote('throws a custom error when an API method is called before the event is emitted', () => { const expectedErrorMessage = 'The WebView must be attached to the DOM ' + 'and the dom-ready event emitted before this method can be called.'; const webview = new WebView(); expect(() => { webview.stop(); }).to.throw(expectedErrorMessage); }); }); describe('context-menu event', () => { it('emits when right-clicked in page', async () => { await loadWebView(w, { src: 'about:blank' }); const { params, url } = await w.executeJavaScript(`new Promise(resolve => { webview.addEventListener('context-menu', (e) => resolve({...e, url: webview.getURL() }), {once: true}) // Simulate right-click to create context-menu event. const opts = { x: 0, y: 0, button: 'right' }; webview.sendInputEvent({ ...opts, type: 'mouseDown' }); webview.sendInputEvent({ ...opts, type: 'mouseUp' }); })`); expect(params.pageURL).to.equal(url); expect(params.frame).to.be.undefined(); expect(params.x).to.be.a('number'); expect(params.y).to.be.a('number'); }); }); describe('found-in-page event', () => { itremote('emits when a request is made', async (fixtures: string) => { const webview = new WebView(); const didFinishLoad = new Promise(resolve => webview.addEventListener('did-finish-load', resolve, { once: true })); webview.src = `file://${fixtures}/pages/content.html`; document.body.appendChild(webview); // TODO(deepak1556): With https://codereview.chromium.org/2836973002 // focus of the webContents is required when triggering the api. // Remove this workaround after determining the cause for // incorrect focus. webview.focus(); await didFinishLoad; const activeMatchOrdinal = []; for (;;) { const foundInPage = new Promise<any>(resolve => webview.addEventListener('found-in-page', resolve, { once: true })); const requestId = webview.findInPage('virtual'); const event = await foundInPage; expect(event.result.requestId).to.equal(requestId); expect(event.result.matches).to.equal(3); activeMatchOrdinal.push(event.result.activeMatchOrdinal); if (event.result.activeMatchOrdinal === event.result.matches) { break; } } expect(activeMatchOrdinal).to.deep.equal([1, 2, 3]); webview.stopFindInPage('clearSelection'); }, [fixtures]); }); describe('will-attach-webview event', () => { itremote('does not emit when src is not changed', async () => { const webview = new WebView(); document.body.appendChild(webview); await setTimeout(); const expectedErrorMessage = 'The WebView must be attached to the DOM and the dom-ready event emitted before this method can be called.'; expect(() => { webview.stop(); }).to.throw(expectedErrorMessage); }); it('supports changing the web preferences', async () => { w.once('will-attach-webview', (event, webPreferences, params) => { params.src = `file://${path.join(fixtures, 'pages', 'c.html')}`; webPreferences.nodeIntegration = false; }); const message = await loadWebViewAndWaitForMessage(w, { nodeintegration: 'yes', src: `file://${fixtures}/pages/a.html` }); const types = JSON.parse(message); expect(types).to.include({ require: 'undefined', module: 'undefined', process: 'undefined', global: 'undefined' }); }); it('handler modifying params.instanceId does not break <webview>', async () => { w.once('will-attach-webview', (event, webPreferences, params) => { params.instanceId = null as any; }); await loadWebViewAndWaitForMessage(w, { src: `file://${fixtures}/pages/a.html` }); }); it('supports preventing a webview from being created', async () => { w.once('will-attach-webview', event => event.preventDefault()); await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/c.html` }, 'destroyed'); }); it('supports removing the preload script', async () => { w.once('will-attach-webview', (event, webPreferences, params) => { params.src = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-stripped-preload.html')).toString(); delete webPreferences.preload; }); const message = await loadWebViewAndWaitForMessage(w, { nodeintegration: 'yes', preload: path.join(fixtures, 'module', 'preload-set-global.js'), src: `file://${fixtures}/pages/a.html` }); expect(message).to.equal('undefined'); }); }); describe('media-started-playing and media-paused events', () => { it('emits when audio starts and stops playing', async function () { if (!await w.executeJavaScript('document.createElement(\'audio\').canPlayType(\'audio/wav\')')) { return this.skip(); } await loadWebView(w, { src: blankPageUrl }); // With the new autoplay policy, audio elements must be unmuted // see https://goo.gl/xX8pDD. await w.executeJavaScript(`new Promise(resolve => { webview.executeJavaScript(\` const audio = document.createElement("audio") audio.src = "../assets/tone.wav" document.body.appendChild(audio); audio.play() \`, true) webview.addEventListener('media-started-playing', () => resolve(), {once: true}) })`); await w.executeJavaScript(`new Promise(resolve => { webview.executeJavaScript(\` document.querySelector("audio").pause() \`, true) webview.addEventListener('media-paused', () => resolve(), {once: true}) })`); }); }); }); describe('methods', () => { let w: WebContents; before(async () => { const window = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); await window.loadURL(`file://${fixtures}/pages/blank.html`); w = window.webContents; }); afterEach(async () => { await w.executeJavaScript(`{ for (const el of document.querySelectorAll('webview')) el.remove(); }`); }); after(closeAllWindows); describe('<webview>.reload()', () => { it('should emit beforeunload handler', async () => { await loadWebView(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/beforeunload-false.html` }); // Event handler has to be added before reload. const channel = await w.executeJavaScript(`new Promise(resolve => { webview.addEventListener('ipc-message', e => resolve(e.channel)) webview.reload(); })`); expect(channel).to.equal('onbeforeunload'); }); }); describe('<webview>.goForward()', () => { useRemoteContext({ webPreferences: { webviewTag: true } }); itremote('should work after a replaced history entry', async (fixtures: string) => { function waitForEvent (target: EventTarget, event: string) { return new Promise<any>(resolve => target.addEventListener(event, resolve, { once: true })); } function waitForEvents (target: EventTarget, ...events: string[]) { return Promise.all(events.map(event => waitForEvent(webview, event))); } const webview = new WebView(); webview.setAttribute('nodeintegration', 'on'); webview.setAttribute('webpreferences', 'contextIsolation=no'); webview.src = `file://${fixtures}/pages/history-replace.html`; document.body.appendChild(webview); { const [e] = await waitForEvents(webview, 'ipc-message', 'did-stop-loading'); expect(e.channel).to.equal('history'); expect(e.args[0]).to.equal(1); expect(webview.canGoBack()).to.be.false(); expect(webview.canGoForward()).to.be.false(); } webview.src = `file://${fixtures}/pages/base-page.html`; await new Promise<void>(resolve => webview.addEventListener('did-stop-loading', resolve, { once: true })); expect(webview.canGoBack()).to.be.true(); expect(webview.canGoForward()).to.be.false(); webview.goBack(); { const [e] = await waitForEvents(webview, 'ipc-message', 'did-stop-loading'); expect(e.channel).to.equal('history'); expect(e.args[0]).to.equal(2); expect(webview.canGoBack()).to.be.false(); expect(webview.canGoForward()).to.be.true(); } webview.goForward(); await new Promise<void>(resolve => webview.addEventListener('did-stop-loading', resolve, { once: true })); expect(webview.canGoBack()).to.be.true(); expect(webview.canGoForward()).to.be.false(); }, [fixtures]); }); describe('<webview>.clearHistory()', () => { it('should clear the navigation history', async () => { await loadWebView(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: blankPageUrl }); // Navigation must be triggered by a user gesture to make canGoBack() return true await w.executeJavaScript('webview.executeJavaScript(`history.pushState(null, "", "foo.html")`, true)'); expect(await w.executeJavaScript('webview.canGoBack()')).to.be.true(); await w.executeJavaScript('webview.clearHistory()'); expect(await w.executeJavaScript('webview.canGoBack()')).to.be.false(); }); }); describe('executeJavaScript', () => { it('can return the result of the executed script', async () => { await loadWebView(w, { src: 'about:blank' }); const jsScript = "'4'+2"; const expectedResult = '42'; const result = await w.executeJavaScript(`webview.executeJavaScript(${JSON.stringify(jsScript)})`); expect(result).to.equal(expectedResult); }); }); it('supports inserting CSS', async () => { await loadWebView(w, { src: `file://${fixtures}/pages/base-page.html` }); await w.executeJavaScript('webview.insertCSS(\'body { background-repeat: round; }\')'); const result = await w.executeJavaScript('webview.executeJavaScript(\'window.getComputedStyle(document.body).getPropertyValue("background-repeat")\')'); expect(result).to.equal('round'); }); it('supports removing inserted CSS', async () => { await loadWebView(w, { src: `file://${fixtures}/pages/base-page.html` }); const key = await w.executeJavaScript('webview.insertCSS(\'body { background-repeat: round; }\')'); await w.executeJavaScript(`webview.removeInsertedCSS(${JSON.stringify(key)})`); const result = await w.executeJavaScript('webview.executeJavaScript(\'window.getComputedStyle(document.body).getPropertyValue("background-repeat")\')'); expect(result).to.equal('repeat'); }); describe('sendInputEvent', () => { it('can send keyboard event', async () => { await loadWebViewAndWaitForEvent(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/onkeyup.html` }, 'dom-ready'); const waitForIpcMessage = w.executeJavaScript('new Promise(resolve => webview.addEventListener("ipc-message", e => resolve({...e})), {once: true})'); w.executeJavaScript(`webview.sendInputEvent({ type: 'keyup', keyCode: 'c', modifiers: ['shift'] })`); const { channel, args } = await waitForIpcMessage; expect(channel).to.equal('keyup'); expect(args).to.deep.equal(['C', 'KeyC', 67, true, false]); }); it('can send mouse event', async () => { await loadWebViewAndWaitForEvent(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/onmouseup.html` }, 'dom-ready'); const waitForIpcMessage = w.executeJavaScript('new Promise(resolve => webview.addEventListener("ipc-message", e => resolve({...e})), {once: true})'); w.executeJavaScript(`webview.sendInputEvent({ type: 'mouseup', modifiers: ['ctrl'], x: 10, y: 20 })`); const { channel, args } = await waitForIpcMessage; expect(channel).to.equal('mouseup'); expect(args).to.deep.equal([10, 20, false, true]); }); }); describe('<webview>.getWebContentsId', () => { it('can return the WebContents ID', async () => { await loadWebView(w, { src: 'about:blank' }); expect(await w.executeJavaScript('webview.getWebContentsId()')).to.be.a('number'); }); }); ifdescribe(features.isPrintingEnabled())('<webview>.printToPDF()', () => { it('rejects on incorrectly typed parameters', async () => { const badTypes = { landscape: [], displayHeaderFooter: '123', printBackground: 2, scale: 'not-a-number', pageSize: 'IAmAPageSize', margins: 'terrible', pageRanges: { oops: 'im-not-the-right-key' }, headerTemplate: [1, 2, 3], footerTemplate: [4, 5, 6], preferCSSPageSize: 'no' }; // These will hard crash in Chromium unless we type-check for (const [key, value] of Object.entries(badTypes)) { const param = { [key]: value }; const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'; await loadWebView(w, { src }); await expect(w.executeJavaScript(`webview.printToPDF(${JSON.stringify(param)})`)).to.eventually.be.rejected(); } }); it('can print to PDF', async () => { const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'; await loadWebView(w, { src }); const data = await w.executeJavaScript('webview.printToPDF({})'); expect(data).to.be.an.instanceof(Uint8Array).that.is.not.empty(); }); }); describe('DOM events', () => { for (const [description, sandbox] of [ ['without sandbox', false] as const, ['with sandbox', true] as const ]) { describe(description, () => { it('emits focus event', async () => { await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/a.html`, webpreferences: `sandbox=${sandbox ? 'yes' : 'no'}` }, 'dom-ready'); // If this test fails, check if webview.focus() still works. await w.executeJavaScript(`new Promise(resolve => { webview.addEventListener('focus', () => resolve(), {once: true}); webview.focus(); })`); }); }); } }); // TODO(miniak): figure out why this is failing on windows ifdescribe(process.platform !== 'win32')('<webview>.capturePage()', () => { it('returns a Promise with a NativeImage', async function () { this.retries(5); const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'; await loadWebViewAndWaitForEvent(w, { src }, 'did-stop-loading'); const image = await w.executeJavaScript('webview.capturePage()'); expect(image.isEmpty()).to.be.false(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha const imgBuffer = image.toPNG(); expect(imgBuffer[25]).to.equal(6); }); it('returns a Promise with a NativeImage in the renderer', async function () { this.retries(5); const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'; await loadWebViewAndWaitForEvent(w, { src }, 'did-stop-loading'); const byte = await w.executeJavaScript(`new Promise(resolve => { webview.capturePage().then(image => { resolve(image.toPNG()[25]) }); })`); expect(byte).to.equal(6); }); }); // FIXME(zcbenz): Disabled because of moving to OOPIF webview. xdescribe('setDevToolsWebContents() API', () => { /* it('sets webContents of webview as devtools', async () => { const webview2 = new WebView(); loadWebView(webview2); // Setup an event handler for further usage. const waitForDomReady = waitForEvent(webview2, 'dom-ready'); loadWebView(webview, { src: 'about:blank' }); await waitForEvent(webview, 'dom-ready'); webview.getWebContents().setDevToolsWebContents(webview2.getWebContents()); webview.getWebContents().openDevTools(); await waitForDomReady; // Its WebContents should be a DevTools. const devtools = webview2.getWebContents(); expect(devtools.getURL().startsWith('devtools://devtools')).to.be.true(); const name = await devtools.executeJavaScript('InspectorFrontendHost.constructor.name'); document.body.removeChild(webview2); expect(name).to.be.equal('InspectorFrontendHostImpl'); }); */ }); }); describe('basic auth', () => { let w: WebContents; before(async () => { const window = new BrowserWindow({ show: false, webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); await window.loadURL(`file://${fixtures}/pages/blank.html`); w = window.webContents; }); afterEach(async () => { await w.executeJavaScript(`{ for (const el of document.querySelectorAll('webview')) el.remove(); }`); }); after(closeAllWindows); it('should authenticate with correct credentials', async () => { const message = 'Authenticated'; const server = http.createServer((req, res) => { const credentials = auth(req)!; if (credentials.name === 'test' && credentials.pass === 'test') { res.end(message); } else { res.end('failed'); } }); defer(() => { server.close(); }); const { port } = await listen(server); const e = await loadWebViewAndWaitForEvent(w, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/basic-auth.html?port=${port}` }, 'ipc-message'); expect(e.channel).to.equal(message); }); }); });
closed
electron/electron
https://github.com/electron/electron
39,833
[Bug]: passing resizable windowfeature and disabling fullscreening also disables ability to maximize the window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.8.0, 26.2.0 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 25.7.0 ### Expected Behavior I expect that calling `window.open(url, name, "resizable")` and then setting `fullscreenable:false` in `setWindowOpenHandler` will disable fullscreening, but continue to allow you to maximize the window. ### Actual Behavior Maximizing is disabled (`isMaximizable()` returns `false`) ### Testcase Gist URL https://gist.github.com/pushkin-/c7651478899a6c944d28c2d7aa3232ba ### Additional Information Seems to have regressed in [this PR](https://github.com/electron/electron/pull/39620) If you don't pass the `resizable` window feature, there's no issue. Perhaps related somewhat to [this issue](https://github.com/electron/electron/issues/39832)?
https://github.com/electron/electron/issues/39833
https://github.com/electron/electron/pull/40705
22970f573b3ced41ad6b0e2c3e124e3a4ed6b40e
cc1b64e01c334dc9b27cea7c90a066645f983190
2023-09-12T15:46:17Z
c++
2024-01-05T17:15:35Z
shell/browser/native_window_mac.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #import <Cocoa/Cocoa.h> #include <memory> #include <string> #include <vector> #include "electron/shell/common/api/api.mojom.h" #include "shell/browser/native_window.h" #include "ui/display/display_observer.h" #include "ui/native_theme/native_theme_observer.h" #include "ui/views/controls/native/native_view_host.h" @class ElectronNSWindow; @class ElectronNSWindowDelegate; @class ElectronPreviewItem; @class ElectronTouchBar; @class WindowButtonsProxy; namespace electron { class RootViewMac; class NativeWindowMac : public NativeWindow, public ui::NativeThemeObserver, public display::DisplayObserver { public: NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent); ~NativeWindowMac() override; // NativeWindow: void SetContentView(views::View* view) override; void Close() override; void CloseImmediately() override; void Focus(bool focus) override; bool IsFocused() const override; void Show() override; void ShowInactive() override; void Hide() override; bool IsVisible() const override; bool IsEnabled() const override; void SetEnabled(bool enable) override; void Maximize() override; void Unmaximize() override; bool IsMaximized() const override; void Minimize() override; void Restore() override; bool IsMinimized() const override; void SetFullScreen(bool fullscreen) override; bool IsFullscreen() const override; void SetBounds(const gfx::Rect& bounds, bool animate = false) override; gfx::Rect GetBounds() const override; bool IsNormal() const override; gfx::Rect GetNormalBounds() const override; void SetSizeConstraints( const extensions::SizeConstraints& window_constraints) override; void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) override; void SetResizable(bool resizable) override; bool MoveAbove(const std::string& sourceId) override; void MoveTop() override; bool IsResizable() const override; void SetMovable(bool movable) override; bool IsMovable() const override; void SetMinimizable(bool minimizable) override; bool IsMinimizable() const override; void SetMaximizable(bool maximizable) override; bool IsMaximizable() const override; void SetFullScreenable(bool fullscreenable) override; bool IsFullScreenable() const override; void SetClosable(bool closable) override; bool IsClosable() const override; void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relative_level) override; std::string GetAlwaysOnTopLevel() const override; ui::ZOrderLevel GetZOrderLevel() const override; void Center() override; void Invalidate() override; void SetTitle(const std::string& title) override; std::string GetTitle() const override; void FlashFrame(bool flash) override; void SetSkipTaskbar(bool skip) override; void SetExcludedFromShownWindowsMenu(bool excluded) override; bool IsExcludedFromShownWindowsMenu() const override; void SetSimpleFullScreen(bool simple_fullscreen) override; bool IsSimpleFullScreen() const override; void SetKiosk(bool kiosk) override; bool IsKiosk() const override; void SetBackgroundColor(SkColor color) override; SkColor GetBackgroundColor() const override; void InvalidateShadow() override; void SetHasShadow(bool has_shadow) override; bool HasShadow() const override; void SetOpacity(const double opacity) override; double GetOpacity() const override; void SetRepresentedFilename(const std::string& filename) override; std::string GetRepresentedFilename() const override; void SetDocumentEdited(bool edited) override; bool IsDocumentEdited() const override; void SetIgnoreMouseEvents(bool ignore, bool forward) override; bool IsHiddenInMissionControl() const override; void SetHiddenInMissionControl(bool hidden) override; void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; bool IsFocusable() const override; void SetParentWindow(NativeWindow* parent) override; content::DesktopMediaID GetDesktopMediaID() const override; gfx::NativeView GetNativeView() const override; gfx::NativeWindow GetNativeWindow() const override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; NativeWindowHandle GetNativeWindowHandle() const override; void SetProgressBar(double progress, const ProgressState state) override; void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) override; void SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) override; bool IsVisibleOnAllWorkspaces() const override; void SetAutoHideCursor(bool auto_hide) override; void SetVibrancy(const std::string& type) override; void SetWindowButtonVisibility(bool visible) override; bool GetWindowButtonVisibility() const override; void SetWindowButtonPosition(absl::optional<gfx::Point> position) override; absl::optional<gfx::Point> GetWindowButtonPosition() const override; void RedrawTrafficLights() override; void UpdateFrame() override; void SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) override; void RefreshTouchBarItem(const std::string& item_id) override; void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) override; void SelectPreviousTab() override; void SelectNextTab() override; void ShowAllTabs() override; void MergeAllWindows() override; void MoveTabToNewWindow() override; void ToggleTabBar() override; bool AddTabbedWindow(NativeWindow* window) override; absl::optional<std::string> GetTabbingIdentifier() const override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void PreviewFile(const std::string& path, const std::string& display_name) override; void CloseFilePreview() override; gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override; gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override; absl::optional<gfx::Rect> GetWindowControlsOverlayRect() override; void NotifyWindowEnterFullScreen() override; void NotifyWindowLeaveFullScreen() override; void SetActive(bool is_key) override; bool IsActive() const override; // Remove the specified child window without closing it. void RemoveChildWindow(NativeWindow* child) override; void RemoveChildFromParentWindow() override; // Attach child windows, if the window is visible. void AttachChildren() override; // Detach window from parent without destroying it. void DetachChildren() override; void NotifyWindowWillEnterFullScreen(); void NotifyWindowWillLeaveFullScreen(); // Cleanup observers when window is getting closed. Note that the destructor // can be called much later after window gets closed, so we should not do // cleanup in destructor. void Cleanup(); void UpdateVibrancyRadii(bool fullscreen); void UpdateWindowOriginalFrame(); // Set the attribute of NSWindow while work around a bug of zoom button. bool HasStyleMask(NSUInteger flag) const; void SetStyleMask(bool on, NSUInteger flag); void SetCollectionBehavior(bool on, NSUInteger flag); void SetWindowLevel(int level); bool HandleDeferredClose(); void SetHasDeferredWindowClose(bool defer_close) { has_deferred_window_close_ = defer_close; } void set_wants_to_be_visible(bool visible) { wants_to_be_visible_ = visible; } bool wants_to_be_visible() const { return wants_to_be_visible_; } enum class VisualEffectState { kFollowWindow, kActive, kInactive, }; ElectronPreviewItem* preview_item() const { return preview_item_; } ElectronTouchBar* touch_bar() const { return touch_bar_; } bool zoom_to_page_width() const { return zoom_to_page_width_; } bool always_simple_fullscreen() const { return always_simple_fullscreen_; } // We need to save the result of windowWillUseStandardFrame:defaultFrame // because macOS calls it with what it refers to as the "best fit" frame for a // zoom. This means that even if an aspect ratio is set, macOS might adjust it // to better fit the screen. // // Thus, we can't just calculate the maximized aspect ratio'd sizing from // the current visible screen and compare that to the current window's frame // to determine whether a window is maximized. NSRect default_frame_for_zoom() const { return default_frame_for_zoom_; } void set_default_frame_for_zoom(NSRect frame) { default_frame_for_zoom_ = frame; } protected: // views::WidgetDelegate: views::View* GetContentsView() override; bool CanMaximize() const override; std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView( views::Widget* widget) override; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; // display::DisplayObserver: void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; private: // Add custom layers to the content view. void AddContentViewLayers(); void InternalSetWindowButtonVisibility(bool visible); void InternalSetParentWindow(NativeWindow* parent, bool attach); void SetForwardMouseMessages(bool forward); ElectronNSWindow* window_; // Weak ref, managed by widget_. ElectronNSWindowDelegate* __strong window_delegate_; ElectronPreviewItem* __strong preview_item_; ElectronTouchBar* __strong touch_bar_; // The views::View that fills the client area. std::unique_ptr<RootViewMac> root_view_; bool fullscreen_before_kiosk_ = false; bool is_kiosk_ = false; bool zoom_to_page_width_ = false; absl::optional<gfx::Point> traffic_light_position_; // Trying to close an NSWindow during a fullscreen transition will cause the // window to lock up. Use this to track if CloseWindow was called during a // fullscreen transition, to defer the -[NSWindow close] call until the // transition is complete. bool has_deferred_window_close_ = false; // If true, the window is either visible, or wants to be visible but is // currently hidden due to having a hidden parent. bool wants_to_be_visible_ = false; NSInteger attention_request_id_ = 0; // identifier from requestUserAttention // The presentation options before entering kiosk mode. NSApplicationPresentationOptions kiosk_options_; // The "visualEffectState" option. VisualEffectState visual_effect_state_ = VisualEffectState::kFollowWindow; // The visibility mode of window button controls when explicitly set through // setWindowButtonVisibility(). absl::optional<bool> window_button_visibility_; // Controls the position and visibility of window buttons. WindowButtonsProxy* __strong buttons_proxy_; std::unique_ptr<SkRegion> draggable_region_; // Maximizable window state; necessary for persistence through redraws. bool maximizable_ = true; bool user_set_bounds_maximized_ = false; // Simple (pre-Lion) Fullscreen Settings bool always_simple_fullscreen_ = false; bool is_simple_fullscreen_ = false; bool was_maximizable_ = false; bool was_movable_ = false; bool is_active_ = false; NSRect original_frame_; NSInteger original_level_; NSUInteger simple_fullscreen_mask_; NSRect default_frame_for_zoom_; std::string vibrancy_type_; // The presentation options before entering simple fullscreen mode. NSApplicationPresentationOptions simple_fullscreen_options_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
closed
electron/electron
https://github.com/electron/electron
39,833
[Bug]: passing resizable windowfeature and disabling fullscreening also disables ability to maximize the window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.8.0, 26.2.0 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 25.7.0 ### Expected Behavior I expect that calling `window.open(url, name, "resizable")` and then setting `fullscreenable:false` in `setWindowOpenHandler` will disable fullscreening, but continue to allow you to maximize the window. ### Actual Behavior Maximizing is disabled (`isMaximizable()` returns `false`) ### Testcase Gist URL https://gist.github.com/pushkin-/c7651478899a6c944d28c2d7aa3232ba ### Additional Information Seems to have regressed in [this PR](https://github.com/electron/electron/pull/39620) If you don't pass the `resizable` window feature, there's no issue. Perhaps related somewhat to [this issue](https://github.com/electron/electron/issues/39832)?
https://github.com/electron/electron/issues/39833
https://github.com/electron/electron/pull/40705
22970f573b3ced41ad6b0e2c3e124e3a4ed6b40e
cc1b64e01c334dc9b27cea7c90a066645f983190
2023-09-12T15:46:17Z
c++
2024-01-05T17:15:35Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/apple/scoped_cftyperef.h" #include "base/mac/mac_util.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } bool IsPanel(NSWindow* window) { return [window isKindOfClass:[NSPanel class]]; } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); widget()->SetNativeWindowProperty(kElectronNativeWindowKey, this); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this]; [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_]; [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { // If we're a panel window, we do not want to activate the app, // which enables Electron-apps to build Spotlight-like experiences. // // On macOS < Sonoma, "activateIgnoringOtherApps:NO" would not // activate apps if focusing a window that is inActive. That // changed with macOS Sonoma, which also deprecated // "activateIgnoringOtherApps". For the panel-specific usecase, // we can simply replace "activateIgnoringOtherApps:NO" with // "activate". For details on why we cannot replace all calls 1:1, // please see // https://github.com/electron/electron/pull/40307#issuecomment-1801976591. // // There's a slim chance we should have never called // activateIgnoringOtherApps, but we tried that many years ago // and saw weird focus bugs on other macOS versions. So, to make // this safe, we're gating by versions. if (@available(macOS 14.0, *)) { if (!IsPanel(window_)) { [[NSApplication sharedApplication] activate]; } else { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; } } else { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; } [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() const { 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; } set_wants_to_be_visible(true); // 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() { set_wants_to_be_visible(true); // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // If the window wants to be visible and has a parent, then the parent may // order it back in (in the period between orderOut: and close). set_wants_to_be_visible(false); DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() const { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() const { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() const { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() const { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow() { if (parent() && !is_modal()) { parent()->RemoveChildWindow(this); NativeWindow::SetParentWindow(nullptr); } } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { if (!static_cast<NativeWindowMac*>(child)->wants_to_be_visible()) continue; auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } void NativeWindowMac::SetFullScreen(bool fullscreen) { // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; if (![window_ toggleFullScreenMode:nil]) fullscreen_transition_state_ = FullScreenTransitionState::kNone; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() const { 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() const { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() const { 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::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { // Apply the size constraints to NSWindow. if (window_constraints.HasMinimumSize()) [window_ setMinSize:window_constraints.GetMinimumSize().ToCGSize()]; if (window_constraints.HasMaximumSize()) [window_ setMaxSize:window_constraints.GetMaximumSize().ToCGSize()]; NativeWindow::SetSizeConstraints(window_constraints); } 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()); } }; // Apply the size constraints to NSWindow. NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:0]; } else { ReorderChildWindowAbove(window_, nullptr); } } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); bool was_fullscreenable = IsFullScreenable(); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreen collection behavior as well as the maximize traffic // light in SetCanResize if resizability is false on macOS unless // the window is both resizable and maximizable. We want consistent // cross-platform behavior, so if resizability is disabled we disable // the maximize button and ensure fullscreenability matches user setting. SetCanResize(resizable); SetFullScreenable(was_fullscreenable); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:resizable ? was_fullscreenable : false]; } bool NativeWindowMac::IsResizable() const { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() const { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() const { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() const { 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() const { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() const { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() const { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() const { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() const { 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() const { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() const { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() const { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::apple::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor.get()]; } SkColor NativeWindowMac::GetBackgroundColor() const { 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() const { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() const { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() const { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() const { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() const { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() const { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[NSImageView alloc] init]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[ElectronProgressBar alloc] initWithFrame:frame]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() const { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); const int macos_version = base::mac::MacOSMajorVersion(); // Modal window corners are rounded on macOS >= 11 or higher if the user // hasn't passed noRoundedCorners. bool should_round_modal = !no_rounded_corner && (macos_version >= 11 ? true : !is_modal()); // Nonmodal window corners are rounded if they're frameless and the user // hasn't passed noRoundedCorners. bool should_round_nonmodal = !no_rounded_corner && !has_frame(); if (should_round_nonmodal || should_round_modal) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (macos_version >= 11) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NativeWindow::SetVibrancy(type); NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ window:this settings:std::move(items)]; [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::ShowAllTabs() { [window_ toggleTabOverview:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } absl::optional<std::string> NativeWindowMac::GetTabbingIdentifier() const { if ([window_ tabbingMode] == NSWindowTabbingModeDisallowed) return absl::nullopt; return base::SysNSStringToUTF8([window_ tabbingIdentifier]); } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_ = [[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]; [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:NO]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:YES]; } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { CALayer* background_layer = [[CALayer alloc] init]; [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(); // Set new parent window. if (new_parent) { new_parent->add_child_window(this); if (attach) new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } absl::optional<gfx::Rect> NativeWindowMac::GetWindowControlsOverlayRect() { if (!titlebar_overlay_) return absl::nullopt; // On macOS, when in fullscreen mode, window controls (the menu bar, title // bar, and toolbar) are attached to a separate NSView that slides down from // the top of the screen, independent of, and overlapping the WebContents. // Disable WCO when in fullscreen, because this space is inaccessible to // WebContents. https://crbug.com/915110. if (IsFullscreen()) return gfx::Rect(); if (buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); overlay.set_height([buttons_proxy_ useCustomHeight] ? titlebar_overlay_height() : NSHeight(buttons)); if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return absl::nullopt; } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,833
[Bug]: passing resizable windowfeature and disabling fullscreening also disables ability to maximize the window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.8.0, 26.2.0 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 25.7.0 ### Expected Behavior I expect that calling `window.open(url, name, "resizable")` and then setting `fullscreenable:false` in `setWindowOpenHandler` will disable fullscreening, but continue to allow you to maximize the window. ### Actual Behavior Maximizing is disabled (`isMaximizable()` returns `false`) ### Testcase Gist URL https://gist.github.com/pushkin-/c7651478899a6c944d28c2d7aa3232ba ### Additional Information Seems to have regressed in [this PR](https://github.com/electron/electron/pull/39620) If you don't pass the `resizable` window feature, there's no issue. Perhaps related somewhat to [this issue](https://github.com/electron/electron/issues/39832)?
https://github.com/electron/electron/issues/39833
https://github.com/electron/electron/pull/40705
22970f573b3ced41ad6b0e2c3e124e3a4ed6b40e
cc1b64e01c334dc9b27cea7c90a066645f983190
2023-09-12T15:46:17Z
c++
2024-01-05T17:15:35Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as http from 'node:http'; import * as os from 'node:os'; import { AddressInfo } from 'node:net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; const fixtures = path.resolve(__dirname, 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { it('sets the correct class name on the prototype', () => { expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow'); }); describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. const wr = new WeakRef(w); await setTimeout(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = once(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = once(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, '-before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await once(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await once(w.webContents, '-before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); for (const win of windows) win.show(); for (const win of windows) win.focus(); for (const win of windows) win.destroy(); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w: BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server: http.Server; let url: string; let postData = null as any; before(async () => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); it('is triggered when navigating from chrome: to http:', async () => { let hasEmittedWillNavigate = false; const willNavigatePromise = new Promise((resolve) => { w.webContents.once('will-navigate', e => { e.preventDefault(); hasEmittedWillNavigate = true; resolve(e.url); }); }); await w.loadURL('chrome://gpu'); // shouldn't emit for browser-initiated request via loadURL expect(hasEmittedWillNavigate).to.equal(false); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await willNavigatePromise; expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('chrome://gpu/'); }); }); describe('will-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); describe('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); url = (await listen(server)).url; }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(url + '/navigate'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(url + '/redirect'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(url + '/in-page'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = once(w, 'maximize'); const shown = once(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await setTimeout(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); ifit(process.platform === 'darwin')('should attach child window to parent', async () => { const wShow = once(w, 'show'); w.show(); await wShow; const c = new BrowserWindow({ show: false, parent: w }); const cShow = once(c, 'show'); c.showInactive(); await cShow; // verifying by checking that the child tracks the parent's visibility const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); closeWindow(c); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); ifit(process.platform === 'darwin')('it does not activate the app if focusing an inactive panel', async () => { // Show to focus app, then remove existing window w.show(); w.destroy(); // We first need to resign app focus for this test to work const isInactive = once(app, 'did-resign-active'); childProcess.execSync('osascript -e \'tell application "Finder" to activate\''); await isInactive; // Create new window w = new BrowserWindow({ type: 'panel', height: 200, width: 200, center: true, show: false }); const isShow = once(w, 'show'); const isFocus = once(w, 'focus'); w.showInactive(); w.focus(); await isShow; await isFocus; const getActiveAppOsa = 'tell application "System Events" to get the name of the first process whose frontmost is true'; const activeApp = childProcess.execSync(`osascript -e '${getActiveAppOsa}'`).toString().trim(); expect(activeApp).to.equal('Finder'); }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { afterEach(closeAllWindows); it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); it('should not crash when called on a modal child window', async () => { const shown = once(w, 'show'); w.show(); await shown; const child = new BrowserWindow({ modal: true, parent: w }); expect(() => { child.moveTop(); }).to.not.throw(); }); }); describe('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; for (const sourceId of fakeSourceIds) { 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]; for (const sourceId of fakeSourceIds) { 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']; for (const sourceId of fakeSourceIds) { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); } }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = once(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = once(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.showAllTabs()', () => { it('does not throw', () => { expect(() => { w.showAllTabs(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); describe('BrowserWindow.tabbingIdentifier', () => { it('is undefined if no tabbingIdentifier was set', () => { const w = new BrowserWindow({ show: false }); expect(w.tabbingIdentifier).to.be.undefined('tabbingIdentifier'); }); it('returns the window tabbingIdentifier', () => { const w = new BrowserWindow({ show: false, tabbingIdentifier: 'group1' }); expect(w.tabbingIdentifier).to.equal('group1'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves when the window is occluded', async () => { const w1 = new BrowserWindow({ show: false }); w1.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w1, 'ready-to-show'); w1.show(); const w2 = new BrowserWindow({ show: false }); w2.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w2, 'ready-to-show'); w2.show(); const visibleImage = await w1.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); }); it('resolves when the window is not visible', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.minimize(); const hiddenImage = await w.capturePage(); expect(hiddenImage.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w: BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w: BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = once(w, 'always-on-top-changed') as Promise<[any, boolean]>; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect(c._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w: BrowserWindow; let server: http.Server; let url: string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); url = (await listen(server)).url; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = once(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('titlebar'); w.setVibrancy('selection'); w.setVibrancy(null); w.setVibrancy('menu'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created') as [any, WebContents]; expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); bv1.webContents.destroy(); bv2.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await once(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await once(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await once(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await once(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await once(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replaceAll('\\', '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('node:events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window') as [BrowserWindow, Electron.DidCreateWindowDetails]; const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replaceAll('\\', '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await once(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await once(app, 'browser-window-created') as [any, BrowserWindow]; // Ask the popup window for details. const detailsAnswer = once(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); const errorPattern = /Failed to read a named property 'document' from 'Window': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./; expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(errorPattern); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(errorPattern); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences!.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => once(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); expect(test.nodeEvents).to.equal(true); expect(test.nodeTimers).to.equal(true); expect(test.nodeUrl).to.equal(true); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Failed to read a named property \'toString\' from \'Location\': Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences!.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await once(w.webContents, '-before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await once(w.webContents, '-before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.close(); await once(w.webContents, '-before-unload-fired'); w.close(); await once(w.webContents, '-before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.reload(); // Chromium does not emit '-before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await once(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit '-before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); // TODO(codebytere): figure out how to make these pass in CI on Windows. ifdescribe(process.platform !== 'win32')('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); it('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); it('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = once(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = once(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('can handle child window close and reparent multiple times', async () => { const w = new BrowserWindow({ show: false }); let c: BrowserWindow | null; for (let i = 0; i < 5; i++) { c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; } await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('only shows the intended window when a child with siblings is shown', async () => { const w = new BrowserWindow({ show: false }); const childOne = new BrowserWindow({ show: false, parent: w }); const childTwo = new BrowserWindow({ show: false, parent: w }); const parentShown = once(w, 'show'); w.show(); await parentShown; expect(childOne.isVisible()).to.be.false('childOne is visible'); expect(childTwo.isVisible()).to.be.false('childTwo is visible'); const childOneShown = once(childOne, 'show'); childOne.show(); await childOneShown; expect(childOne.isVisible()).to.be.true('childOne is not visible'); expect(childTwo.isVisible()).to.be.false('childTwo is visible'); }); ifit(process.platform === 'darwin')('child matches parent visibility when parent visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); ifit(process.platform === 'darwin')('parent matches child visibility when child visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(c, 'minimize'); c.minimize(); await minimized; expect(c.isVisible()).to.be.false('child is visible'); const restored = once(c, 'restore'); c.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); it('closes a grandchild window when a middle child window is destroyed', async () => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); const closed = once(childWindow, 'closed'); window.close(); await closed; expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = once(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('can reparent when the first parent is destroyed', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); c.setParentWindow(w1); expect(w1.getChildWindows().length).to.equal(1); const closed = once(w1, 'closed'); w1.destroy(); await closed; c.setParentWindow(w2); await setTimeout(); const children = w2.getChildWindows(); expect(children[0]).to.equal(c); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); ifit(process.platform === 'win32')('do not change window with frame bounds when maximized', () => { const w = new BrowserWindow({ show: true, frame: true, thickFrame: true }); expect(w.isResizable()).to.be.true('resizable'); w.maximize(); expect(w.isMaximized()).to.be.true('maximized'); const bounds = w.getBounds(); w.setResizable(false); expectBoundsEqual(w.getBounds(), bounds); w.setResizable(true); expectBoundsEqual(w.getBounds(), bounds); }); ifit(process.platform === 'win32')('do not change window without frame bounds when maximized', () => { const w = new BrowserWindow({ show: true, frame: false, thickFrame: true }); expect(w.isResizable()).to.be.true('resizable'); w.maximize(); expect(w.isMaximized()).to.be.true('maximized'); const bounds = w.getBounds(); w.setResizable(false); expectBoundsEqual(w.getBounds(), bounds); w.setResizable(true); expectBoundsEqual(w.getBounds(), bounds); }); ifit(process.platform === 'win32')('do not change window transparent without frame bounds when maximized', () => { const w = new BrowserWindow({ show: true, frame: false, thickFrame: true, transparent: true }); expect(w.isResizable()).to.be.true('resizable'); w.maximize(); expect(w.isMaximized()).to.be.true('maximized'); const bounds = w.getBounds(); w.setResizable(false); expectBoundsEqual(w.getBounds(), bounds); w.setResizable(true); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('loading main frame state', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform !== 'darwin')('when fullscreen state is changed', () => { it('correctly remembers state prior to fullscreen change', async () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); it('correctly remembers state prior to fullscreen change with autoHide', async () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); it('does not open non-fullscreenable child windows in fullscreen if parent is fullscreen', async () => { const w = new BrowserWindow(); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const child = new BrowserWindow({ parent: w, resizable: false, fullscreenable: false }); const shown = once(child, 'show'); await shown; expect(child.resizable).to.be.false('resizable'); expect(child.fullScreen).to.be.false('fullscreen'); expect(child.fullScreenable).to.be.false('fullscreenable'); }); it('is set correctly with different resizable values', async () => { const w1 = new BrowserWindow({ resizable: false, fullscreenable: false }); const w2 = new BrowserWindow({ resizable: true, fullscreenable: false }); const w3 = new BrowserWindow({ fullscreenable: false }); expect(w1.isFullScreenable()).to.be.false('isFullScreenable'); expect(w2.isFullScreenable()).to.be.false('isFullScreenable'); expect(w3.isFullScreenable()).to.be.false('isFullScreenable'); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); const isValidWindow = require('@electron-ci/is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences()!.contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = once(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = once(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); describe('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(1000); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(1000); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); await setTimeout(1000); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
40,799
[Bug]: Broken Vibrancy
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.1.3 ### What operating system are you using? macOS ### Operating System Version macOS sonoma 14.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 26.6.2 ### Expected Behavior Working vibrancy ### Actual Behavior Vibrancy doesn't work ### Testcase Gist URL https://gist.github.com/RoyalFoxy/75bbfcae5cc404201bf64e2f9a597f46 ### Additional Information Note that this issue was introduced with 27.0.0, I just chose 27.1.3 as that's the current vscode electron version. This issue persists on all versions above 27.0.0 including 28.x.x and the alpha builds for version 29
https://github.com/electron/electron/issues/40799
https://github.com/electron/electron/pull/40893
73e7125041339bf0fc319242a00fdb75d4554895
3a22fd32164e02864395a46dc777ce32333c6de4
2023-12-20T19:48:55Z
c++
2024-01-07T21:56:52Z
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 (30.0) ### Behavior Changed: cross-origin iframes now use Permission Policy to access features Cross-origin iframes must now specify features available to a given `iframe` via the `allow` attribute in order to access them. See [documentation](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#allow) for more information. ## Planned Breaking API Changes (29.0) ### Behavior Changed: `ipcRenderer` can no longer be sent over the `contextBridge` Attempting to send `ipcRenderer` as an object over the `contextBridge` will now result in an empty object on the receiving side of the bridge. This change was made to remove / mitigate a security footgun, you should not directly expose ipcRenderer or it's methods over the bridge. Instead provide a safe wrapper like below: ```js contextBridge.exposeInMainWorld('app', { onEvent: (cb) => ipcRenderer.on('foo', (e, ...args) => cb(args)) }) ``` ### Removed: `renderer-process-crashed` event on `app` The `renderer-process-crashed` event on `app` has been removed. Use the new `render-process-gone` event instead. ```js // Removed app.on('renderer-process-crashed', (event, webContents, killed) => { /* ... */ }) // Replace with app.on('render-process-gone', (event, webContents, details) => { /* ... */ }) ``` ### Removed: `crashed` event on `WebContents` and `<webview>` The `crashed` events on `WebContents` and `<webview>` have been removed. Use the new `render-process-gone` event instead. ```js // Removed win.webContents.on('crashed', (event, killed) => { /* ... */ }) webview.addEventListener('crashed', (event) => { /* ... */ }) // Replace with win.webContents.on('render-process-gone', (event, details) => { /* ... */ }) webview.addEventListener('render-process-gone', (event) => { /* ... */ }) ``` ### Removed: `gpu-process-crashed` event on `app` The `gpu-process-crashed` event on `app` has been removed. Use the new `child-process-gone` event instead. ```js // Removed app.on('gpu-process-crashed', (event, killed) => { /* ... */ }) // Replace with app.on('child-process-gone', (event, details) => { /* ... */ }) ``` ### Behavior Changed: `BrowserView.setAutoResize` behavior on macOS In Electron 29, BrowserView is now a wrapper around the new [WebContentsView](api/web-contents-view.md) API. Previously, the `setAutoResize` function of the `BrowserView` API was backed by [autoresizing](https://developer.apple.com/documentation/appkit/nsview/1483281-autoresizingmask?language=objc) on macOS, and by a custom algorithm on Windows and Linux. For simple use cases such as making a BrowserView fill the entire window, the behavior of these two approaches was identical. However, in more advanced cases, BrowserViews would be autoresized differently on macOS than they would be on other platforms, as the custom resizing algorithm for Windows and Linux did not perfectly match the behavior of macOS's autoresizing API. The autoresizing behavior is now standardized across all platforms. If your app uses `BrowserView.setAutoResize` to do anything more complex than making a BrowserView fill the entire window, it's likely you already had custom logic in place to handle this difference in behavior on macOS. If so, that logic will no longer be needed in Electron 29 as autoresizing behavior is consistent. ## Planned Breaking API Changes (28.0) ### Behavior Changed: `WebContents.backgroundThrottling` set to false affects all `WebContents` in the host `BrowserWindow` `WebContents.backgroundThrottling` set to false will disable frames throttling in the `BrowserWindow` for all `WebContents` displayed by it. ### Removed: `BrowserWindow.setTrafficLightPosition(position)` `BrowserWindow.setTrafficLightPosition(position)` has been removed, the `BrowserWindow.setWindowButtonPosition(position)` API should be used instead which accepts `null` instead of `{ x: 0, y: 0 }` to reset the position to system default. ```js // Removed in Electron 28 win.setTrafficLightPosition({ x: 10, y: 10 }) win.setTrafficLightPosition({ x: 0, y: 0 }) // Replace with win.setWindowButtonPosition({ x: 10, y: 10 }) win.setWindowButtonPosition(null) ``` ### Removed: `BrowserWindow.getTrafficLightPosition()` `BrowserWindow.getTrafficLightPosition()` has been removed, the `BrowserWindow.getWindowButtonPosition()` API should be used instead which returns `null` instead of `{ x: 0, y: 0 }` when there is no custom position. ```js // Removed in Electron 28 const pos = win.getTrafficLightPosition() if (pos.x === 0 && pos.y === 0) { // No custom position. } // Replace with const ret = win.getWindowButtonPosition() if (ret === null) { // No custom position. } ``` ### Removed: `ipcRenderer.sendTo()` The `ipcRenderer.sendTo()` API has been removed. It should be replaced by setting up a [`MessageChannel`](tutorial/message-ports.md#setting-up-a-messagechannel-between-two-renderers) between the renderers. The `senderId` and `senderIsMainFrame` properties of `IpcRendererEvent` have been removed as well. ### Removed: `app.runningUnderRosettaTranslation` The `app.runningUnderRosettaTranslation` property has been removed. Use `app.runningUnderARM64Translation` instead. ```js // Removed console.log(app.runningUnderRosettaTranslation) // Replace with console.log(app.runningUnderARM64Translation) ``` ### Deprecated: `renderer-process-crashed` event on `app` The `renderer-process-crashed` event on `app` has been deprecated. Use the new `render-process-gone` event instead. ```js // Deprecated app.on('renderer-process-crashed', (event, webContents, killed) => { /* ... */ }) // Replace with app.on('render-process-gone', (event, webContents, details) => { /* ... */ }) ``` ### Deprecated: `params.inputFormType` property on `context-menu` on `WebContents` The `inputFormType` property of the params object in the `context-menu` event from `WebContents` has been deprecated. Use the new `formControlType` property instead. ### Deprecated: `crashed` event on `WebContents` and `<webview>` The `crashed` events on `WebContents` and `<webview>` have been deprecated. Use the new `render-process-gone` event instead. ```js // Deprecated win.webContents.on('crashed', (event, killed) => { /* ... */ }) webview.addEventListener('crashed', (event) => { /* ... */ }) // Replace with win.webContents.on('render-process-gone', (event, details) => { /* ... */ }) webview.addEventListener('render-process-gone', (event) => { /* ... */ }) ``` ### Deprecated: `gpu-process-crashed` event on `app` The `gpu-process-crashed` event on `app` has been deprecated. Use the new `child-process-gone` event instead. ```js // Deprecated app.on('gpu-process-crashed', (event, killed) => { /* ... */ }) // Replace with app.on('child-process-gone', (event, details) => { /* ... */ }) ``` ## Planned Breaking API Changes (27.0) ### Removed: macOS 10.13 / 10.14 support macOS 10.13 (High Sierra) and macOS 10.14 (Mojave) are no longer supported by [Chromium](https://chromium-review.googlesource.com/c/chromium/src/+/4629466). Older versions of Electron will continue to run on these operating systems, but macOS 10.15 (Catalina) or later will be required to run Electron v27.0.0 and higher. ### Deprecated: `ipcRenderer.sendTo()` The `ipcRenderer.sendTo()` API has been deprecated. It should be replaced by setting up a [`MessageChannel`](tutorial/message-ports.md#setting-up-a-messagechannel-between-two-renderers) between the renderers. The `senderId` and `senderIsMainFrame` properties of `IpcRendererEvent` have been deprecated as well. ### Removed: color scheme events in `systemPreferences` The following `systemPreferences` events have been removed: * `inverted-color-scheme-changed` * `high-contrast-color-scheme-changed` Use the new `updated` event on the `nativeTheme` module instead. ```js // Removed systemPreferences.on('inverted-color-scheme-changed', () => { /* ... */ }) systemPreferences.on('high-contrast-color-scheme-changed', () => { /* ... */ }) // Replace with nativeTheme.on('updated', () => { /* ... */ }) ``` ### Removed: `webContents.getPrinters` The `webContents.getPrinters` method has been removed. Use `webContents.getPrintersAsync` instead. ```js const w = new BrowserWindow({ show: false }) // Removed console.log(w.webContents.getPrinters()) // Replace with w.webContents.getPrintersAsync().then((printers) => { console.log(printers) }) ``` ### Removed: `systemPreferences.{get,set}AppLevelAppearance` and `systemPreferences.appLevelAppearance` The `systemPreferences.getAppLevelAppearance` and `systemPreferences.setAppLevelAppearance` methods have been removed, as well as the `systemPreferences.appLevelAppearance` property. Use the `nativeTheme` module instead. ```js // Removed systemPreferences.getAppLevelAppearance() // Replace with nativeTheme.shouldUseDarkColors // Removed systemPreferences.appLevelAppearance // Replace with nativeTheme.shouldUseDarkColors // Removed systemPreferences.setAppLevelAppearance('dark') // Replace with nativeTheme.themeSource = 'dark' ``` ### Removed: `alternate-selected-control-text` value for `systemPreferences.getColor` The `alternate-selected-control-text` value for `systemPreferences.getColor` has been removed. Use `selected-content-background` instead. ```js // Removed systemPreferences.getColor('alternate-selected-control-text') // Replace with systemPreferences.getColor('selected-content-background') ``` ## Planned Breaking API Changes (26.0) ### Deprecated: `webContents.getPrinters` The `webContents.getPrinters` method has been deprecated. Use `webContents.getPrintersAsync` instead. ```js const w = new BrowserWindow({ show: false }) // Deprecated console.log(w.webContents.getPrinters()) // Replace with w.webContents.getPrintersAsync().then((printers) => { console.log(printers) }) ``` ### Deprecated: `systemPreferences.{get,set}AppLevelAppearance` and `systemPreferences.appLevelAppearance` The `systemPreferences.getAppLevelAppearance` and `systemPreferences.setAppLevelAppearance` methods have been deprecated, as well as the `systemPreferences.appLevelAppearance` property. Use the `nativeTheme` module instead. ```js // Deprecated systemPreferences.getAppLevelAppearance() // Replace with nativeTheme.shouldUseDarkColors // Deprecated systemPreferences.appLevelAppearance // Replace with nativeTheme.shouldUseDarkColors // Deprecated systemPreferences.setAppLevelAppearance('dark') // Replace with nativeTheme.themeSource = 'dark' ``` ### Deprecated: `alternate-selected-control-text` value for `systemPreferences.getColor` The `alternate-selected-control-text` value for `systemPreferences.getColor` has been deprecated. Use `selected-content-background` instead. ```js // Deprecated systemPreferences.getColor('alternate-selected-control-text') // Replace with systemPreferences.getColor('selected-content-background') ``` ## Planned Breaking API Changes (25.0) ### Deprecated: `protocol.{register,intercept}{Buffer,String,Stream,File,Http}Protocol` The `protocol.register*Protocol` and `protocol.intercept*Protocol` methods have been replaced with [`protocol.handle`](api/protocol.md#protocolhandlescheme-handler). The new method can either register a new protocol or intercept an existing protocol, and responses can be of any type. ```js // Deprecated in Electron 25 protocol.registerBufferProtocol('some-protocol', () => { callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') }) }) // Replace with protocol.handle('some-protocol', () => { return new Response( Buffer.from('<h5>Response</h5>'), // Could also be a string or ReadableStream. { headers: { 'content-type': 'text/html' } } ) }) ``` ```js // Deprecated in Electron 25 protocol.registerHttpProtocol('some-protocol', () => { callback({ url: 'https://electronjs.org' }) }) // Replace with protocol.handle('some-protocol', () => { return net.fetch('https://electronjs.org') }) ``` ```js // Deprecated in Electron 25 protocol.registerFileProtocol('some-protocol', () => { callback({ filePath: '/path/to/my/file' }) }) // Replace with protocol.handle('some-protocol', () => { return net.fetch('file:///path/to/my/file') }) ``` ### Deprecated: `BrowserWindow.setTrafficLightPosition(position)` `BrowserWindow.setTrafficLightPosition(position)` has been deprecated, the `BrowserWindow.setWindowButtonPosition(position)` API should be used instead which accepts `null` instead of `{ x: 0, y: 0 }` to reset the position to system default. ```js // Deprecated in Electron 25 win.setTrafficLightPosition({ x: 10, y: 10 }) win.setTrafficLightPosition({ x: 0, y: 0 }) // Replace with win.setWindowButtonPosition({ x: 10, y: 10 }) win.setWindowButtonPosition(null) ``` ### Deprecated: `BrowserWindow.getTrafficLightPosition()` `BrowserWindow.getTrafficLightPosition()` has been deprecated, the `BrowserWindow.getWindowButtonPosition()` API should be used instead which returns `null` instead of `{ x: 0, y: 0 }` when there is no custom position. ```js // Deprecated in Electron 25 const pos = win.getTrafficLightPosition() if (pos.x === 0 && pos.y === 0) { // No custom position. } // Replace with const ret = win.getWindowButtonPosition() if (ret === null) { // No custom position. } ``` ## Planned Breaking API Changes (24.0) ### API Changed: `nativeImage.createThumbnailFromPath(path, size)` The `maxSize` parameter has been changed to `size` to reflect that the size passed in will be the size the thumbnail created. Previously, Windows would not scale the image up if it were smaller than `maxSize`, and macOS would always set the size to `maxSize`. Behavior is now the same across platforms. Updated Behavior: ```js // a 128x128 image. const imagePath = path.join('path', 'to', 'capybara.png') // Scaling up a smaller image. const upSize = { width: 256, height: 256 } nativeImage.createThumbnailFromPath(imagePath, upSize).then(result => { console.log(result.getSize()) // { width: 256, height: 256 } }) // Scaling down a larger image. const downSize = { width: 64, height: 64 } nativeImage.createThumbnailFromPath(imagePath, downSize).then(result => { console.log(result.getSize()) // { width: 64, height: 64 } }) ``` Previous Behavior (on Windows): ```js // a 128x128 image const imagePath = path.join('path', 'to', 'capybara.png') const size = { width: 256, height: 256 } nativeImage.createThumbnailFromPath(imagePath, size).then(result => { console.log(result.getSize()) // { width: 128, height: 128 } }) ``` ## Planned Breaking API Changes (23.0) ### Behavior Changed: Draggable Regions on macOS The implementation of draggable regions (using the CSS property `-webkit-app-region: drag`) has changed on macOS to bring it in line with Windows and Linux. Previously, when a region with `-webkit-app-region: no-drag` overlapped a region with `-webkit-app-region: drag`, the `no-drag` region would always take precedence on macOS, regardless of CSS layering. That is, if a `drag` region was above a `no-drag` region, it would be ignored. Beginning in Electron 23, a `drag` region on top of a `no-drag` region will correctly cause the region to be draggable. Additionally, the `customButtonsOnHover` BrowserWindow property previously created a draggable region which ignored the `-webkit-app-region` CSS property. This has now been fixed (see [#37210](https://github.com/electron/electron/issues/37210#issuecomment-1440509592) for discussion). As a result, if your app uses a frameless window with draggable regions on macOS, the regions which are draggable in your app may change in Electron 23. ### Removed: Windows 7 / 8 / 8.1 support [Windows 7, Windows 8, and Windows 8.1 are no longer supported](https://www.electronjs.org/blog/windows-7-to-8-1-deprecation-notice). Electron follows the planned Chromium deprecation policy, which will [deprecate Windows 7 support beginning in Chromium 109](https://support.google.com/chrome/thread/185534985/sunsetting-support-for-windows-7-8-8-1-in-early-2023?hl=en). Older versions of Electron will continue to run on these operating systems, but Windows 10 or later will be required to run Electron v23.0.0 and higher. ### Removed: BrowserWindow `scroll-touch-*` events The deprecated `scroll-touch-begin`, `scroll-touch-end` and `scroll-touch-edge` events on BrowserWindow have been removed. Instead, use the newly available [`input-event` event](api/web-contents.md#event-input-event) on WebContents. ```js // Removed in Electron 23.0 win.on('scroll-touch-begin', scrollTouchBegin) win.on('scroll-touch-edge', scrollTouchEdge) win.on('scroll-touch-end', scrollTouchEnd) // Replace with win.webContents.on('input-event', (_, event) => { if (event.type === 'gestureScrollBegin') { scrollTouchBegin() } else if (event.type === 'gestureScrollUpdate') { scrollTouchEdge() } else if (event.type === 'gestureScrollEnd') { scrollTouchEnd() } }) ``` ### Removed: `webContents.incrementCapturerCount(stayHidden, stayAwake)` The `webContents.incrementCapturerCount(stayHidden, stayAwake)` function has been removed. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ### Removed: `webContents.decrementCapturerCount(stayHidden, stayAwake)` The `webContents.decrementCapturerCount(stayHidden, stayAwake)` function has been removed. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ## Planned Breaking API Changes (22.0) ### Deprecated: `webContents.incrementCapturerCount(stayHidden, stayAwake)` `webContents.incrementCapturerCount(stayHidden, stayAwake)` has been deprecated. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ### Deprecated: `webContents.decrementCapturerCount(stayHidden, stayAwake)` `webContents.decrementCapturerCount(stayHidden, stayAwake)` has been deprecated. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ### Removed: WebContents `new-window` event The `new-window` event of WebContents has been removed. It is replaced by [`webContents.setWindowOpenHandler()`](api/web-contents.md#contentssetwindowopenhandlerhandler). ```js // Removed in Electron 22 webContents.on('new-window', (event) => { event.preventDefault() }) // Replace with webContents.setWindowOpenHandler((details) => { return { action: 'deny' } }) ``` ### Removed: `<webview>` `new-window` event The `new-window` event of `<webview>` has been removed. There is no direct replacement. ```js // Removed in Electron 22 webview.addEventListener('new-window', (event) => {}) ``` ```js // Replace with // main.js mainWindow.webContents.on('did-attach-webview', (event, wc) => { wc.setWindowOpenHandler((details) => { mainWindow.webContents.send('webview-new-window', wc.id, details) return { action: 'deny' } }) }) // preload.js const { ipcRenderer } = require('electron') ipcRenderer.on('webview-new-window', (e, webContentsId, details) => { console.log('webview-new-window', webContentsId, details) document.getElementById('webview').dispatchEvent(new Event('new-window')) }) // renderer.js document.getElementById('webview').addEventListener('new-window', () => { console.log('got new-window event') }) ``` ### Deprecated: BrowserWindow `scroll-touch-*` events The `scroll-touch-begin`, `scroll-touch-end` and `scroll-touch-edge` events on BrowserWindow are deprecated. Instead, use the newly available [`input-event` event](api/web-contents.md#event-input-event) on WebContents. ```js // Deprecated win.on('scroll-touch-begin', scrollTouchBegin) win.on('scroll-touch-edge', scrollTouchEdge) win.on('scroll-touch-end', scrollTouchEnd) // Replace with win.webContents.on('input-event', (_, event) => { if (event.type === 'gestureScrollBegin') { scrollTouchBegin() } else if (event.type === 'gestureScrollUpdate') { scrollTouchEdge() } else if (event.type === 'gestureScrollEnd') { scrollTouchEnd() } }) ``` ## Planned Breaking API Changes (21.0) ### Behavior Changed: V8 Memory Cage enabled The V8 memory cage has been enabled, which has implications for native modules which wrap non-V8 memory with `ArrayBuffer` or `Buffer`. See the [blog post about the V8 memory cage](https://www.electronjs.org/blog/v8-memory-cage) for more details. ### API Changed: `webContents.printToPDF()` `webContents.printToPDF()` has been modified to conform to [`Page.printToPDF`](https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF) in the Chrome DevTools Protocol. This has been changes in order to address changes upstream that made our previous implementation untenable and rife with bugs. **Arguments Changed** * `pageRanges` **Arguments Removed** * `printSelectionOnly` * `marginsType` * `headerFooter` * `scaleFactor` **Arguments Added** * `headerTemplate` * `footerTemplate` * `displayHeaderFooter` * `margins` * `scale` * `preferCSSPageSize` ```js // Main process const { webContents } = require('electron') webContents.printToPDF({ landscape: true, displayHeaderFooter: true, printBackground: true, scale: 2, pageSize: 'Ledger', margins: { top: 2, bottom: 2, left: 2, right: 2 }, pageRanges: '1-5, 8, 11-13', headerTemplate: '<h1>Title</h1>', footerTemplate: '<div><span class="pageNumber"></span></div>', preferCSSPageSize: true }).then(data => { fs.writeFile(pdfPath, data, (error) => { if (error) throw error console.log(`Wrote PDF successfully to ${pdfPath}`) }) }).catch(error => { console.log(`Failed to write PDF to ${pdfPath}: `, error) }) ``` ## Planned Breaking API Changes (20.0) ### Removed: macOS 10.11 / 10.12 support macOS 10.11 (El Capitan) and macOS 10.12 (Sierra) are no longer supported by [Chromium](https://chromium-review.googlesource.com/c/chromium/src/+/3646050). Older versions of Electron will continue to run on these operating systems, but macOS 10.13 (High Sierra) or later will be required to run Electron v20.0.0 and higher. ### 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. ### API Changed: `session.setDevicePermissionHandler(handler)` The handler invoked when `session.setDevicePermissionHandler(handler)` is used has a change to its arguments. This handler no longer is passed a frame [`WebFrameMain`](api/web-frame-main.md), but instead is passed the `origin`, which is the origin that is checking for device permission. ## Planned Breaking API Changes (19.0) ### Removed: IA32 Linux binaries This is a result of Chromium 102.0.4999.0 dropping support for IA32 Linux. This concludes the [removal of support for IA32 Linux](#removed-ia32-linux-support). ## 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. ### Deprecated: `app.runningUnderRosettaTranslation` The `app.runningUnderRosettaTranslation` property has been deprecated. Use `app.runningUnderARM64Translation` instead. ```js // Deprecated console.log(app.runningUnderRosettaTranslation) // Replace with console.log(app.runningUnderARM64Translation) ``` ## 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 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. ```js // 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. ```js // 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. ```js // 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](./tutorial/using-native-node-modules.md) for more. ### Removed: IA32 Linux support Electron 18 will no longer run on 32-bit Linux systems. See [discontinuing support for 32-bit Linux](https://www.electronjs.org/blog/linux-32bit-support) for more information. ## 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
40,694
[Bug]: crashed when powerMonitor listens on suspend/resume event in main process at 27.1.x
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 26.6.2, 27.1.2, 27.1.3, 28.0.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04.6 ### What arch are you using? x64 ### Last Known Working Electron version 24.8.8, 25.9.7 ### Expected Behavior Not crashed ### Actual Behavior Crashed immediately when app is starting ``` #0 0x000055b563e9e533 in base::ImmediateCrash () at ../../base/immediate_crash.h:146 #1 logging::CheckFailure () at ../../base/check.h:192 #2 bluez::BluezDBusThreadManager::Get () at ../../device/bluetooth/dbus/bluez_dbus_thread_manager.cc:71 #3 0x000055b55f455b28 in electron::PowerObserverLinux::PowerObserverLinux (this=0x37ac02a71578, suspend_observer=<optimized out>) at ../../electron/shell/browser/lib/power_observer_linux.cc:37 #4 0x000055b55f2fe55f in electron::api::PowerMonitor::PowerMonitor (this=0x37ac02a71540, isolate=0x37ac0022c000) at ../../electron/shell/browser/api/electron_api_power_monitor.h:88 #5 electron::api::PowerMonitor::Create (isolate=0x37ac0022c000) at ../../electron/shell/browser/api/electron_api_power_monitor.cc:135 #6 0x000055b55f2a7819 in base::RepeatingCallback<v8::Local<v8::Value> (v8::Isolate*)>::Run(v8::Isolate*) const & (this=0x7ffdd8bcd0d8, args=0x4) at ../../base/functional/callback.h:333 #7 gin_helper::Invoker<gin_helper::IndicesHolder<0ul>, v8::Isolate*>::DispatchToCallback<v8::Local<v8::Value> >(base::RepeatingCallback<v8::Local<v8::Value> (v8::Isolate*)>) ( this=0x7ffdd8bcd150, callback=...) at ../../electron/shell/common/gin_helper/function_template.h:225 #8 0x000055b55f2a775a in gin_helper::Dispatcher<v8::Local<v8::Value> (v8::Isolate*)>::DispatchToCallback(v8::FunctionCallbackInfo<v8::Value> const&) (info=...) at ../../electron/shell/common/gin_helper/function_template.h:269 ``` ### Testcase Gist URL _No response_ ### Additional Information ``` js // Modules to control application life and create native browser window const { app, BrowserWindow, powerMonitor } = require('electron') const path = require('node:path') function createWindow () { // Create the browser window. const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js') } }) // and load the index.html of the app. mainWindow.loadFile('index.html') // Open the DevTools. // mainWindow.webContents.openDevTools() } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.whenReady().then(() => { createWindow() app.on('activate', function () { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) // Quit when all windows are closed, except on macOS. There, it's common // for applications and their menu bar to stay active until the user quits // explicitly with Cmd + Q. app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here. powerMonitor.on('suspend', () => { console.log('suspend') }); powerMonitor.on('resume', () => { console.log('resume') }); ```
https://github.com/electron/electron/issues/40694
https://github.com/electron/electron/pull/40888
7b4d490bfed9bf1b14b160132ae45c03eb946496
c184b93fc52f578b559511ec059bab4098d1404c
2023-12-05T04:44:15Z
c++
2024-01-09T08:41:42Z
shell/browser/electron_browser_main_parts.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_main_parts.h" #include <memory> #include <string> #include <utility> #include <vector> #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/i18n/rtl.h" #include "base/metrics/field_trial.h" #include "base/nix/xdg_util.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "chrome/browser/icon_manager.h" #include "chrome/browser/ui/color/chrome_color_mixers.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/os_crypt/sync/key_storage_config_linux.h" #include "components/os_crypt/sync/key_storage_util_linux.h" #include "components/os_crypt/sync/os_crypt.h" #include "content/browser/browser_main_loop.h" // nogncheck #include "content/public/browser/browser_child_process_host_delegate.h" #include "content/public/browser/browser_child_process_host_iterator.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_data.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/device_service.h" #include "content/public/browser/first_party_sets_handler.h" #include "content/public/browser/web_ui_controller_factory.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/process_type.h" #include "content/public/common/result_codes.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "media/base/localized_strings.h" #include "services/network/public/cpp/features.h" #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "shell/app/electron_main_delegate.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/api/electron_api_utility_process.h" #include "shell/browser/browser.h" #include "shell/browser/browser_process_impl.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_web_ui_controller_factory.h" #include "shell/browser/feature_list.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_helper/trackable_object.h" #include "shell/common/logging.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/idle/idle.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_switches.h" #include "ui/color/color_provider_manager.h" #if defined(USE_AURA) #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #include "ui/wm/core/wm_state.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/environment.h" #include "chrome/browser/ui/views/dark_mode_manager_linux.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h" #include "electron/electron_gtk_stubs.h" #include "ui/base/cursor/cursor_factory.h" #include "ui/base/ime/linux/linux_input_method_context_factory.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/linux_ui_factory.h" #include "ui/linux/linux_ui_getter.h" #include "ui/ozone/public/ozone_platform.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/l10n/l10n_util_win.h" #include "ui/gfx/system_fonts_win.h" #include "ui/strings/grit/app_locale_settings.h" #endif #if BUILDFLAG(IS_MAC) #include "components/os_crypt/sync/keychain_password_mac.h" #include "shell/browser/ui/cocoa/views_delegate_mac.h" #else #include "shell/browser/ui/views/electron_views_delegate.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #include "shell/common/plugin_info.h" #endif // BUILDFLAG(ENABLE_PLUGINS) namespace electron { namespace { #if BUILDFLAG(IS_LINUX) class LinuxUiGetterImpl : public ui::LinuxUiGetter { public: LinuxUiGetterImpl() = default; ~LinuxUiGetterImpl() override = default; ui::LinuxUiTheme* GetForWindow(aura::Window* window) override { return GetForProfile(nullptr); } ui::LinuxUiTheme* GetForProfile(Profile* profile) override { return ui::GetLinuxUiTheme(ui::SystemTheme::kGtk); } }; #endif template <typename T> void Erase(T* container, typename T::iterator iter) { container->erase(iter); } #if BUILDFLAG(IS_WIN) int GetMinimumFontSize() { int min_font_size; base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE), &min_font_size); return min_font_size; } #endif std::u16string MediaStringProvider(media::MessageId id) { switch (id) { case media::DEFAULT_AUDIO_DEVICE_NAME: return u"Default"; #if BUILDFLAG(IS_WIN) case media::COMMUNICATIONS_AUDIO_DEVICE_NAME: return u"Communications"; #endif default: return std::u16string(); } } } // namespace // static ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr; ElectronBrowserMainParts::ElectronBrowserMainParts() : fake_browser_process_(std::make_unique<BrowserProcessImpl>()), node_bindings_{ NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)}, electron_bindings_{ std::make_unique<ElectronBindings>(node_bindings_->uv_loop())}, browser_{std::make_unique<Browser>()} { DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts"; self_ = this; } ElectronBrowserMainParts::~ElectronBrowserMainParts() = default; // static ElectronBrowserMainParts* ElectronBrowserMainParts::Get() { DCHECK(self_); return self_; } bool ElectronBrowserMainParts::SetExitCode(int code) { if (!exit_code_) return false; content::BrowserMainLoop::GetInstance()->SetResultCode(code); *exit_code_ = code; return true; } int ElectronBrowserMainParts::GetExitCode() const { return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT); } int ElectronBrowserMainParts::PreEarlyInitialization() { field_trial_list_ = std::make_unique<base::FieldTrialList>(); #if BUILDFLAG(IS_POSIX) HandleSIGCHLD(); #endif #if BUILDFLAG(IS_LINUX) DetectOzonePlatform(); ui::OzonePlatform::PreEarlyInitialization(); #endif #if BUILDFLAG(IS_MAC) screen_ = std::make_unique<display::ScopedNativeScreen>(); #endif ui::ColorProviderManager::Get().AppendColorProviderInitializer( base::BindRepeating(AddChromeColorMixers)); return GetExitCode(); } void ElectronBrowserMainParts::PostEarlyInitialization() { // A workaround was previously needed because there was no ThreadTaskRunner // set. If this check is failing we may need to re-add that workaround DCHECK(base::SingleThreadTaskRunner::HasCurrentDefault()); // The ProxyResolverV8 has setup a complete V8 environment, in order to // avoid conflicts we only initialize our V8 environment after that. js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop()); v8::HandleScope scope(js_env_->isolate()); node_bindings_->Initialize(js_env_->isolate()->GetCurrentContext()); // Create the global environment. node_env_ = node_bindings_->CreateEnvironment( js_env_->isolate()->GetCurrentContext(), js_env_->platform()); node_env_->set_trace_sync_io(node_env_->options()->trace_sync_io); // We do not want to crash the main process on unhandled rejections. node_env_->options()->unhandled_rejections = "warn-with-error-code"; // Add Electron extended APIs. electron_bindings_->BindTo(js_env_->isolate(), node_env_->process_object()); // Create explicit microtasks runner. js_env_->CreateMicrotasksRunner(); // Wrap the uv loop with global env. node_bindings_->set_uv_env(node_env_.get()); // Load everything. node_bindings_->LoadEnvironment(node_env_.get()); // Wait for app node_bindings_->JoinAppCode(); // We already initialized the feature list in PreEarlyInitialization(), but // the user JS script would not have had a chance to alter the command-line // switches at that point. Lets reinitialize it here to pick up the // command-line changes. base::FeatureList::ClearInstanceForTesting(); InitializeFeatureList(); // Initialize field trials. InitializeFieldTrials(); // Reinitialize logging now that the app has had a chance to set the app name // and/or user data directory. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(), /* is_preinit = */ false); // Initialize after user script environment creation. fake_browser_process_->PostEarlyInitialization(); } int ElectronBrowserMainParts::PreCreateThreads() { if (!views::LayoutProvider::Get()) { layout_provider_ = std::make_unique<views::LayoutProvider>(); } // Fetch the system locale for Electron. #if BUILDFLAG(IS_MAC) fake_browser_process_->SetSystemLocale(GetCurrentSystemLocale()); #else fake_browser_process_->SetSystemLocale(base::i18n::GetConfiguredLocale()); #endif auto* command_line = base::CommandLine::ForCurrentProcess(); std::string locale = command_line->GetSwitchValueASCII(::switches::kLang); #if BUILDFLAG(IS_MAC) // The browser process only wants to support the language Cocoa will use, // so force the app locale to be overridden with that value. This must // happen before the ResourceBundle is loaded if (locale.empty()) l10n_util::OverrideLocaleWithCocoaLocale(); #elif BUILDFLAG(IS_LINUX) // l10n_util::GetApplicationLocaleInternal uses g_get_language_names(), // which keys off of getenv("LC_ALL"). // We must set this env first to make ui::ResourceBundle accept the custom // locale. auto env = base::Environment::Create(); absl::optional<std::string> lc_all; if (!locale.empty()) { std::string str; if (env->GetVar("LC_ALL", &str)) lc_all.emplace(std::move(str)); env->SetVar("LC_ALL", locale.c_str()); } #endif // Load resources bundle according to locale. std::string loaded_locale = LoadResourceBundle(locale); #if defined(USE_AURA) // NB: must be called _after_ locale resource bundle is loaded, // because ui lib makes use of it in X11 if (!display::Screen::GetScreen()) { screen_ = views::CreateDesktopScreen(); } #endif // Initialize the app locale for Electron and Chromium. std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale); ElectronBrowserClient::SetApplicationLocale(app_locale); fake_browser_process_->SetApplicationLocale(app_locale); #if BUILDFLAG(IS_LINUX) // Reset to the original LC_ALL since we should not be changing it. if (!locale.empty()) { if (lc_all) env->SetVar("LC_ALL", *lc_all); else env->UnSetVar("LC_ALL"); } #endif // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); #if BUILDFLAG(IS_MAC) ui::InitIdleMonitor(); Browser::Get()->ApplyForcedRTL(); #endif fake_browser_process_->PreCreateThreads(); // Notify observers. Browser::Get()->PreCreateThreads(); return 0; } void ElectronBrowserMainParts::PostCreateThreads() { content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread)); #if BUILDFLAG(ENABLE_PLUGINS) // PluginService can only be used on the UI thread // and ContentClient::AddPlugins gets called for both browser and render // process where the latter will not have UI thread which leads to DCHECK. // Separate the WebPluginInfo registration for these processes. std::vector<content::WebPluginInfo> plugins; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->RefreshPlugins(); GetInternalPlugins(&plugins); for (const auto& plugin : plugins) plugin_service->RegisterInternalPlugin(plugin, true); #endif } void ElectronBrowserMainParts::PostDestroyThreads() { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_browser_client_.reset(); extensions::ExtensionsBrowserClient::Set(nullptr); #endif #if BUILDFLAG(IS_LINUX) device::BluetoothAdapterFactory::Shutdown(); bluez::DBusBluezManagerWrapperLinux::Shutdown(); #endif fake_browser_process_->PostDestroyThreads(); } void ElectronBrowserMainParts::ToolkitInitialized() { #if BUILDFLAG(IS_LINUX) auto* linux_ui = ui::GetDefaultLinuxUi(); CHECK(linux_ui); linux_ui_getter_ = std::make_unique<LinuxUiGetterImpl>(); // Try loading gtk symbols used by Electron. electron::InitializeElectron_gtk(gtk::GetLibGtk()); if (!electron::IsElectron_gtkInitialized()) { electron::UninitializeElectron_gtk(); } electron::InitializeElectron_gdk_pixbuf(gtk::GetLibGdkPixbuf()); CHECK(electron::IsElectron_gdk_pixbufInitialized()) << "Failed to initialize libgdk_pixbuf-2.0.so.0"; // source theme changes from system settings, including settings portal: // https://flatpak.github.io/xdg-desktop-portal/#gdbus-org.freedesktop.portal.Settings dark_mode_manager_ = std::make_unique<ui::DarkModeManagerLinux>(); ui::LinuxUi::SetInstance(linux_ui); // Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager // implementation). Start observing them once it's initialized. ui::CursorFactory::GetInstance()->ObserveThemeChanges(); #endif #if defined(USE_AURA) wm_state_ = std::make_unique<wm::WMState>(); #endif #if BUILDFLAG(IS_WIN) gfx::win::SetAdjustFontCallback(&l10n_util::AdjustUiFont); gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize); #endif #if BUILDFLAG(IS_MAC) views_delegate_ = std::make_unique<ViewsDelegateMac>(); #else views_delegate_ = std::make_unique<ViewsDelegate>(); #endif } int ElectronBrowserMainParts::PreMainMessageLoopRun() { // Run user's main script before most things get initialized, so we can have // a chance to setup everything. node_bindings_->PrepareEmbedThread(); node_bindings_->StartPolling(); // url::Add*Scheme are not threadsafe, this helps prevent data races. url::LockSchemeRegistries(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_client_ = std::make_unique<ElectronExtensionsClient>(); extensions::ExtensionsClient::Set(extensions_client_.get()); // BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient. extensions_browser_client_ = std::make_unique<ElectronExtensionsBrowserClient>(); extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt(); extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt(); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckServiceFactory::GetInstance(); #endif content::WebUIControllerFactory::RegisterFactory( ElectronWebUIControllerFactory::GetInstance()); auto* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) { // --remote-debugging-pipe auto on_disconnect = base::BindOnce([]() { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce([]() { Browser::Get()->Quit(); })); }); content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler( std::move(on_disconnect)); } else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) { // --remote-debugging-port DevToolsManagerDelegate::StartHttpHandler(); } #if !BUILDFLAG(IS_MAC) // The corresponding call in macOS is in ElectronApplicationDelegate. Browser::Get()->WillFinishLaunching(); Browser::Get()->DidFinishLaunching(base::Value::Dict()); #endif // Notify observers that main thread message loop was initialized. Browser::Get()->PreMainMessageLoopRun(); fake_browser_process_->PreMainMessageLoopRun(); return GetExitCode(); } void ElectronBrowserMainParts::WillRunMainMessageLoop( std::unique_ptr<base::RunLoop>& run_loop) { exit_code_ = content::RESULT_CODE_NORMAL_EXIT; Browser::Get()->SetMainMessageLoopQuitClosure( run_loop->QuitWhenIdleClosure()); } void ElectronBrowserMainParts::PostCreateMainMessageLoop() { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) std::string app_name = electron::Browser::Get()->GetName(); #endif #if BUILDFLAG(IS_LINUX) auto shutdown_cb = base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop( std::move(shutdown_cb), content::GetUIThreadTaskRunner({content::BrowserTaskType::kUserInput})); bluez::DBusBluezManagerWrapperLinux::Initialize(); // Set up crypt config. This needs to be done before anything starts the // network service, as the raw encryption key needs to be shared with the // network service for encrypted cookie storage. const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); std::unique_ptr<os_crypt::Config> config = std::make_unique<os_crypt::Config>(); // Forward to os_crypt the flag to use a specific password store. config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore); config->product_name = app_name; config->application_name = app_name; // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1 config->should_use_preference = command_line.HasSwitch(::switches::kEnableEncryptionSelection); base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path); bool use_backend = !config->should_use_preference || os_crypt::GetBackendUse(config->user_data_path); std::unique_ptr<base::Environment> env(base::Environment::Create()); base::nix::DesktopEnvironment desktop_env = base::nix::GetDesktopEnvironment(env.get()); os_crypt::SelectedLinuxBackend selected_backend = os_crypt::SelectBackend(config->store, use_backend, desktop_env); fake_browser_process_->SetLinuxStorageBackend(selected_backend); OSCrypt::SetConfig(std::move(config)); #endif #if BUILDFLAG(IS_MAC) KeychainPassword::GetServiceName() = app_name + " Safe Storage"; KeychainPassword::GetAccountName() = app_name; #endif #if BUILDFLAG(IS_POSIX) // Exit in response to SIGINT, SIGTERM, etc. InstallShutdownSignalHandlers( base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())), content::GetUIThreadTaskRunner({})); #endif } void ElectronBrowserMainParts::PostMainMessageLoopRun() { #if BUILDFLAG(IS_MAC) FreeAppDelegate(); #endif // Shutdown the DownloadManager before destroying Node to prevent // DownloadItem callbacks from crashing. for (auto& iter : ElectronBrowserContext::browser_context_map()) { auto* download_manager = iter.second.get()->GetDownloadManager(); if (download_manager) { download_manager->Shutdown(); } } // Shutdown utility process created with Electron API before // stopping Node.js so that exit events can be emitted. We don't let // content layer perform this action since it destroys // child process only after this step (PostMainMessageLoopRun) via // BrowserProcessIOThread::ProcessHostCleanUp() which is too late for our // use case. // https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_main_loop.cc;l=1086-1108 // // The following logic is based on // https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_process_io_thread.cc;l=127-159 // // Although content::BrowserChildProcessHostIterator is only to be called from // IO thread, it is safe to call from PostMainMessageLoopRun because thread // restrictions have been lifted. // https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_main_loop.cc;l=1062-1078 for (content::BrowserChildProcessHostIterator it( content::PROCESS_TYPE_UTILITY); !it.Done(); ++it) { if (it.GetDelegate()->GetServiceName() == node::mojom::NodeService::Name_) { auto& process = it.GetData().GetProcess(); if (!process.IsValid()) continue; auto utility_process_wrapper = api::UtilityProcessWrapper::FromProcessId(process.Pid()); if (utility_process_wrapper) utility_process_wrapper->Shutdown(0 /* exit_code */); } } // Destroy node platform after all destructors_ are executed, as they may // invoke Node/V8 APIs inside them. node_env_->set_trace_sync_io(false); js_env_->DestroyMicrotasksRunner(); node::Stop(node_env_.get(), node::StopFlags::kDoNotTerminateIsolate); node_env_.reset(); auto default_context_key = ElectronBrowserContext::PartitionKey("", false); std::unique_ptr<ElectronBrowserContext> default_context = std::move( ElectronBrowserContext::browser_context_map()[default_context_key]); ElectronBrowserContext::browser_context_map().clear(); default_context.reset(); fake_browser_process_->PostMainMessageLoopRun(); content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler(); #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::GetInstance()->PostMainMessageLoopRun(); #endif } #if !BUILDFLAG(IS_MAC) void ElectronBrowserMainParts::PreCreateMainMessageLoop() { PreCreateMainMessageLoopCommon(); } #endif void ElectronBrowserMainParts::PreCreateMainMessageLoopCommon() { #if BUILDFLAG(IS_MAC) InitializeMainNib(); RegisterURLHandler(); #endif media::SetLocalizedStringProvider(MediaStringProvider); #if BUILDFLAG(IS_WIN) auto* local_state = g_browser_process->local_state(); DCHECK(local_state); bool os_crypt_init = OSCrypt::Init(local_state); DCHECK(os_crypt_init); #endif } device::mojom::GeolocationControl* ElectronBrowserMainParts::GetGeolocationControl() { if (!geolocation_control_) { content::GetDeviceService().BindGeolocationControl( geolocation_control_.BindNewPipeAndPassReceiver()); } return geolocation_control_.get(); } IconManager* ElectronBrowserMainParts::GetIconManager() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!icon_manager_.get()) icon_manager_ = std::make_unique<IconManager>(); return icon_manager_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,694
[Bug]: crashed when powerMonitor listens on suspend/resume event in main process at 27.1.x
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 26.6.2, 27.1.2, 27.1.3, 28.0.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04.6 ### What arch are you using? x64 ### Last Known Working Electron version 24.8.8, 25.9.7 ### Expected Behavior Not crashed ### Actual Behavior Crashed immediately when app is starting ``` #0 0x000055b563e9e533 in base::ImmediateCrash () at ../../base/immediate_crash.h:146 #1 logging::CheckFailure () at ../../base/check.h:192 #2 bluez::BluezDBusThreadManager::Get () at ../../device/bluetooth/dbus/bluez_dbus_thread_manager.cc:71 #3 0x000055b55f455b28 in electron::PowerObserverLinux::PowerObserverLinux (this=0x37ac02a71578, suspend_observer=<optimized out>) at ../../electron/shell/browser/lib/power_observer_linux.cc:37 #4 0x000055b55f2fe55f in electron::api::PowerMonitor::PowerMonitor (this=0x37ac02a71540, isolate=0x37ac0022c000) at ../../electron/shell/browser/api/electron_api_power_monitor.h:88 #5 electron::api::PowerMonitor::Create (isolate=0x37ac0022c000) at ../../electron/shell/browser/api/electron_api_power_monitor.cc:135 #6 0x000055b55f2a7819 in base::RepeatingCallback<v8::Local<v8::Value> (v8::Isolate*)>::Run(v8::Isolate*) const & (this=0x7ffdd8bcd0d8, args=0x4) at ../../base/functional/callback.h:333 #7 gin_helper::Invoker<gin_helper::IndicesHolder<0ul>, v8::Isolate*>::DispatchToCallback<v8::Local<v8::Value> >(base::RepeatingCallback<v8::Local<v8::Value> (v8::Isolate*)>) ( this=0x7ffdd8bcd150, callback=...) at ../../electron/shell/common/gin_helper/function_template.h:225 #8 0x000055b55f2a775a in gin_helper::Dispatcher<v8::Local<v8::Value> (v8::Isolate*)>::DispatchToCallback(v8::FunctionCallbackInfo<v8::Value> const&) (info=...) at ../../electron/shell/common/gin_helper/function_template.h:269 ``` ### Testcase Gist URL _No response_ ### Additional Information ``` js // Modules to control application life and create native browser window const { app, BrowserWindow, powerMonitor } = require('electron') const path = require('node:path') function createWindow () { // Create the browser window. const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js') } }) // and load the index.html of the app. mainWindow.loadFile('index.html') // Open the DevTools. // mainWindow.webContents.openDevTools() } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.whenReady().then(() => { createWindow() app.on('activate', function () { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) // Quit when all windows are closed, except on macOS. There, it's common // for applications and their menu bar to stay active until the user quits // explicitly with Cmd + Q. app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here. powerMonitor.on('suspend', () => { console.log('suspend') }); powerMonitor.on('resume', () => { console.log('resume') }); ```
https://github.com/electron/electron/issues/40694
https://github.com/electron/electron/pull/40888
7b4d490bfed9bf1b14b160132ae45c03eb946496
c184b93fc52f578b559511ec059bab4098d1404c
2023-12-05T04:44:15Z
c++
2024-01-09T08:41:42Z
shell/browser/lib/power_observer_linux.cc
// Copyright (c) 2017 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/lib/power_observer_linux.h" #include <unistd.h> #include <uv.h> #include <utility> #include "base/command_line.h" #include "base/files/file_path.h" #include "base/functional/bind.h" #include "base/logging.h" #include "device/bluetooth/dbus/bluez_dbus_thread_manager.h" namespace { const char kLogindServiceName[] = "org.freedesktop.login1"; const char kLogindObjectPath[] = "/org/freedesktop/login1"; const char kLogindManagerInterface[] = "org.freedesktop.login1.Manager"; base::FilePath::StringType GetExecutableBaseName() { return base::CommandLine::ForCurrentProcess() ->GetProgram() .BaseName() .value(); } } // namespace namespace electron { PowerObserverLinux::PowerObserverLinux( base::PowerSuspendObserver* suspend_observer) : suspend_observer_(suspend_observer), lock_owner_name_(GetExecutableBaseName()) { auto* bus = bluez::BluezDBusThreadManager::Get()->GetSystemBus(); if (!bus) { LOG(WARNING) << "Failed to get system bus connection"; return; } // set up the logind proxy const auto weakThis = weak_ptr_factory_.GetWeakPtr(); logind_ = bus->GetObjectProxy(kLogindServiceName, dbus::ObjectPath(kLogindObjectPath)); logind_->ConnectToSignal( kLogindManagerInterface, "PrepareForShutdown", base::BindRepeating(&PowerObserverLinux::OnPrepareForShutdown, weakThis), base::BindRepeating(&PowerObserverLinux::OnSignalConnected, weakThis)); logind_->ConnectToSignal( kLogindManagerInterface, "PrepareForSleep", base::BindRepeating(&PowerObserverLinux::OnPrepareForSleep, weakThis), base::BindRepeating(&PowerObserverLinux::OnSignalConnected, weakThis)); logind_->WaitForServiceToBeAvailable(base::BindRepeating( &PowerObserverLinux::OnLoginServiceAvailable, weakThis)); } PowerObserverLinux::~PowerObserverLinux() = default; void PowerObserverLinux::OnLoginServiceAvailable(bool service_available) { if (!service_available) { LOG(WARNING) << kLogindServiceName << " not available"; return; } // Take sleep inhibit lock BlockSleep(); } void PowerObserverLinux::BlockSleep() { dbus::MethodCall sleep_inhibit_call(kLogindManagerInterface, "Inhibit"); dbus::MessageWriter inhibit_writer(&sleep_inhibit_call); inhibit_writer.AppendString("sleep"); // what // Use the executable name as the lock owner, which will list rebrands of the // electron executable as separate entities. inhibit_writer.AppendString(lock_owner_name_); // who inhibit_writer.AppendString("Application cleanup before suspend"); // why inhibit_writer.AppendString("delay"); // mode logind_->CallMethod( &sleep_inhibit_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&PowerObserverLinux::OnInhibitResponse, weak_ptr_factory_.GetWeakPtr(), &sleep_lock_)); } void PowerObserverLinux::UnblockSleep() { sleep_lock_.reset(); } void PowerObserverLinux::BlockShutdown() { if (shutdown_lock_.is_valid()) { LOG(WARNING) << "Trying to subscribe to shutdown multiple times"; return; } dbus::MethodCall shutdown_inhibit_call(kLogindManagerInterface, "Inhibit"); dbus::MessageWriter inhibit_writer(&shutdown_inhibit_call); inhibit_writer.AppendString("shutdown"); // what inhibit_writer.AppendString(lock_owner_name_); // who inhibit_writer.AppendString("Ensure a clean shutdown"); // why inhibit_writer.AppendString("delay"); // mode logind_->CallMethod( &shutdown_inhibit_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&PowerObserverLinux::OnInhibitResponse, weak_ptr_factory_.GetWeakPtr(), &shutdown_lock_)); } void PowerObserverLinux::UnblockShutdown() { if (!shutdown_lock_.is_valid()) { LOG(WARNING) << "Trying to unsubscribe to shutdown without being subscribed"; return; } shutdown_lock_.reset(); } void PowerObserverLinux::SetShutdownHandler( base::RepeatingCallback<bool()> handler) { // In order to delay system shutdown when e.preventDefault() is invoked // on a powerMonitor 'shutdown' event, we need an org.freedesktop.login1 // shutdown delay lock. For more details see the "Taking Delay Locks" // section of https://www.freedesktop.org/wiki/Software/systemd/inhibit/ if (handler && !should_shutdown_) { BlockShutdown(); } else if (!handler && should_shutdown_) { UnblockShutdown(); } should_shutdown_ = std::move(handler); } void PowerObserverLinux::OnInhibitResponse(base::ScopedFD* scoped_fd, dbus::Response* response) { if (response != nullptr) { dbus::MessageReader reader(response); reader.PopFileDescriptor(scoped_fd); } } void PowerObserverLinux::OnPrepareForSleep(dbus::Signal* signal) { dbus::MessageReader reader(signal); bool suspending; if (!reader.PopBool(&suspending)) { LOG(ERROR) << "Invalid signal: " << signal->ToString(); return; } if (suspending) { suspend_observer_->OnSuspend(); UnblockSleep(); } else { BlockSleep(); suspend_observer_->OnResume(); } } void PowerObserverLinux::OnPrepareForShutdown(dbus::Signal* signal) { dbus::MessageReader reader(signal); bool shutting_down; if (!reader.PopBool(&shutting_down)) { LOG(ERROR) << "Invalid signal: " << signal->ToString(); return; } if (shutting_down) { if (!should_shutdown_ || should_shutdown_.Run()) { // The user didn't try to prevent shutdown. Release the lock and allow the // shutdown to continue normally. shutdown_lock_.reset(); } } } void PowerObserverLinux::OnSignalConnected(const std::string& /*interface*/, const std::string& signal, bool success) { LOG_IF(WARNING, !success) << "Failed to connect to " << signal; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,851
[Bug]: InAppPurchase promises not resolving
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.0 ### What operating system are you using? macOS ### Operating System Version macOS 14.1.1 (23B81) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior In app purchase working as expected and described in the documentation. ### Actual Behavior I want to integrate In App Purchase, i setup all the code correctly, in development or in "production" via testflight any of the methods inAppPurchase.getProducts or inAppPurchase.purchaseProduct didn't work. The first one return a promise that never resolve, the second one just didn't do anything. I tested to upgrade to electron 29.0.0 -> Same behaviour. I downgraded my electron version to 24.1.0 and i got another behaviour. In this version all work fine in development, but not in "production" via testflight, via testflight the inAppPurchase.getProducts didn't resolve the promise too and only the inAppPurchase.purchaseProduct kinda work but i didn't receive any inAppPurchase.on("transactions-updated") event so it's also unusable (can't restore purchases or check if a purchase is made if i didn't get the events). ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/40851
https://github.com/electron/electron/pull/40938
b39ebb8625b714d1369552d865643c98c624b9f8
d5d162b62237705e804831f49e738c987d99b2f9
2023-12-30T13:16:52Z
c++
2024-01-11T12:32:29Z
shell/browser/mac/in_app_purchase.mm
// Copyright (c) 2017 Amaplex Software, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/mac/in_app_purchase.h" #include <string> #include <utility> #include "base/functional/bind.h" #include "base/strings/sys_string_conversions.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #import <CommonCrypto/CommonCrypto.h> #import <StoreKit/StoreKit.h> // ============================================================================ // InAppPurchase // ============================================================================ // --------------------------------- Interface -------------------------------- @interface InAppPurchase : NSObject <SKProductsRequestDelegate> { @private in_app_purchase::InAppPurchaseCallback callback_; NSInteger quantity_; NSString* username_; } - (id)initWithCallback:(in_app_purchase::InAppPurchaseCallback)callback quantity:(NSInteger)quantity username:(NSString*)username; - (void)purchaseProduct:(NSString*)productID; @end // ------------------------------- Implementation ----------------------------- @implementation InAppPurchase /** * Init with a callback. * * @param callback - The callback that will be called when the payment is added * to the queue. */ - (id)initWithCallback:(in_app_purchase::InAppPurchaseCallback)callback quantity:(NSInteger)quantity username:(NSString*)username { if ((self = [super init])) { callback_ = std::move(callback); quantity_ = quantity; username_ = [username copy]; } return self; } /** * Start the in-app purchase process. * * @param productID - The id of the product to purchase (the id of * com.example.app.product1 is product1). */ - (void)purchaseProduct:(NSString*)productID { // Retrieve the product information. (The products request retrieves, // information about valid products along with a list of the invalid product // identifiers, and then calls its delegate to process the result). SKProductsRequest* productsRequest; productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:productID]]; productsRequest.delegate = self; [productsRequest start]; } /** * Process product informations and start the payment. * * @param request - The product request. * @param response - The informations about the list of products. */ - (void)productsRequest:(SKProductsRequest*)request didReceiveResponse:(SKProductsResponse*)response { // Get the first product. NSArray* products = response.products; SKProduct* product = [products count] == 1 ? [products firstObject] : nil; // Return if the product is not found or invalid. if (product == nil) { [self runCallback:false]; return; } // Start the payment process. [self checkout:product]; } /** * Submit a payment request to the App Store. * * @param product - The product to purchase. */ - (void)checkout:(SKProduct*)product { // Add the payment to the transaction queue. (The observer will be called // when the transaction is finished). SKMutablePayment* payment = [SKMutablePayment paymentWithProduct:product]; payment.quantity = quantity_; payment.applicationUsername = username_; [[SKPaymentQueue defaultQueue] addPayment:payment]; // Notify that the payment has been added to the queue with success. [self runCallback:true]; } /** * Submit a payment request to the App Store. * * @param product - The product to purchase. */ - (void)runCallback:(bool)isProductValid { if (callback_) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(std::move(callback_), isProductValid)); } } - (void)dealloc { username_ = nil; } @end // ============================================================================ // C++ in_app_purchase // ============================================================================ namespace in_app_purchase { bool CanMakePayments() { return [SKPaymentQueue canMakePayments]; } void RestoreCompletedTransactions() { [[SKPaymentQueue defaultQueue] restoreCompletedTransactions]; } void FinishAllTransactions() { for (SKPaymentTransaction* transaction in SKPaymentQueue.defaultQueue .transactions) { [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; } } void FinishTransactionByDate(const std::string& date) { // Create the date formatter. NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init]; NSLocale* enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; [dateFormatter setLocale:enUSPOSIXLocale]; [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"]; // Remove the transaction. NSString* transactionDate = base::SysUTF8ToNSString(date); for (SKPaymentTransaction* transaction in SKPaymentQueue.defaultQueue .transactions) { if ([transactionDate isEqualToString:[dateFormatter stringFromDate:transaction.transactionDate]]) { [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; } } } std::string GetReceiptURL() { NSURL* receiptURL = [[NSBundle mainBundle] appStoreReceiptURL]; if (receiptURL != nil) { return std::string([[receiptURL path] UTF8String]); } else { return ""; } } void PurchaseProduct(const std::string& productID, int quantity, const std::string& username, InAppPurchaseCallback callback) { auto* iap = [[InAppPurchase alloc] initWithCallback:std::move(callback) quantity:quantity username:base::SysUTF8ToNSString(username)]; [iap purchaseProduct:base::SysUTF8ToNSString(productID)]; } } // namespace in_app_purchase
closed
electron/electron
https://github.com/electron/electron
40,851
[Bug]: InAppPurchase promises not resolving
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.0 ### What operating system are you using? macOS ### Operating System Version macOS 14.1.1 (23B81) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior In app purchase working as expected and described in the documentation. ### Actual Behavior I want to integrate In App Purchase, i setup all the code correctly, in development or in "production" via testflight any of the methods inAppPurchase.getProducts or inAppPurchase.purchaseProduct didn't work. The first one return a promise that never resolve, the second one just didn't do anything. I tested to upgrade to electron 29.0.0 -> Same behaviour. I downgraded my electron version to 24.1.0 and i got another behaviour. In this version all work fine in development, but not in "production" via testflight, via testflight the inAppPurchase.getProducts didn't resolve the promise too and only the inAppPurchase.purchaseProduct kinda work but i didn't receive any inAppPurchase.on("transactions-updated") event so it's also unusable (can't restore purchases or check if a purchase is made if i didn't get the events). ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/40851
https://github.com/electron/electron/pull/40938
b39ebb8625b714d1369552d865643c98c624b9f8
d5d162b62237705e804831f49e738c987d99b2f9
2023-12-30T13:16:52Z
c++
2024-01-11T12:32:29Z
shell/browser/mac/in_app_purchase_product.mm
// Copyright (c) 2017 Amaplex Software, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/mac/in_app_purchase_product.h" #include <string> #include <utility> #include <vector> #include "base/functional/bind.h" #include "base/strings/sys_string_conversions.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #import <StoreKit/StoreKit.h> // ============================================================================ // InAppPurchaseProduct // ============================================================================ // --------------------------------- Interface -------------------------------- @interface InAppPurchaseProduct : NSObject <SKProductsRequestDelegate> { @private in_app_purchase::InAppPurchaseProductsCallback callback_; } - (id)initWithCallback:(in_app_purchase::InAppPurchaseProductsCallback)callback; @end // ------------------------------- Implementation ----------------------------- @implementation InAppPurchaseProduct /** * Init with a callback. * * @param callback - The callback that will be called to return the products. */ - (id)initWithCallback: (in_app_purchase::InAppPurchaseProductsCallback)callback { if ((self = [super init])) { callback_ = std::move(callback); } return self; } /** * Return products. * * @param productIDs - The products' id to fetch. */ - (void)getProducts:(NSSet*)productIDs { SKProductsRequest* productsRequest; productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIDs]; productsRequest.delegate = self; [productsRequest start]; } /** * @see SKProductsRequestDelegate */ - (void)productsRequest:(SKProductsRequest*)request didReceiveResponse:(SKProductsResponse*)response { // Get the products. NSArray* products = response.products; // Convert the products. std::vector<in_app_purchase::Product> converted; converted.reserve([products count]); for (SKProduct* product in products) { converted.push_back([self skProductToStruct:product]); } // Send the callback to the browser thread. content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(std::move(callback_), converted)); } /** * Format local price. * * @param price - The price to format. * @param priceLocal - The local format. */ - (NSString*)formatPrice:(NSDecimalNumber*)price withLocal:(NSLocale*)priceLocal { NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; [numberFormatter setLocale:priceLocal]; return [numberFormatter stringFromNumber:price]; } /** * Convert a SKProductSubscriptionPeriod object to a ProductSubscriptionPeriod * structure. * * @param productProductSubscriptionPeriod - The SKProductSubscriptionPeriod * object to convert. */ - (in_app_purchase::ProductSubscriptionPeriod) skProductSubscriptionPeriodToStruct: (SKProductSubscriptionPeriod*)productSubscriptionPeriod { in_app_purchase::ProductSubscriptionPeriod productSubscriptionPeriodStruct; productSubscriptionPeriodStruct.numberOfUnits = (int)productSubscriptionPeriod.numberOfUnits; if (productSubscriptionPeriod.unit == SKProductPeriodUnitDay) { productSubscriptionPeriodStruct.unit = "day"; } else if (productSubscriptionPeriod.unit == SKProductPeriodUnitWeek) { productSubscriptionPeriodStruct.unit = "week"; } else if (productSubscriptionPeriod.unit == SKProductPeriodUnitMonth) { productSubscriptionPeriodStruct.unit = "month"; } else if (productSubscriptionPeriod.unit == SKProductPeriodUnitYear) { productSubscriptionPeriodStruct.unit = "year"; } return productSubscriptionPeriodStruct; } /** * Convert a SKProductDiscount object to a ProductDiscount structure. * * @param productDiscount - The SKProductDiscount object to convert. */ - (in_app_purchase::ProductDiscount)skProductDiscountToStruct: (SKProductDiscount*)productDiscount { in_app_purchase::ProductDiscount productDiscountStruct; if (productDiscount.paymentMode == SKProductDiscountPaymentModePayAsYouGo) { productDiscountStruct.paymentMode = "payAsYouGo"; } else if (productDiscount.paymentMode == SKProductDiscountPaymentModePayUpFront) { productDiscountStruct.paymentMode = "payUpFront"; } else if (productDiscount.paymentMode == SKProductDiscountPaymentModeFreeTrial) { productDiscountStruct.paymentMode = "freeTrial"; } productDiscountStruct.numberOfPeriods = (int)productDiscount.numberOfPeriods; if (productDiscount.priceLocale != nil) { productDiscountStruct.priceLocale = [[self formatPrice:productDiscount.price withLocal:productDiscount.priceLocale] UTF8String]; } if (productDiscount.subscriptionPeriod != nil) { productDiscountStruct.subscriptionPeriod = [self skProductSubscriptionPeriodToStruct:productDiscount.subscriptionPeriod]; } productDiscountStruct.type = (int)productDiscount.type; if (productDiscount.identifier != nil) { productDiscountStruct.identifier = [productDiscount.identifier UTF8String]; } productDiscountStruct.price = [productDiscount.price doubleValue]; return productDiscountStruct; } /** * Convert a skProduct object to Product structure. * * @param product - The SKProduct object to convert. */ - (in_app_purchase::Product)skProductToStruct:(SKProduct*)product { in_app_purchase::Product productStruct; // Product Identifier if (product.productIdentifier != nil) { productStruct.productIdentifier = [product.productIdentifier UTF8String]; } // Product Attributes if (product.localizedDescription != nil) { productStruct.localizedDescription = [product.localizedDescription UTF8String]; } if (product.localizedTitle != nil) { productStruct.localizedTitle = [product.localizedTitle UTF8String]; } // Pricing Information if (product.price != nil) { productStruct.price = [product.price doubleValue]; if (product.priceLocale != nil) { productStruct.formattedPrice = [[self formatPrice:product.price withLocal:product.priceLocale] UTF8String]; // Currency Information if (product.priceLocale.currencyCode != nil) { productStruct.currencyCode = [product.priceLocale.currencyCode UTF8String]; } } } if (product.introductoryPrice != nil) { productStruct.introductoryPrice = [self skProductDiscountToStruct:product.introductoryPrice]; } if (product.subscriptionPeriod != nil) { productStruct.subscriptionPeriod = [self skProductSubscriptionPeriodToStruct:product.subscriptionPeriod]; } if (product.subscriptionGroupIdentifier != nil) { productStruct.subscriptionGroupIdentifier = [product.subscriptionGroupIdentifier UTF8String]; } if (product.discounts != nil) { productStruct.discounts.reserve([product.discounts count]); for (SKProductDiscount* discount in product.discounts) { productStruct.discounts.push_back( [self skProductDiscountToStruct:discount]); } } // Downloadable Content Information productStruct.isDownloadable = [product isDownloadable]; if (product.downloadContentVersion != nil) { productStruct.downloadContentVersion = [product.downloadContentVersion UTF8String]; } if (product.downloadContentLengths != nil) { productStruct.downloadContentLengths.reserve( [product.downloadContentLengths count]); for (NSNumber* contentLength in product.downloadContentLengths) { productStruct.downloadContentLengths.push_back( [contentLength longLongValue]); } } return productStruct; } @end // ============================================================================ // C++ in_app_purchase // ============================================================================ namespace in_app_purchase { ProductSubscriptionPeriod::ProductSubscriptionPeriod( const ProductSubscriptionPeriod&) = default; ProductSubscriptionPeriod::ProductSubscriptionPeriod() = default; ProductSubscriptionPeriod::~ProductSubscriptionPeriod() = default; ProductDiscount::ProductDiscount(const ProductDiscount&) = default; ProductDiscount::ProductDiscount() = default; ProductDiscount::~ProductDiscount() = default; Product::Product() = default; Product::Product(const Product&) = default; Product::~Product() = default; void GetProducts(const std::vector<std::string>& productIDs, InAppPurchaseProductsCallback callback) { auto* iapProduct = [[InAppPurchaseProduct alloc] initWithCallback:std::move(callback)]; // Convert the products' id to NSSet. NSMutableSet* productsIDSet = [NSMutableSet setWithCapacity:productIDs.size()]; for (auto& productID : productIDs) { [productsIDSet addObject:base::SysUTF8ToNSString(productID)]; } // Fetch the products. [iapProduct getProducts:productsIDSet]; } } // namespace in_app_purchase
closed
electron/electron
https://github.com/electron/electron
40,851
[Bug]: InAppPurchase promises not resolving
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.0.0 ### What operating system are you using? macOS ### Operating System Version macOS 14.1.1 (23B81) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior In app purchase working as expected and described in the documentation. ### Actual Behavior I want to integrate In App Purchase, i setup all the code correctly, in development or in "production" via testflight any of the methods inAppPurchase.getProducts or inAppPurchase.purchaseProduct didn't work. The first one return a promise that never resolve, the second one just didn't do anything. I tested to upgrade to electron 29.0.0 -> Same behaviour. I downgraded my electron version to 24.1.0 and i got another behaviour. In this version all work fine in development, but not in "production" via testflight, via testflight the inAppPurchase.getProducts didn't resolve the promise too and only the inAppPurchase.purchaseProduct kinda work but i didn't receive any inAppPurchase.on("transactions-updated") event so it's also unusable (can't restore purchases or check if a purchase is made if i didn't get the events). ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/40851
https://github.com/electron/electron/pull/40938
b39ebb8625b714d1369552d865643c98c624b9f8
d5d162b62237705e804831f49e738c987d99b2f9
2023-12-30T13:16:52Z
c++
2024-01-11T12:32:29Z
spec/api-in-app-purchase-spec.ts
import { expect } from 'chai'; import { inAppPurchase } from 'electron/main'; describe('inAppPurchase module', function () { if (process.platform !== 'darwin') return; this.timeout(3 * 60 * 1000); it('canMakePayments() returns a boolean', () => { const canMakePayments = inAppPurchase.canMakePayments(); expect(canMakePayments).to.be.a('boolean'); }); it('restoreCompletedTransactions() does not throw', () => { expect(() => { inAppPurchase.restoreCompletedTransactions(); }).to.not.throw(); }); it('finishAllTransactions() does not throw', () => { expect(() => { inAppPurchase.finishAllTransactions(); }).to.not.throw(); }); it('finishTransactionByDate() does not throw', () => { expect(() => { inAppPurchase.finishTransactionByDate(new Date().toISOString()); }).to.not.throw(); }); it('getReceiptURL() returns receipt URL', () => { expect(inAppPurchase.getReceiptURL()).to.match(/_MASReceipt\/receipt$/); }); // The following three tests are disabled because they hit Apple servers, and // Apple started blocking requests from AWS IPs (we think), so they fail on CI. // TODO: find a way to mock out the server requests so we can test these APIs // without relying on a remote service. xdescribe('handles product purchases', () => { it('purchaseProduct() fails when buying invalid product', async () => { const success = await inAppPurchase.purchaseProduct('non-exist'); expect(success).to.be.false('failed to purchase non-existent product'); }); it('purchaseProduct() accepts optional (Integer) argument', async () => { const success = await inAppPurchase.purchaseProduct('non-exist', 1); expect(success).to.be.false('failed to purchase non-existent product'); }); it('purchaseProduct() accepts optional (Object) argument', async () => { const success = await inAppPurchase.purchaseProduct('non-exist', { quantity: 1, username: 'username' }); expect(success).to.be.false('failed to purchase non-existent product'); }); it('getProducts() returns an empty list when getting invalid product', async () => { const products = await inAppPurchase.getProducts(['non-exist']); expect(products).to.be.an('array').of.length(0); }); }); });
closed
electron/electron
https://github.com/electron/electron
40,989
[Bug]: ESM cannot be used with contextIsolation: false import.meta.url
### Preflight Checklist - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [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 28.1.3 ### What operating system are you using? Windows ### Operating System Version 22631.3007 ### What arch are you using? x64 ### Last Known Working Electron version 28.1.3 ### Expected Behavior The rendering process renders normally. ### Actual Behavior In ESM, `import.meta.url` is not available in `preload` when I use `contextIsolation: false`,rendering process is unresponsive. ### Testcase Gist URL https://gist.github.com/f9cde94e621204933822255591f11011 ### Additional Information _No response_
https://github.com/electron/electron/issues/40989
https://github.com/electron/electron/pull/40993
4949c4c4e130e63b861adfc0093453c510579000
6803624576dc0086b83bdf50051a0dfd96f71401
2024-01-15T03:33:49Z
c++
2024-01-16T13:29:00Z
patches/node/chore_expose_importmoduledynamically_and.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Samuel Attard <[email protected]> Date: Wed, 8 Mar 2023 13:02:17 -0800 Subject: chore: expose ImportModuleDynamically and HostInitializeImportMetaObjectCallback to embedders This also subtly changes the behavior of shouldNotRegisterESMLoader to ensure that node sets up the handlers internally but simply avoids setting its own handlers on the Isolate. This is so that Electron can set it to its own blended handler between Node and Blink. Not upstreamable. diff --git a/lib/internal/modules/esm/utils.js b/lib/internal/modules/esm/utils.js index 41077285452eac05766a22c2e1d252868e7e548b..2246e57efcf0b95903644d643ad5572717ecdaf4 100644 --- a/lib/internal/modules/esm/utils.js +++ b/lib/internal/modules/esm/utils.js @@ -22,7 +22,7 @@ const { ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING, ERR_INVALID_ARG_VALUE, } = require('internal/errors').codes; -const { getOptionValue } = require('internal/options'); +const { getOptionValue, getEmbedderOptions } = require('internal/options'); const { loadPreloadModules, initializeFrozenIntrinsics, @@ -190,12 +190,13 @@ let _isLoaderWorker = false; * @param {boolean} [isLoaderWorker=false] - A boolean indicating whether the loader is a worker or not. */ function initializeESM(isLoaderWorker = false) { + const shouldSetOnIsolate = !getEmbedderOptions().shouldNotRegisterESMLoader; _isLoaderWorker = isLoaderWorker; initializeDefaultConditions(); // Setup per-isolate callbacks that locate data or callbacks that we keep // track of for different ESM modules. - setInitializeImportMetaObjectCallback(initializeImportMetaObject); - setImportModuleDynamicallyCallback(importModuleDynamicallyCallback); + setInitializeImportMetaObjectCallback(initializeImportMetaObject, shouldSetOnIsolate); + setImportModuleDynamicallyCallback(importModuleDynamicallyCallback, shouldSetOnIsolate); } /** diff --git a/src/module_wrap.cc b/src/module_wrap.cc index 52c30dcb47d1faba0c2267e4381a624e450baa02..ba4c1a0d5a987e4d410b49f5c47166943bd101a6 100644 --- a/src/module_wrap.cc +++ b/src/module_wrap.cc @@ -547,7 +547,7 @@ MaybeLocal<Module> ModuleWrap::ResolveModuleCallback( return module->module_.Get(isolate); } -static MaybeLocal<Promise> ImportModuleDynamically( +MaybeLocal<Promise> ImportModuleDynamically( Local<Context> context, Local<v8::Data> host_defined_options, Local<Value> resource_name, @@ -608,12 +608,13 @@ void ModuleWrap::SetImportModuleDynamicallyCallback( Environment* env = Environment::GetCurrent(args); HandleScope handle_scope(isolate); - CHECK_EQ(args.Length(), 1); + CHECK_EQ(args.Length(), 2); CHECK(args[0]->IsFunction()); Local<Function> import_callback = args[0].As<Function>(); env->set_host_import_module_dynamically_callback(import_callback); - isolate->SetHostImportModuleDynamicallyCallback(ImportModuleDynamically); + if (args[1]->IsBoolean() && args[1]->BooleanValue(isolate)) + isolate->SetHostImportModuleDynamicallyCallback(ImportModuleDynamically); } void ModuleWrap::HostInitializeImportMetaObjectCallback( @@ -650,13 +651,14 @@ void ModuleWrap::SetInitializeImportMetaObjectCallback( Environment* env = Environment::GetCurrent(args); Isolate* isolate = env->isolate(); - CHECK_EQ(args.Length(), 1); + CHECK_EQ(args.Length(), 2); CHECK(args[0]->IsFunction()); Local<Function> import_meta_callback = args[0].As<Function>(); env->set_host_initialize_import_meta_object_callback(import_meta_callback); - isolate->SetHostInitializeImportMetaObjectCallback( - HostInitializeImportMetaObjectCallback); + if (args[1]->IsBoolean() && args[1]->BooleanValue(isolate)) + isolate->SetHostInitializeImportMetaObjectCallback( + HostInitializeImportMetaObjectCallback); } MaybeLocal<Value> ModuleWrap::SyntheticModuleEvaluationStepsCallback( diff --git a/src/module_wrap.h b/src/module_wrap.h index 1fc801edced9c5e44613846b4dc555804c5bae97..23a0d7aee1dfa0ebe26e0507e31eacb0b4d137ed 100644 --- a/src/module_wrap.h +++ b/src/module_wrap.h @@ -30,7 +30,14 @@ enum HostDefinedOptions : int { kLength = 9, }; -class ModuleWrap : public BaseObject { +NODE_EXTERN v8::MaybeLocal<v8::Promise> ImportModuleDynamically( + v8::Local<v8::Context> context, + v8::Local<v8::Data> host_defined_options, + v8::Local<v8::Value> resource_name, + v8::Local<v8::String> specifier, + v8::Local<v8::FixedArray> import_assertions); + +class NODE_EXTERN ModuleWrap : public BaseObject { public: enum InternalFields { kModuleSlot = BaseObject::kInternalFieldCount,
closed
electron/electron
https://github.com/electron/electron
40,989
[Bug]: ESM cannot be used with contextIsolation: false import.meta.url
### Preflight Checklist - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [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 28.1.3 ### What operating system are you using? Windows ### Operating System Version 22631.3007 ### What arch are you using? x64 ### Last Known Working Electron version 28.1.3 ### Expected Behavior The rendering process renders normally. ### Actual Behavior In ESM, `import.meta.url` is not available in `preload` when I use `contextIsolation: false`,rendering process is unresponsive. ### Testcase Gist URL https://gist.github.com/f9cde94e621204933822255591f11011 ### Additional Information _No response_
https://github.com/electron/electron/issues/40989
https://github.com/electron/electron/pull/40993
4949c4c4e130e63b861adfc0093453c510579000
6803624576dc0086b83bdf50051a0dfd96f71401
2024-01-15T03:33:49Z
c++
2024-01-16T13:29:00Z
patches/node/fix_missing_include_for_node_extern.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Wed, 15 Nov 2023 12:25:39 +0100 Subject: fix: missing include for NODE_EXTERN At some point it seems that node.h was removed from the include chain, causing the following error: ../../third_party/electron_node/src/module_wrap.h:33:1: error: unknown type name 'NODE_EXTERN' 33 | NODE_EXTERN v8::MaybeLocal<v8::Promise> ImportModuleDynamically( | ^ This should be upstreamed. diff --git a/src/module_wrap.h b/src/module_wrap.h index 23a0d7aee1dfa0ebe26e0507e31eacb0b4d137ed..0733017d8e1ac6e60589082b402bd44a98ddc312 100644 --- a/src/module_wrap.h +++ b/src/module_wrap.h @@ -7,6 +7,7 @@ #include <string> #include <vector> #include "base_object.h" +#include "node.h" namespace node {
closed
electron/electron
https://github.com/electron/electron
40,989
[Bug]: ESM cannot be used with contextIsolation: false import.meta.url
### Preflight Checklist - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [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 28.1.3 ### What operating system are you using? Windows ### Operating System Version 22631.3007 ### What arch are you using? x64 ### Last Known Working Electron version 28.1.3 ### Expected Behavior The rendering process renders normally. ### Actual Behavior In ESM, `import.meta.url` is not available in `preload` when I use `contextIsolation: false`,rendering process is unresponsive. ### Testcase Gist URL https://gist.github.com/f9cde94e621204933822255591f11011 ### Additional Information _No response_
https://github.com/electron/electron/issues/40989
https://github.com/electron/electron/pull/40993
4949c4c4e130e63b861adfc0093453c510579000
6803624576dc0086b83bdf50051a0dfd96f71401
2024-01-15T03:33:49Z
c++
2024-01-16T13:29:00Z
shell/common/node_bindings.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/node_bindings.h" #include <algorithm> #include <string> #include <string_view> #include <utility> #include <vector> #include "base/base_paths.h" #include "base/command_line.h" #include "base/containers/fixed_flat_set.h" #include "base/environment.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_paths.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "shell/browser/api/electron_api_app.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/electron_command_line.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/mac/main_application_bundle.h" #include "shell/common/world_ids.h" #include "third_party/blink/public/web/web_local_frame.h" #include "third_party/blink/renderer/bindings/core/v8/v8_initializer.h" // nogncheck #include "third_party/electron_node/src/debug_utils.h" #include "third_party/electron_node/src/module_wrap.h" #if !IS_MAS_BUILD() #include "shell/common/crash_keys.h" #endif #define ELECTRON_BROWSER_BINDINGS(V) \ V(electron_browser_app) \ V(electron_browser_auto_updater) \ V(electron_browser_content_tracing) \ V(electron_browser_crash_reporter) \ V(electron_browser_desktop_capturer) \ V(electron_browser_dialog) \ V(electron_browser_event_emitter) \ V(electron_browser_global_shortcut) \ V(electron_browser_image_view) \ V(electron_browser_in_app_purchase) \ V(electron_browser_menu) \ V(electron_browser_message_port) \ V(electron_browser_native_theme) \ V(electron_browser_notification) \ V(electron_browser_power_monitor) \ V(electron_browser_power_save_blocker) \ V(electron_browser_protocol) \ V(electron_browser_printing) \ V(electron_browser_push_notifications) \ V(electron_browser_safe_storage) \ V(electron_browser_session) \ V(electron_browser_screen) \ V(electron_browser_system_preferences) \ V(electron_browser_base_window) \ V(electron_browser_tray) \ V(electron_browser_utility_process) \ V(electron_browser_view) \ V(electron_browser_web_contents) \ V(electron_browser_web_contents_view) \ V(electron_browser_web_frame_main) \ V(electron_browser_web_view_manager) \ V(electron_browser_window) \ V(electron_common_net) #define ELECTRON_COMMON_BINDINGS(V) \ V(electron_common_asar) \ V(electron_common_clipboard) \ V(electron_common_command_line) \ V(electron_common_crashpad_support) \ V(electron_common_environment) \ V(electron_common_features) \ V(electron_common_native_image) \ V(electron_common_shell) \ V(electron_common_v8_util) #define ELECTRON_RENDERER_BINDINGS(V) \ V(electron_renderer_web_utils) \ V(electron_renderer_context_bridge) \ V(electron_renderer_crash_reporter) \ V(electron_renderer_ipc) \ V(electron_renderer_web_frame) #define ELECTRON_UTILITY_BINDINGS(V) \ V(electron_browser_event_emitter) \ V(electron_common_net) \ V(electron_utility_parent_port) #define ELECTRON_TESTING_BINDINGS(V) V(electron_common_testing) // This is used to load built-in bindings. Instead of using // __attribute__((constructor)), we call the _register_<modname> // function for each built-in bindings explicitly. This is only // forward declaration. The definitions are in each binding's // implementation when calling the NODE_LINKED_BINDING_CONTEXT_AWARE. #define V(modname) void _register_##modname(); ELECTRON_BROWSER_BINDINGS(V) ELECTRON_COMMON_BINDINGS(V) ELECTRON_RENDERER_BINDINGS(V) ELECTRON_UTILITY_BINDINGS(V) #if DCHECK_IS_ON() ELECTRON_TESTING_BINDINGS(V) #endif #undef V namespace { void stop_and_close_uv_loop(uv_loop_t* loop) { uv_stop(loop); auto const ensure_closing = [](uv_handle_t* handle, void*) { // We should be using the UvHandle wrapper everywhere, in which case // all handles should already be in a closing state... DCHECK(uv_is_closing(handle)); // ...but if a raw handle got through, through, do the right thing anyway if (!uv_is_closing(handle)) { uv_close(handle, nullptr); } }; uv_walk(loop, ensure_closing, nullptr); // All remaining handles are in a closing state now. // Pump the event loop so that they can finish closing. for (;;) if (uv_run(loop, UV_RUN_DEFAULT) == 0) break; DCHECK_EQ(0, uv_loop_alive(loop)); node::CheckedUvLoopClose(loop); } bool g_is_initialized = false; void V8FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; #if !IS_MAS_BUILD() electron::crash_keys::SetCrashKey("electron.v8-fatal.message", message); electron::crash_keys::SetCrashKey("electron.v8-fatal.location", location); #endif volatile int* zero = nullptr; *zero = 0; } bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context, v8::Local<v8::String> source) { // If we're running with contextIsolation enabled in the renderer process, // fall back to Blink's logic. if (node::Environment::GetCurrent(context) == nullptr) { if (!electron::IsRendererProcess()) return false; return blink::V8Initializer::WasmCodeGenerationCheckCallbackInMainThread( context, source); } return node::AllowWasmCodeGenerationCallback(context, source); } v8::MaybeLocal<v8::Promise> HostImportModuleDynamically( v8::Local<v8::Context> context, v8::Local<v8::Data> v8_host_defined_options, v8::Local<v8::Value> v8_referrer_resource_url, v8::Local<v8::String> v8_specifier, v8::Local<v8::FixedArray> v8_import_assertions) { if (node::Environment::GetCurrent(context) == nullptr) { if (electron::IsBrowserProcess() || electron::IsUtilityProcess()) return v8::MaybeLocal<v8::Promise>(); return blink::V8Initializer::HostImportModuleDynamically( context, v8_host_defined_options, v8_referrer_resource_url, v8_specifier, v8_import_assertions); } // If we're running with contextIsolation enabled in the renderer process, // fall back to Blink's logic. if (electron::IsRendererProcess()) { blink::WebLocalFrame* frame = blink::WebLocalFrame::FrameForContext(context); if (!frame || frame->GetScriptContextWorldId(context) != electron::WorldIDs::ISOLATED_WORLD_ID) { return blink::V8Initializer::HostImportModuleDynamically( context, v8_host_defined_options, v8_referrer_resource_url, v8_specifier, v8_import_assertions); } } return node::loader::ImportModuleDynamically( context, v8_host_defined_options, v8_referrer_resource_url, v8_specifier, v8_import_assertions); } void HostInitializeImportMetaObject(v8::Local<v8::Context> context, v8::Local<v8::Module> module, v8::Local<v8::Object> meta) { if (node::Environment::GetCurrent(context) == nullptr) { if (electron::IsBrowserProcess() || electron::IsUtilityProcess()) return; return blink::V8Initializer::HostGetImportMetaProperties(context, module, meta); } // If we're running with contextIsolation enabled in the renderer process, // fall back to Blink's logic. if (electron::IsRendererProcess()) { blink::WebLocalFrame* frame = blink::WebLocalFrame::FrameForContext(context); if (!frame || frame->GetScriptContextWorldId(context) != electron::WorldIDs::ISOLATED_WORLD_ID) { return blink::V8Initializer::HostGetImportMetaProperties(context, module, meta); } } return node::loader::ModuleWrap::HostInitializeImportMetaObjectCallback( context, module, meta); } v8::ModifyCodeGenerationFromStringsResult ModifyCodeGenerationFromStrings( v8::Local<v8::Context> context, v8::Local<v8::Value> source, bool is_code_like) { if (node::Environment::GetCurrent(context) == nullptr) { // No node environment means we're in the renderer process, either in a // sandboxed renderer or in an unsandboxed renderer with context isolation // enabled. if (!electron::IsRendererProcess()) { NOTREACHED(); return {false, {}}; } return blink::V8Initializer::CodeGenerationCheckCallbackInMainThread( context, source, is_code_like); } // If we get here then we have a node environment, so either a) we're in the // non-renderer process, or b) we're in the renderer process in a context that // has both node and blink, i.e. contextIsolation disabled. // If we're in the renderer with contextIsolation disabled, ask blink first // (for CSP), and iff that allows codegen, delegate to node. if (electron::IsRendererProcess()) { v8::ModifyCodeGenerationFromStringsResult result = blink::V8Initializer::CodeGenerationCheckCallbackInMainThread( context, source, is_code_like); if (!result.codegen_allowed) return result; } // If we're in the main process or utility process, delegate to node. return node::ModifyCodeGenerationFromStrings(context, source, is_code_like); } void ErrorMessageListener(v8::Local<v8::Message> message, v8::Local<v8::Value> data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); node::Environment* env = node::Environment::GetCurrent(isolate); if (env) { gin_helper::MicrotasksScope microtasks_scope( isolate, env->context()->GetMicrotaskQueue(), v8::MicrotasksScope::kDoNotRunMicrotasks); // Emit the after() hooks now that the exception has been handled. // Analogous to node/lib/internal/process/execution.js#L176-L180 if (env->async_hooks()->fields()[node::AsyncHooks::kAfter]) { while (env->async_hooks()->fields()[node::AsyncHooks::kStackLength]) { double id = env->execution_async_id(); // Do not call EmitAfter for asyncId 0. if (id != 0) node::AsyncWrap::EmitAfter(env, id); env->async_hooks()->pop_async_context(id); } } // Ensure that the async id stack is properly cleared so the async // hook stack does not become corrupted. env->async_hooks()->clear_async_id_stack(); } } // Only allow a specific subset of options in non-ELECTRON_RUN_AS_NODE mode. // If node CLI inspect support is disabled, allow no debug options. bool IsAllowedOption(const std::string_view option) { static constexpr auto debug_options = base::MakeFixedFlatSet<std::string_view>({ "--debug", "--debug-brk", "--debug-port", "--inspect", "--inspect-brk", "--inspect-brk-node", "--inspect-port", "--inspect-publish-uid", }); // This should be aligned with what's possible to set via the process object. static constexpr auto options = base::MakeFixedFlatSet<std::string_view>({ "--dns-result-order", "--no-deprecation", "--throw-deprecation", "--trace-deprecation", "--trace-warnings", }); if (debug_options.contains(option)) return electron::fuses::IsNodeCliInspectEnabled(); return options.contains(option); } // Initialize NODE_OPTIONS to pass to Node.js // See https://nodejs.org/api/cli.html#cli_node_options_options void SetNodeOptions(base::Environment* env) { // Options that are unilaterally disallowed static constexpr auto disallowed = base::MakeFixedFlatSet<std::string_view>({ "--enable-fips", "--experimental-policy", "--force-fips", "--openssl-config", "--use-bundled-ca", "--use-openssl-ca", }); static constexpr auto pkg_opts = base::MakeFixedFlatSet<std::string_view>({ "--http-parser", "--max-http-header-size", }); if (env->HasVar("NODE_OPTIONS")) { if (electron::fuses::IsNodeOptionsEnabled()) { std::string options; env->GetVar("NODE_OPTIONS", &options); std::vector<std::string> parts = base::SplitString( options, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); bool is_packaged_app = electron::api::App::IsPackaged(); for (const auto& part : parts) { // Strip off values passed to individual NODE_OPTIONs std::string option = part.substr(0, part.find('=')); if (is_packaged_app && !pkg_opts.contains(option)) { // Explicitly disallow majority of NODE_OPTIONS in packaged apps LOG(ERROR) << "Most NODE_OPTIONs are not supported in packaged apps." << " See documentation for more details."; options.erase(options.find(option), part.length()); } else if (disallowed.contains(option)) { // Remove NODE_OPTIONS specifically disallowed for use in Node.js // through Electron owing to constraints like BoringSSL. LOG(ERROR) << "The NODE_OPTION " << option << " is not supported in Electron"; options.erase(options.find(option), part.length()); } } // overwrite new NODE_OPTIONS without unsupported variables env->SetVar("NODE_OPTIONS", options); } else { LOG(ERROR) << "NODE_OPTIONS have been disabled in this app"; env->SetVar("NODE_OPTIONS", ""); } } } } // namespace namespace electron { namespace { base::FilePath GetResourcesPath() { #if BUILDFLAG(IS_MAC) return MainApplicationBundlePath().Append("Contents").Append("Resources"); #else auto* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); base::PathService::Get(base::FILE_EXE, &exec_path); return exec_path.DirName().Append(FILE_PATH_LITERAL("resources")); #endif } } // namespace NodeBindings::NodeBindings(BrowserEnvironment browser_env) : browser_env_{browser_env}, uv_loop_{InitEventLoop(browser_env, &worker_loop_)} {} NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); // Clear uv. uv_sem_destroy(&embed_sem_); dummy_uv_handle_.reset(); // Clean up worker loop if (in_worker_loop()) stop_and_close_uv_loop(uv_loop_); } // static uv_loop_t* NodeBindings::InitEventLoop(BrowserEnvironment browser_env, uv_loop_t* worker_loop) { uv_loop_t* event_loop = nullptr; if (browser_env == BrowserEnvironment::kWorker) { uv_loop_init(worker_loop); event_loop = worker_loop; } else { event_loop = uv_default_loop(); } // Interrupt embed polling when a handle is started. uv_loop_configure(event_loop, UV_LOOP_INTERRUPT_ON_IO_CHANGE); return event_loop; } void NodeBindings::RegisterBuiltinBindings() { #define V(modname) _register_##modname(); if (IsBrowserProcess()) { ELECTRON_BROWSER_BINDINGS(V) } ELECTRON_COMMON_BINDINGS(V) if (IsRendererProcess()) { ELECTRON_RENDERER_BINDINGS(V) } if (IsUtilityProcess()) { ELECTRON_UTILITY_BINDINGS(V) } #if DCHECK_IS_ON() ELECTRON_TESTING_BINDINGS(V) #endif #undef V } bool NodeBindings::IsInitialized() { return g_is_initialized; } // Initialize Node.js cli options to pass to Node.js // See https://nodejs.org/api/cli.html#cli_options std::vector<std::string> NodeBindings::ParseNodeCliFlags() { const auto argv = base::CommandLine::ForCurrentProcess()->argv(); std::vector<std::string> args; // TODO(codebytere): We need to set the first entry in args to the // process name owing to src/node_options-inl.h#L286-L290 but this is // redundant and so should be refactored upstream. args.reserve(argv.size() + 1); args.emplace_back("electron"); for (const auto& arg : argv) { #if BUILDFLAG(IS_WIN) const auto& option = base::WideToUTF8(arg); #else const auto& option = arg; #endif const auto stripped = std::string_view{option}.substr(0, option.find('=')); // Only allow no-op or a small set of debug/trace related options. if (IsAllowedOption(stripped) || stripped == "--") args.push_back(option); } // We need to disable Node.js' fetch implementation to prevent // conflict with Blink's in renderer and worker processes. if (browser_env_ == BrowserEnvironment::kRenderer || browser_env_ == BrowserEnvironment::kWorker) { args.push_back("--no-experimental-fetch"); } return args; } void NodeBindings::Initialize(v8::Local<v8::Context> context) { TRACE_EVENT0("electron", "NodeBindings::Initialize"); // Open node's error reporting system for browser process. #if BUILDFLAG(IS_LINUX) // Get real command line in renderer process forked by zygote. if (browser_env_ != BrowserEnvironment::kBrowser) ElectronCommandLine::InitializeFromCommandLine(); #endif // Explicitly register electron's builtin bindings. RegisterBuiltinBindings(); auto env = base::Environment::Create(); SetNodeOptions(env.get()); // Parse and set Node.js cli flags. std::vector<std::string> args = ParseNodeCliFlags(); uint64_t process_flags = node::ProcessInitializationFlags::kNoInitializeV8 | node::ProcessInitializationFlags::kNoInitializeNodeV8Platform | node::ProcessInitializationFlags::kNoEnableWasmTrapHandler; // We do not want the child processes spawned from the utility process // to inherit the custom stdio handles created for the parent. if (browser_env_ != BrowserEnvironment::kUtility) process_flags |= node::ProcessInitializationFlags::kEnableStdioInheritance; if (browser_env_ == BrowserEnvironment::kRenderer) process_flags |= node::ProcessInitializationFlags::kNoInitializeCppgc | node::ProcessInitializationFlags::kNoDefaultSignalHandling; if (!fuses::IsNodeOptionsEnabled()) process_flags |= node::ProcessInitializationFlags::kDisableNodeOptionsEnv; std::unique_ptr<node::InitializationResult> result = node::InitializeOncePerProcess( args, static_cast<node::ProcessInitializationFlags::Flags>(process_flags)); for (const std::string& error : result->errors()) { fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str()); } if (result->early_return() != 0) exit(result->exit_code()); #if BUILDFLAG(IS_WIN) // uv_init overrides error mode to suppress the default crash dialog, bring // it back if user wants to show it. if (browser_env_ == BrowserEnvironment::kBrowser || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE")) SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX); #endif gin_helper::internal::Event::GetConstructor(context); g_is_initialized = true; } std::shared_ptr<node::Environment> NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform, std::vector<std::string> args, std::vector<std::string> exec_args, std::optional<base::RepeatingCallback<void()>> on_app_code_ready) { // Feed node the path to initialization script. std::string process_type; switch (browser_env_) { case BrowserEnvironment::kBrowser: process_type = "browser"; break; case BrowserEnvironment::kRenderer: process_type = "renderer"; break; case BrowserEnvironment::kWorker: process_type = "worker"; break; case BrowserEnvironment::kUtility: process_type = "utility"; break; } v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary global(isolate, context->Global()); if (browser_env_ == BrowserEnvironment::kBrowser) { const std::vector<std::string> search_paths = {"app.asar", "app", "default_app.asar"}; const std::vector<std::string> app_asar_search_paths = {"app.asar"}; context->Global()->SetPrivate( context, v8::Private::ForApi( isolate, gin::ConvertToV8(isolate, "appSearchPaths").As<v8::String>()), gin::ConvertToV8(isolate, electron::fuses::IsOnlyLoadAppFromAsarEnabled() ? app_asar_search_paths : search_paths)); context->Global()->SetPrivate( context, v8::Private::ForApi( isolate, gin::ConvertToV8(isolate, "appSearchPathsOnlyLoadASAR") .As<v8::String>()), gin::ConvertToV8(isolate, electron::fuses::IsOnlyLoadAppFromAsarEnabled())); } base::FilePath resources_path = GetResourcesPath(); std::string init_script = "electron/js2c/" + process_type + "_init"; args.insert(args.begin() + 1, init_script); auto* isolate_data = node::CreateIsolateData(isolate, uv_loop_, platform); context->SetAlignedPointerInEmbedderData(kElectronContextEmbedderDataIndex, static_cast<void*>(isolate_data)); node::Environment* env; uint64_t env_flags = node::EnvironmentFlags::kDefaultFlags | node::EnvironmentFlags::kHideConsoleWindows | node::EnvironmentFlags::kNoGlobalSearchPaths | node::EnvironmentFlags::kNoRegisterESMLoader; if (browser_env_ == BrowserEnvironment::kRenderer || browser_env_ == BrowserEnvironment::kWorker) { // Only one ESM loader can be registered per isolate - // in renderer processes this should be blink. We need to tell Node.js // not to register its handler (overriding blinks) in non-browser processes. // We also avoid overriding globals like setImmediate, clearImmediate // queueMicrotask etc during the bootstrap phase of Node.js // for processes that already have these defined by DOM. // Check //third_party/electron_node/lib/internal/bootstrap/node.js // for the list of overrides on globalThis. env_flags |= node::EnvironmentFlags::kNoBrowserGlobals | node::EnvironmentFlags::kNoCreateInspector; } if (!electron::fuses::IsNodeCliInspectEnabled()) { // If --inspect and friends are disabled we also shouldn't listen for // SIGUSR1 env_flags |= node::EnvironmentFlags::kNoStartDebugSignalHandler; } { v8::TryCatch try_catch(isolate); env = node::CreateEnvironment( static_cast<node::IsolateData*>(isolate_data), context, args, exec_args, static_cast<node::EnvironmentFlags::Flags>(env_flags)); if (try_catch.HasCaught()) { std::string err_msg = "Failed to initialize node environment in process: " + process_type; v8::Local<v8::Message> message = try_catch.Message(); std::string msg; if (!message.IsEmpty() && gin::ConvertFromV8(isolate, message->Get(), &msg)) err_msg += " , with error: " + msg; LOG(ERROR) << err_msg; } } DCHECK(env); node::IsolateSettings is; // Use a custom fatal error callback to allow us to add // crash message and location to CrashReports. is.fatal_error_callback = V8FatalErrorCallback; // We don't want to abort either in the renderer or browser processes. // We already listen for uncaught exceptions and handle them there. // For utility process we expect the process to behave as standard // Node.js runtime and abort the process with appropriate exit // code depending on a handler being set for `uncaughtException` event. if (browser_env_ != BrowserEnvironment::kUtility) { is.should_abort_on_uncaught_exception_callback = [](v8::Isolate*) { return false; }; } // Use a custom callback here to allow us to leverage Blink's logic in the // renderer process. is.allow_wasm_code_generation_callback = AllowWasmCodeGenerationCallback; is.flags |= node::IsolateSettingsFlags:: ALLOW_MODIFY_CODE_GENERATION_FROM_STRINGS_CALLBACK; is.modify_code_generation_from_strings_callback = ModifyCodeGenerationFromStrings; if (browser_env_ == BrowserEnvironment::kBrowser || browser_env_ == BrowserEnvironment::kUtility) { // Node.js requires that microtask checkpoints be explicitly invoked. is.policy = v8::MicrotasksPolicy::kExplicit; } else { // Blink expects the microtasks policy to be kScoped, but Node.js expects it // to be kExplicit. In the renderer, there can be many contexts within the // same isolate, so we don't want to change the existing policy here, which // could be either kExplicit or kScoped depending on whether we're executing // from within a Node.js or a Blink entrypoint. Instead, the policy is // toggled to kExplicit when entering Node.js through UvRunOnce. is.policy = context->GetIsolate()->GetMicrotasksPolicy(); // We do not want to use Node.js' message listener as it interferes with // Blink's. is.flags &= ~node::IsolateSettingsFlags::MESSAGE_LISTENER_WITH_ERROR_LEVEL; // Isolate message listeners are additive (you can add multiple), so instead // we add an extra one here to ensure that the async hook stack is properly // cleared when errors are thrown. context->GetIsolate()->AddMessageListenerWithErrorLevel( ErrorMessageListener, v8::Isolate::kMessageError); // We do not want to use the promise rejection callback that Node.js uses, // because it does not send PromiseRejectionEvents to the global script // context. We need to use the one Blink already provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK; // We do not want to use the stack trace callback that Node.js uses, // because it relies on Node.js being aware of the current Context and // that's not always the case. We need to use the one Blink already // provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK; } node::SetIsolateUpForNode(context->GetIsolate(), is); context->GetIsolate()->SetHostImportModuleDynamicallyCallback( HostImportModuleDynamically); context->GetIsolate()->SetHostInitializeImportMetaObjectCallback( HostInitializeImportMetaObject); gin_helper::Dictionary process(context->GetIsolate(), env->process_object()); process.SetReadOnly("type", process_type); process.Set("resourcesPath", resources_path); // The path to helper app. base::FilePath helper_exec_path; base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); if (browser_env_ == BrowserEnvironment::kBrowser || browser_env_ == BrowserEnvironment::kRenderer) { if (on_app_code_ready) { process.SetMethod("appCodeLoaded", std::move(*on_app_code_ready)); } else { process.SetMethod("appCodeLoaded", base::BindRepeating(&NodeBindings::SetAppCodeLoaded, base::Unretained(this))); } } auto env_deleter = [isolate, isolate_data, context = v8::Global<v8::Context>{isolate, context}]( node::Environment* nenv) mutable { // When `isolate_data` was created above, a pointer to it was kept // in context's embedder_data[kElectronContextEmbedderDataIndex]. // Since we're about to free `isolate_data`, clear that entry v8::HandleScope handle_scope{isolate}; context.Get(isolate)->SetAlignedPointerInEmbedderData( kElectronContextEmbedderDataIndex, nullptr); context.Reset(); node::FreeEnvironment(nenv); node::FreeIsolateData(isolate_data); }; return {env, std::move(env_deleter)}; } std::shared_ptr<node::Environment> NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform, std::optional<base::RepeatingCallback<void()>> on_app_code_ready) { #if BUILDFLAG(IS_WIN) auto& electron_args = ElectronCommandLine::argv(); std::vector<std::string> args(electron_args.size()); std::transform(electron_args.cbegin(), electron_args.cend(), args.begin(), [](auto& a) { return base::WideToUTF8(a); }); #else auto args = ElectronCommandLine::argv(); #endif return CreateEnvironment(context, platform, args, {}, on_app_code_ready); } void NodeBindings::LoadEnvironment(node::Environment* env) { node::LoadEnvironment(env, node::StartExecutionCallback{}); gin_helper::EmitEvent(env->isolate(), env->process_object(), "loaded"); } void NodeBindings::PrepareEmbedThread() { // IOCP does not change for the process until the loop is recreated, // we ensure that there is only a single polling thread satisfying // the concurrency limit set from CreateIoCompletionPort call by // uv_loop_init for the lifetime of this process. // More background can be found at: // https://github.com/microsoft/vscode/issues/142786#issuecomment-1061673400 if (initialized_) return; // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, dummy_uv_handle_.get(), nullptr); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::StartPolling() { // Avoid calling UvRunOnce if the loop is already active, // otherwise it can lead to situations were the number of active // threads processing on IOCP is greater than the concurrency limit. if (initialized_) return; initialized_ = true; // The MessageLoop should have been created, remember the one in main thread. task_runner_ = base::SingleThreadTaskRunner::GetCurrentDefault(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::SetAppCodeLoaded() { app_code_loaded_ = true; } void NodeBindings::JoinAppCode() { // We can only "join" app code to the main thread in the browser process if (browser_env_ != BrowserEnvironment::kBrowser) { return; } auto* browser = Browser::Get(); node::Environment* env = uv_env(); if (!env) return; v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Pump the event loop until we get the signal that the app code has finished // loading while (!app_code_loaded_ && !browser->is_shutting_down()) { int r = uv_run(uv_loop_, UV_RUN_ONCE); if (r == 0) { base::RunLoop().QuitWhenIdle(); // Quit from uv. break; } } } void NodeBindings::UvRunOnce() { node::Environment* env = uv_env(); // When doing navigation without restarting renderer process, it may happen // that the node environment is destroyed but the message loop is still there. // In this case we should not run uv loop. if (!env) return; v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Node.js expects `kExplicit` microtasks policy and will run microtasks // checkpoints after every call into JavaScript. Since we use a different // policy in the renderer - switch to `kExplicit` and then drop back to the // previous policy value. v8::MicrotaskQueue* microtask_queue = env->context()->GetMicrotaskQueue(); auto old_policy = microtask_queue->microtasks_policy(); DCHECK_EQ(microtask_queue->GetMicrotasksScopeDepth(), 0); microtask_queue->set_microtasks_policy(v8::MicrotasksPolicy::kExplicit); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall"); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_END0("devtools.timeline", "FunctionCall"); microtask_queue->set_microtasks_policy(old_policy); if (r == 0) base::RunLoop().QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(task_runner_); task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce, weak_factory_.GetWeakPtr())); } void NodeBindings::WakeupEmbedThread() { uv_async_send(dummy_uv_handle_.get()); } // static void NodeBindings::EmbedThreadRunner(void* arg) { auto* self = static_cast<NodeBindings*>(arg); while (true) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); if (self->embed_closed_) break; // Wait for something to happen in uv loop. // Note that the PollEvents() is implemented by derived classes, so when // this class is being destructed the PollEvents() would not be available // anymore. Because of it we must make sure we only invoke PollEvents() // when this class is alive. self->PollEvents(); if (self->embed_closed_) break; // Deal with event in main thread. self->WakeupMainThread(); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,989
[Bug]: ESM cannot be used with contextIsolation: false import.meta.url
### Preflight Checklist - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [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 28.1.3 ### What operating system are you using? Windows ### Operating System Version 22631.3007 ### What arch are you using? x64 ### Last Known Working Electron version 28.1.3 ### Expected Behavior The rendering process renders normally. ### Actual Behavior In ESM, `import.meta.url` is not available in `preload` when I use `contextIsolation: false`,rendering process is unresponsive. ### Testcase Gist URL https://gist.github.com/f9cde94e621204933822255591f11011 ### Additional Information _No response_
https://github.com/electron/electron/issues/40989
https://github.com/electron/electron/pull/40993
4949c4c4e130e63b861adfc0093453c510579000
6803624576dc0086b83bdf50051a0dfd96f71401
2024-01-15T03:33:49Z
c++
2024-01-16T13:29:00Z
spec/esm-spec.ts
import { expect } from 'chai'; import * as cp from 'node:child_process'; import { BrowserWindow } from 'electron'; import * as fs from 'fs-extra'; import * as os from 'node:os'; import * as path from 'node:path'; import { pathToFileURL } from 'node:url'; const runFixture = async (appPath: string, args: string[] = []) => { const result = cp.spawn(process.execPath, [appPath, ...args], { stdio: 'pipe' }); const stdout: Buffer[] = []; const stderr: Buffer[] = []; result.stdout.on('data', (chunk) => stdout.push(chunk)); result.stderr.on('data', (chunk) => stderr.push(chunk)); const [code, signal] = await new Promise<[number | null, NodeJS.Signals | null]>((resolve) => { result.on('close', (code, signal) => { resolve([code, signal]); }); }); return { code, signal, stdout: Buffer.concat(stdout).toString().trim(), stderr: Buffer.concat(stderr).toString().trim() }; }; const fixturePath = path.resolve(__dirname, 'fixtures', 'esm'); describe('esm', () => { describe('main process', () => { it('should load an esm entrypoint', async () => { const result = await runFixture(path.resolve(fixturePath, 'entrypoint.mjs')); expect(result.code).to.equal(0); expect(result.stdout).to.equal('ESM Launch, ready: false'); }); it('should load an esm entrypoint based on type=module', async () => { const result = await runFixture(path.resolve(fixturePath, 'package')); expect(result.code).to.equal(0); expect(result.stdout).to.equal('ESM Package Launch, ready: false'); }); it('should wait for a top-level await before declaring the app ready', async () => { const result = await runFixture(path.resolve(fixturePath, 'top-level-await.mjs')); expect(result.code).to.equal(0); expect(result.stdout).to.equal('Top level await, ready: false'); }); it('should allow usage of pre-app-ready apis in top-level await', async () => { const result = await runFixture(path.resolve(fixturePath, 'pre-app-ready-apis.mjs')); expect(result.code).to.equal(0); }); it('should allow use of dynamic import', async () => { const result = await runFixture(path.resolve(fixturePath, 'dynamic.mjs')); expect(result.code).to.equal(0); expect(result.stdout).to.equal('Exit with app, ready: false'); }); }); describe('renderer process', () => { let w: BrowserWindow | null = null; const tempDirs: string[] = []; afterEach(async () => { if (w) w.close(); w = null; while (tempDirs.length) { await fs.remove(tempDirs.pop()!); } }); async function loadWindowWithPreload (preload: string, webPreferences: Electron.WebPreferences) { const tmpDir = await fs.mkdtemp(path.resolve(os.tmpdir(), 'e-spec-preload-')); tempDirs.push(tmpDir); const preloadPath = path.resolve(tmpDir, 'preload.mjs'); await fs.writeFile(preloadPath, preload); w = new BrowserWindow({ show: false, webPreferences: { ...webPreferences, preload: preloadPath } }); let error: Error | null = null; w.webContents.on('preload-error', (_, __, err) => { error = err; }); await w.loadFile(path.resolve(fixturePath, 'empty.html')); return [w.webContents, error] as [Electron.WebContents, Error | null]; } describe('nodeIntegration', () => { it('should support an esm entrypoint', async () => { const [webContents] = await loadWindowWithPreload('import { resolve } from "path"; window.resolvePath = resolve;', { nodeIntegration: true, sandbox: false, contextIsolation: false }); const exposedType = await webContents.executeJavaScript('typeof window.resolvePath'); expect(exposedType).to.equal('function'); }); it('should delay load until the ESM import chain is complete', async () => { const [webContents] = await loadWindowWithPreload(`import { resolve } from "path"; await new Promise(r => setTimeout(r, 500)); window.resolvePath = resolve;`, { nodeIntegration: true, sandbox: false, contextIsolation: false }); const exposedType = await webContents.executeJavaScript('typeof window.resolvePath'); expect(exposedType).to.equal('function'); }); it('should support a top-level await fetch blocking the page load', async () => { const [webContents] = await loadWindowWithPreload(` const r = await fetch("package/package.json"); window.packageJson = await r.json();`, { nodeIntegration: true, sandbox: false, contextIsolation: false }); const packageJson = await webContents.executeJavaScript('window.packageJson'); expect(packageJson).to.deep.equal(require('./fixtures/esm/package/package.json')); }); const hostsUrl = pathToFileURL(process.platform === 'win32' ? 'C:\\Windows\\System32\\drivers\\etc\\hosts' : '/etc/hosts'); describe('without context isolation', () => { it('should use blinks dynamic loader in the main world', async () => { const [webContents] = await loadWindowWithPreload('', { nodeIntegration: true, sandbox: false, contextIsolation: false }); let error: Error | null = null; try { await webContents.executeJavaScript(`import(${JSON.stringify(hostsUrl)})`); } catch (err) { error = err as Error; } expect(error).to.not.equal(null); // This is a blink specific error message expect(error?.message).to.include('Failed to fetch dynamically imported module'); }); }); describe('with context isolation', () => { let badFilePath = ''; beforeEach(async () => { badFilePath = path.resolve(path.resolve(os.tmpdir(), 'bad-file.badjs')); await fs.promises.writeFile(badFilePath, 'const foo = "bar";'); }); afterEach(async () => { await fs.promises.unlink(badFilePath); }); it('should use nodes esm dynamic loader in the isolated context', async () => { const [, preloadError] = await loadWindowWithPreload(`await import(${JSON.stringify((pathToFileURL(badFilePath)))})`, { nodeIntegration: true, sandbox: false, contextIsolation: true }); expect(preloadError).to.not.equal(null); // This is a node.js specific error message expect(preloadError!.toString()).to.include('Unknown file extension'); }); it('should use blinks dynamic loader in the main world', async () => { const [webContents] = await loadWindowWithPreload('', { nodeIntegration: true, sandbox: false, contextIsolation: true }); let error: Error | null = null; try { await webContents.executeJavaScript(`import(${JSON.stringify(hostsUrl)})`); } catch (err) { error = err as Error; } expect(error).to.not.equal(null); // This is a blink specific error message expect(error?.message).to.include('Failed to fetch dynamically imported module'); }); }); }); }); });
closed
electron/electron
https://github.com/electron/electron
40,989
[Bug]: ESM cannot be used with contextIsolation: false import.meta.url
### Preflight Checklist - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [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 28.1.3 ### What operating system are you using? Windows ### Operating System Version 22631.3007 ### What arch are you using? x64 ### Last Known Working Electron version 28.1.3 ### Expected Behavior The rendering process renders normally. ### Actual Behavior In ESM, `import.meta.url` is not available in `preload` when I use `contextIsolation: false`,rendering process is unresponsive. ### Testcase Gist URL https://gist.github.com/f9cde94e621204933822255591f11011 ### Additional Information _No response_
https://github.com/electron/electron/issues/40989
https://github.com/electron/electron/pull/40993
4949c4c4e130e63b861adfc0093453c510579000
6803624576dc0086b83bdf50051a0dfd96f71401
2024-01-15T03:33:49Z
c++
2024-01-16T13:29:00Z
spec/fixtures/esm/import-meta/index.html
closed
electron/electron
https://github.com/electron/electron
40,989
[Bug]: ESM cannot be used with contextIsolation: false import.meta.url
### Preflight Checklist - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [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 28.1.3 ### What operating system are you using? Windows ### Operating System Version 22631.3007 ### What arch are you using? x64 ### Last Known Working Electron version 28.1.3 ### Expected Behavior The rendering process renders normally. ### Actual Behavior In ESM, `import.meta.url` is not available in `preload` when I use `contextIsolation: false`,rendering process is unresponsive. ### Testcase Gist URL https://gist.github.com/f9cde94e621204933822255591f11011 ### Additional Information _No response_
https://github.com/electron/electron/issues/40989
https://github.com/electron/electron/pull/40993
4949c4c4e130e63b861adfc0093453c510579000
6803624576dc0086b83bdf50051a0dfd96f71401
2024-01-15T03:33:49Z
c++
2024-01-16T13:29:00Z
spec/fixtures/esm/import-meta/main.mjs
closed
electron/electron
https://github.com/electron/electron
40,989
[Bug]: ESM cannot be used with contextIsolation: false import.meta.url
### Preflight Checklist - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [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 28.1.3 ### What operating system are you using? Windows ### Operating System Version 22631.3007 ### What arch are you using? x64 ### Last Known Working Electron version 28.1.3 ### Expected Behavior The rendering process renders normally. ### Actual Behavior In ESM, `import.meta.url` is not available in `preload` when I use `contextIsolation: false`,rendering process is unresponsive. ### Testcase Gist URL https://gist.github.com/f9cde94e621204933822255591f11011 ### Additional Information _No response_
https://github.com/electron/electron/issues/40989
https://github.com/electron/electron/pull/40993
4949c4c4e130e63b861adfc0093453c510579000
6803624576dc0086b83bdf50051a0dfd96f71401
2024-01-15T03:33:49Z
c++
2024-01-16T13:29:00Z
spec/fixtures/esm/import-meta/package.json
closed
electron/electron
https://github.com/electron/electron
40,989
[Bug]: ESM cannot be used with contextIsolation: false import.meta.url
### Preflight Checklist - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [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 28.1.3 ### What operating system are you using? Windows ### Operating System Version 22631.3007 ### What arch are you using? x64 ### Last Known Working Electron version 28.1.3 ### Expected Behavior The rendering process renders normally. ### Actual Behavior In ESM, `import.meta.url` is not available in `preload` when I use `contextIsolation: false`,rendering process is unresponsive. ### Testcase Gist URL https://gist.github.com/f9cde94e621204933822255591f11011 ### Additional Information _No response_
https://github.com/electron/electron/issues/40989
https://github.com/electron/electron/pull/40993
4949c4c4e130e63b861adfc0093453c510579000
6803624576dc0086b83bdf50051a0dfd96f71401
2024-01-15T03:33:49Z
c++
2024-01-16T13:29:00Z
spec/fixtures/esm/import-meta/preload.mjs
closed
electron/electron
https://github.com/electron/electron
41,023
[Bug]: Exit Full Screen button is disabled starting from v28.1.2
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 28.1.2 ### What operating system are you using? macOS ### Operating System Version 14.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 28.1.0 ### Expected Behavior When the "enter full screen" button is clicked, the "exit full screen" button shouldn't be disabled ### Actual Behavior "exit full screen" button is disabled ![Screenshot 2024-01-17 at 10 48 51 AM](https://github.com/electron/electron/assets/24944765/14973ec4-9a78-46d1-baff-e8af0a534b1a) ### Testcase Gist URL _No response_ ### Additional Information Probably related to: fix: macOS maximize button shouldn't be disabled just because the window is non-fullscreenable #40896 As issue started from v28.1.2
https://github.com/electron/electron/issues/41023
https://github.com/electron/electron/pull/40994
021592200e4bcc0127ad6aebcee3caa578fb77f4
f97d8719e6071722c67d2a1ac371f80faee78b0e
2024-01-17T15:49:12Z
c++
2024-01-17T17:23:41Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/apple/scoped_cftyperef.h" #include "base/mac/mac_util.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } bool IsPanel(NSWindow* window) { return [window isKindOfClass:[NSPanel class]]; } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); widget()->SetNativeWindowProperty(kElectronNativeWindowKey, this); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this]; [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_]; [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { // If we're a panel window, we do not want to activate the app, // which enables Electron-apps to build Spotlight-like experiences. // // On macOS < Sonoma, "activateIgnoringOtherApps:NO" would not // activate apps if focusing a window that is inActive. That // changed with macOS Sonoma, which also deprecated // "activateIgnoringOtherApps". For the panel-specific usecase, // we can simply replace "activateIgnoringOtherApps:NO" with // "activate". For details on why we cannot replace all calls 1:1, // please see // https://github.com/electron/electron/pull/40307#issuecomment-1801976591. // // There's a slim chance we should have never called // activateIgnoringOtherApps, but we tried that many years ago // and saw weird focus bugs on other macOS versions. So, to make // this safe, we're gating by versions. if (@available(macOS 14.0, *)) { if (!IsPanel(window_)) { [[NSApplication sharedApplication] activate]; } else { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; } } else { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; } [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() const { 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; } set_wants_to_be_visible(true); // 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() { set_wants_to_be_visible(true); // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // If the window wants to be visible and has a parent, then the parent may // order it back in (in the period between orderOut: and close). set_wants_to_be_visible(false); DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() const { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() const { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() const { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() const { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow() { if (parent() && !is_modal()) { parent()->RemoveChildWindow(this); NativeWindow::SetParentWindow(nullptr); } } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { if (!static_cast<NativeWindowMac*>(child)->wants_to_be_visible()) continue; auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } void NativeWindowMac::SetFullScreen(bool fullscreen) { // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; if (![window_ toggleFullScreenMode:nil]) fullscreen_transition_state_ = FullScreenTransitionState::kNone; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() const { 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() const { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() const { 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::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { // Apply the size constraints to NSWindow. if (window_constraints.HasMinimumSize()) [window_ setMinSize:window_constraints.GetMinimumSize().ToCGSize()]; if (window_constraints.HasMaximumSize()) [window_ setMaxSize:window_constraints.GetMaximumSize().ToCGSize()]; NativeWindow::SetSizeConstraints(window_constraints); } 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()); } }; // Apply the size constraints to NSWindow. NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:0]; } else { ReorderChildWindowAbove(window_, nullptr); } } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); bool was_fullscreenable = IsFullScreenable(); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreen collection behavior as well as the maximize traffic // light in SetCanResize if resizability is false on macOS unless // the window is both resizable and maximizable. We want consistent // cross-platform behavior, so if resizability is disabled we disable // the maximize button and ensure fullscreenability matches user setting. SetCanResize(resizable); SetFullScreenable(was_fullscreenable); UpdateZoomButton(); } bool NativeWindowMac::IsResizable() const { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() const { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() const { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; UpdateZoomButton(); } bool NativeWindowMac::IsMaximizable() const { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::UpdateZoomButton() { [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:IsResizable() && (CanMaximize() || IsFullScreenable())]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); UpdateZoomButton(); } bool NativeWindowMac::IsFullScreenable() const { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() const { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() const { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() const { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() const { 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() const { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() const { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() const { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::apple::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor.get()]; } SkColor NativeWindowMac::GetBackgroundColor() const { 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() const { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() const { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() const { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() const { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() const { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() const { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[NSImageView alloc] init]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[ElectronProgressBar alloc] initWithFrame:frame]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() const { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); const int macos_version = base::mac::MacOSMajorVersion(); // Modal window corners are rounded on macOS >= 11 or higher if the user // hasn't passed noRoundedCorners. bool should_round_modal = !no_rounded_corner && (macos_version >= 11 ? true : !is_modal()); // Nonmodal window corners are rounded if they're frameless and the user // hasn't passed noRoundedCorners. bool should_round_nonmodal = !no_rounded_corner && !has_frame(); if (should_round_nonmodal || should_round_modal) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (macos_version >= 11) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NativeWindow::SetVibrancy(type); NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( std::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } std::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ window:this settings:std::move(items)]; [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::ShowAllTabs() { [window_ toggleTabOverview:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } std::optional<std::string> NativeWindowMac::GetTabbingIdentifier() const { if ([window_ tabbingMode] == NSWindowTabbingModeDisallowed) return std::nullopt; return base::SysNSStringToUTF8([window_ tabbingIdentifier]); } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_ = [[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]; [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:NO]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:YES]; } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { CALayer* background_layer = [[CALayer alloc] init]; [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(); // Set new parent window. if (new_parent) { new_parent->add_child_window(this); if (attach) new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } std::optional<gfx::Rect> NativeWindowMac::GetWindowControlsOverlayRect() { if (!titlebar_overlay_) return std::nullopt; // On macOS, when in fullscreen mode, window controls (the menu bar, title // bar, and toolbar) are attached to a separate NSView that slides down from // the top of the screen, independent of, and overlapping the WebContents. // Disable WCO when in fullscreen, because this space is inaccessible to // WebContents. https://crbug.com/915110. if (IsFullscreen()) return gfx::Rect(); if (buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); overlay.set_height([buttons_proxy_ useCustomHeight] ? titlebar_overlay_height() : NSHeight(buttons)); if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return std::nullopt; } // 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
40,800
[Bug]: Vibrancy top corners are white
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 26.3.0 ### What operating system are you using? macOS ### Operating System Version macOS sonoma 14.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 26.2.4 ### Expected Behavior Vibrancy works just as expected. <img width="1800" alt="image" src="https://github.com/electron/electron/assets/48829979/39b70992-6eac-4061-aa0b-163bbede235f"> ### Actual Behavior The vibrancy part of the window seems to be too small and not cover the title bar leaving tiny ugly white rounded corners behind in the top section. <img width="1800" alt="image" src="https://github.com/electron/electron/assets/48829979/b68f482f-7222-4a1e-9960-8604b60a6f22"> ### Testcase Gist URL https://gist.github.com/977c2ba87b683011bf1e093f6dd06d2f ### Additional Information I don't know if this issue would still persist in versions above 26 considering vibrancy has [broken entirely in versions 27 and above](https://github.com/electron/electron/issues/40799)
https://github.com/electron/electron/issues/40800
https://github.com/electron/electron/pull/41003
f97d8719e6071722c67d2a1ac371f80faee78b0e
df7f07a8af35a7b96c892374f0b51f3d432fc705
2023-12-20T19:57:45Z
c++
2024-01-18T08:59:54Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/apple/scoped_cftyperef.h" #include "base/mac/mac_util.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } bool IsPanel(NSWindow* window) { return [window isKindOfClass:[NSPanel class]]; } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); widget()->SetNativeWindowProperty(kElectronNativeWindowKey, this); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this]; [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_]; [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { // If we're a panel window, we do not want to activate the app, // which enables Electron-apps to build Spotlight-like experiences. // // On macOS < Sonoma, "activateIgnoringOtherApps:NO" would not // activate apps if focusing a window that is inActive. That // changed with macOS Sonoma, which also deprecated // "activateIgnoringOtherApps". For the panel-specific usecase, // we can simply replace "activateIgnoringOtherApps:NO" with // "activate". For details on why we cannot replace all calls 1:1, // please see // https://github.com/electron/electron/pull/40307#issuecomment-1801976591. // // There's a slim chance we should have never called // activateIgnoringOtherApps, but we tried that many years ago // and saw weird focus bugs on other macOS versions. So, to make // this safe, we're gating by versions. if (@available(macOS 14.0, *)) { if (!IsPanel(window_)) { [[NSApplication sharedApplication] activate]; } else { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; } } else { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; } [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() const { 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; } set_wants_to_be_visible(true); // 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() { set_wants_to_be_visible(true); // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // If the window wants to be visible and has a parent, then the parent may // order it back in (in the period between orderOut: and close). set_wants_to_be_visible(false); DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() const { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() const { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() const { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() const { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow() { if (parent() && !is_modal()) { parent()->RemoveChildWindow(this); NativeWindow::SetParentWindow(nullptr); } } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { if (!static_cast<NativeWindowMac*>(child)->wants_to_be_visible()) continue; auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } void NativeWindowMac::SetFullScreen(bool fullscreen) { // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; if (![window_ toggleFullScreenMode:nil]) fullscreen_transition_state_ = FullScreenTransitionState::kNone; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() const { 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() const { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() const { 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::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { // Apply the size constraints to NSWindow. if (window_constraints.HasMinimumSize()) [window_ setMinSize:window_constraints.GetMinimumSize().ToCGSize()]; if (window_constraints.HasMaximumSize()) [window_ setMaxSize:window_constraints.GetMaximumSize().ToCGSize()]; NativeWindow::SetSizeConstraints(window_constraints); } 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()); } }; // Apply the size constraints to NSWindow. NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:0]; } else { ReorderChildWindowAbove(window_, nullptr); } } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); bool was_fullscreenable = IsFullScreenable(); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreen collection behavior as well as the maximize traffic // light in SetCanResize if resizability is false on macOS unless // the window is both resizable and maximizable. We want consistent // cross-platform behavior, so if resizability is disabled we disable // the maximize button and ensure fullscreenability matches user setting. SetCanResize(resizable); SetFullScreenable(was_fullscreenable); UpdateZoomButton(); } bool NativeWindowMac::IsResizable() const { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() const { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() const { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; UpdateZoomButton(); } bool NativeWindowMac::IsMaximizable() const { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::UpdateZoomButton() { [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:HasStyleMask(NSWindowStyleMaskResizable) && (CanMaximize() || IsFullScreenable())]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); UpdateZoomButton(); } bool NativeWindowMac::IsFullScreenable() const { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() const { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() const { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() const { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() const { 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() const { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() const { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() const { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::apple::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor.get()]; } SkColor NativeWindowMac::GetBackgroundColor() const { 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() const { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() const { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() const { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() const { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() const { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() const { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[NSImageView alloc] init]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[ElectronProgressBar alloc] initWithFrame:frame]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() const { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); const int macos_version = base::mac::MacOSMajorVersion(); // Modal window corners are rounded on macOS >= 11 or higher if the user // hasn't passed noRoundedCorners. bool should_round_modal = !no_rounded_corner && (macos_version >= 11 ? true : !is_modal()); // Nonmodal window corners are rounded if they're frameless and the user // hasn't passed noRoundedCorners. bool should_round_nonmodal = !no_rounded_corner && !has_frame(); if (should_round_nonmodal || should_round_modal) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (macos_version >= 11) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NativeWindow::SetVibrancy(type); NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( std::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } std::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ window:this settings:std::move(items)]; [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::ShowAllTabs() { [window_ toggleTabOverview:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } std::optional<std::string> NativeWindowMac::GetTabbingIdentifier() const { if ([window_ tabbingMode] == NSWindowTabbingModeDisallowed) return std::nullopt; return base::SysNSStringToUTF8([window_ tabbingIdentifier]); } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_ = [[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]; [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:NO]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:YES]; } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { CALayer* background_layer = [[CALayer alloc] init]; [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(); // Set new parent window. if (new_parent) { new_parent->add_child_window(this); if (attach) new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } std::optional<gfx::Rect> NativeWindowMac::GetWindowControlsOverlayRect() { if (!titlebar_overlay_) return std::nullopt; // On macOS, when in fullscreen mode, window controls (the menu bar, title // bar, and toolbar) are attached to a separate NSView that slides down from // the top of the screen, independent of, and overlapping the WebContents. // Disable WCO when in fullscreen, because this space is inaccessible to // WebContents. https://crbug.com/915110. if (IsFullscreen()) return gfx::Rect(); if (buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); overlay.set_height([buttons_proxy_ useCustomHeight] ? titlebar_overlay_height() : NSHeight(buttons)); if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return std::nullopt; } // 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
40,676
[Bug]: Crash showMessageBox, NSRangeException - index 0 beyond bounds for empty NSArray
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 26.6.2 ### What operating system are you using? macOS ### Operating System Version Ventura ### What arch are you using? arm64/x64 ### Last Known Working Electron version Unknown ### Expected Behavior Not crash ### Actual Behavior Crash ### Testcase Gist URL _No response_ ### Additional Information I'm experiencing a crash in my production app. This definitely feels like a regression in Electron, because my app has been stable around this existing feature logic. Suspect code (sync and async have same behavior): ``` dialog.showMessageBoxSync(homeWindow.mainWindow, { type: 'info', defaultId: 0, title: 'License Installed', message: 'Your license has been installed. Thank you for using APP.' }); ``` ``` 2023-12-01 10:01:39.697 Electron[92515:6921708] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray' *** First throw call stack: ( 0 CoreFoundation 0x000000019b98f154 __exceptionPreprocess + 176 1 libobjc.A.dylib 0x000000019b4ae4d4 objc_exception_throw + 60 2 CoreFoundation 0x000000019b9bc1b4 CFArrayApply + 0 3 Electron Framework 0x0000000108aa4734 _ZN4heap4base5Stack18ClearStackSegmentsEv + 342460 4 Electron Framework 0x0000000108aa48ec _ZN4heap4base5Stack18ClearStackSegmentsEv + 342900 5 Electron Framework 0x000000010891b6c8 _ZNK2v88internal20CodeCommentsIterator4sizeEv + 128336 6 Electron Framework 0x000000010891c760 _ZNK2v88internal20CodeCommentsIterator4sizeEv + 132584 7 Electron Framework 0x000000010891c64c _ZNK2v88internal20CodeCommentsIterator4sizeEv + 132308 8 ??? 0x0000000157e4ea50 0x0 + 5769587280 9 ??? 0x0000000157e4ce7c 0x0 + 5769580156 10 ??? 0x0000000157e4ce7c 0x0 + 5769580156 11 ??? 0x0000000157e4ce7c 0x0 + 5769580156 12 ??? 0x00000001504f10d4 0x0 + 5642326228 13 ??? 0x00000001504f20cc 0x0 + 5642330316 14 ??? 0x0000000157e4aca8 0x0 + 5769571496 15 ??? 0x0000000157e4a998 0x0 + 5769570712 16 Electron Framework 0x000000010995d250 _ZN2v88internal9Execution4CallEPNS0_7IsolateENS0_6HandleINS0_6ObjectEEES6_iPS6_ + 444 17 Electron Framework 0x0000000109852d60 _ZN2v88Function4CallENS_5LocalINS_7ContextEEENS1_INS_5ValueEEEiPS5_ + 520 18 Electron Framework 0x000000010ecd8f08 _ZN4node16EmitAsyncDestroyEPNS_11EnvironmentENS_13async_contextE + 304248 19 Electron Framework 0x00000001088c5a9c uv_timer_get_due_in + 152 20 Electron Framework 0x00000001088c89b8 uv_run + 636 21 Electron Framework 0x0000000108a4ee4c _ZN4node24FreeArrayBufferAllocatorEPNS_20ArrayBufferAllocatorE + 14612 22 Electron Framework 0x000000010b687bd4 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 17950948 23 Electron Framework 0x000000010b6a0670 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 18051968 24 Electron Framework 0x0000000108adae1c _ZN8electron5fuses45IsLoadBrowserProcessSpecificV8SnapshotEnabledEv + 90896 25 Electron Framework 0x0000000108818010 Electron Framework + 1769488 26 Electron Framework 0x0000000108ada4dc _ZN8electron5fuses45IsLoadBrowserProcessSpecificV8SnapshotEnabledEv + 88528 27 CoreFoundation 0x000000019b91663c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 28 CoreFoundation 0x000000019b9165d0 __CFRunLoopDoSource0 + 176 29 CoreFoundation 0x000000019b916340 __CFRunLoopDoSources0 + 244 30 CoreFoundation 0x000000019b914f48 __CFRunLoopRun + 828 31 CoreFoundation 0x000000019b9144b8 CFRunLoopRunSpecific + 612 32 HIToolbox 0x00000001a515ec40 RunCurrentEventLoopInMode + 292 33 HIToolbox 0x00000001a515e8d0 ReceiveNextEventCommon + 220 34 HIToolbox 0x00000001a515e7d4 _BlockUntilNextEventMatchingListInModeWithFilter + 76 35 AppKit 0x000000019eb35d44 _DPSNextEvent + 636 36 AppKit 0x000000019eb34ee0 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716 37 AppKit 0x000000019eb29344 -[NSApplication run] + 464 38 Electron Framework 0x0000000108adba88 _ZN8electron5fuses45IsLoadBrowserProcessSpecificV8SnapshotEnabledEv + 94076 39 Electron Framework 0x0000000108ad9f58 _ZN8electron5fuses45IsLoadBrowserProcessSpecificV8SnapshotEnabledEv + 87116 40 Electron Framework 0x000000010b6a10a8 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 18054584 41 Electron Framework 0x000000010b66d62c _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 17843004 42 Electron Framework 0x000000010a90687c _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3790220 43 Electron Framework 0x000000010a908188 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3796632 44 Electron Framework 0x000000010a904508 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3781144 45 Electron Framework 0x0000000108bb8090 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 13728 46 Electron Framework 0x0000000108bb8fac _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 17596 47 Electron Framework 0x0000000108bb8dfc _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 17164 48 Electron Framework 0x0000000108bb797c _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 11916 49 Electron Framework 0x0000000108bb7a8c _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 12188 50 Electron Framework 0x00000001088d9c10 ElectronMain + 128 51 dyld 0x000000019b4dff28 start + 2236 ) ```
https://github.com/electron/electron/issues/40676
https://github.com/electron/electron/pull/40996
df7f07a8af35a7b96c892374f0b51f3d432fc705
7e6fb97a2f4659d1416300a1c38f7294af081fb2
2023-12-01T16:05:56Z
c++
2024-01-18T12:21:15Z
shell/browser/ui/message_box_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/ui/message_box.h" #include <string> #include <utility> #include <vector> #import <Cocoa/Cocoa.h> #include "base/containers/contains.h" #include "base/containers/flat_map.h" #include "base/functional/callback.h" #include "base/mac/mac_util.h" #include "base/no_destructor.h" #include "base/strings/sys_string_conversions.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "shell/browser/native_window.h" #include "skia/ext/skia_utils_mac.h" #include "ui/gfx/image/image_skia.h" namespace electron { MessageBoxSettings::MessageBoxSettings() = default; MessageBoxSettings::MessageBoxSettings(const MessageBoxSettings&) = default; MessageBoxSettings::~MessageBoxSettings() = default; namespace { // <ID, messageBox> map base::flat_map<int, NSAlert*>& GetDialogsMap() { static base::NoDestructor<base::flat_map<int, NSAlert*>> dialogs; return *dialogs; } NSAlert* CreateNSAlert(const MessageBoxSettings& settings) { // Ignore the title; it's the window title on other platforms and ignorable. NSAlert* alert = [[NSAlert alloc] init]; [alert setMessageText:base::SysUTF8ToNSString(settings.message)]; [alert setInformativeText:base::SysUTF8ToNSString(settings.detail)]; switch (settings.type) { case MessageBoxType::kInformation: alert.alertStyle = NSAlertStyleInformational; break; case MessageBoxType::kWarning: case MessageBoxType::kError: // NSWarningAlertStyle shows the app icon while NSAlertStyleCritical // shows a warning icon with an app icon badge. Since there is no // error variant, lets just use NSAlertStyleCritical. alert.alertStyle = NSAlertStyleCritical; break; default: break; } for (size_t i = 0; i < settings.buttons.size(); ++i) { NSString* title = base::SysUTF8ToNSString(settings.buttons[i]); // An empty title causes crash on macOS. if (settings.buttons[i].empty()) title = @"(empty)"; NSButton* button = [alert addButtonWithTitle:title]; [button setTag:i]; } NSArray* ns_buttons = [alert buttons]; int button_count = static_cast<int>([ns_buttons count]); if (settings.default_id >= 0 && settings.default_id < button_count) { // The first button added gets set as the default selected, so remove // that and set the button @ default_id to be default. [[ns_buttons objectAtIndex:0] setKeyEquivalent:@""]; [[ns_buttons objectAtIndex:settings.default_id] setKeyEquivalent:@"\r"]; } // Bind cancel id button to escape key if there is more than one button if (button_count > 1 && settings.cancel_id >= 0 && settings.cancel_id < button_count) { [[ns_buttons objectAtIndex:settings.cancel_id] setKeyEquivalent:@"\e"]; } // TODO(@codebytere): This behavior violates HIG & should be deprecated. if (settings.cancel_id >= 0 && settings.cancel_id == settings.default_id) { [[ns_buttons objectAtIndex:settings.default_id] highlight:YES]; } if (!settings.checkbox_label.empty()) { alert.showsSuppressionButton = YES; alert.suppressionButton.title = base::SysUTF8ToNSString(settings.checkbox_label); alert.suppressionButton.state = settings.checkbox_checked ? NSControlStateValueOn : NSControlStateValueOff; } if (!settings.icon.isNull()) { NSImage* image = skia::SkBitmapToNSImage(*settings.icon.bitmap()); [alert setIcon:image]; } if (settings.text_width > 0) { NSRect rect = NSMakeRect(0, 0, settings.text_width, 0); NSView* accessoryView = [[NSView alloc] initWithFrame:rect]; [alert setAccessoryView:accessoryView]; } return alert; } } // namespace int ShowMessageBoxSync(const MessageBoxSettings& settings) { NSAlert* alert(CreateNSAlert(settings)); // Use runModal for synchronous alert without parent, since we don't have a // window to wait for. Also use it when window is provided but it is not // shown as it would be impossible to dismiss the alert if it is connected // to invisible window (see #22671). if (!settings.parent_window || !settings.parent_window->IsVisible()) return [alert runModal]; __block int ret_code = -1; NSWindow* window = settings.parent_window->GetNativeWindow().GetNativeNSWindow(); [alert beginSheetModalForWindow:window completionHandler:^(NSModalResponse response) { ret_code = response; [NSApp stopModal]; }]; [NSApp runModalForWindow:window]; return ret_code; } void ShowMessageBox(const MessageBoxSettings& settings, MessageBoxCallback callback) { NSAlert* alert = CreateNSAlert(settings); // Use runModal for synchronous alert without parent, since we don't have a // window to wait for. if (!settings.parent_window) { int ret = [alert runModal]; std::move(callback).Run( ret, alert.suppressionButton.state == NSControlStateValueOn); } else { if (settings.id) { if (base::Contains(GetDialogsMap(), *settings.id)) CloseMessageBox(*settings.id); GetDialogsMap()[*settings.id] = alert; } NSWindow* window = settings.parent_window ? settings.parent_window->GetNativeWindow().GetNativeNSWindow() : nil; // Duplicate the callback object here since c is a reference and gcd would // only store the pointer, by duplication we can force gcd to store a copy. __block MessageBoxCallback callback_ = std::move(callback); __block std::optional<int> id = std::move(settings.id); __block int cancel_id = settings.cancel_id; auto handler = ^(NSModalResponse response) { if (id) GetDialogsMap().erase(*id); // When the alert is cancelled programmatically, the response would be // something like -1000. This currently only happens when users call // CloseMessageBox API, and we should return cancelId as result. if (response < 0) response = cancel_id; bool suppressed = alert.suppressionButton.state == NSControlStateValueOn; // The completionHandler runs inside a transaction commit, and we should // not do any runModal inside it. However since we can not control what // users will run in the callback, we have to delay running the callback // until next tick, otherwise crash like this may happen: // https://github.com/electron/electron/issues/26884 content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(std::move(callback_), response, suppressed)); }; [alert beginSheetModalForWindow:window completionHandler:handler]; } } void CloseMessageBox(int id) { auto it = GetDialogsMap().find(id); if (it == GetDialogsMap().end()) { LOG(ERROR) << "CloseMessageBox called with nonexistent ID"; return; } [NSApp endSheet:it->second.window]; } void ShowErrorBox(const std::u16string& title, const std::u16string& content) { NSAlert* alert = [[NSAlert alloc] init]; [alert setMessageText:base::SysUTF16ToNSString(title)]; [alert setInformativeText:base::SysUTF16ToNSString(content)]; [alert setAlertStyle:NSAlertStyleCritical]; [alert runModal]; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,676
[Bug]: Crash showMessageBox, NSRangeException - index 0 beyond bounds for empty NSArray
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 26.6.2 ### What operating system are you using? macOS ### Operating System Version Ventura ### What arch are you using? arm64/x64 ### Last Known Working Electron version Unknown ### Expected Behavior Not crash ### Actual Behavior Crash ### Testcase Gist URL _No response_ ### Additional Information I'm experiencing a crash in my production app. This definitely feels like a regression in Electron, because my app has been stable around this existing feature logic. Suspect code (sync and async have same behavior): ``` dialog.showMessageBoxSync(homeWindow.mainWindow, { type: 'info', defaultId: 0, title: 'License Installed', message: 'Your license has been installed. Thank you for using APP.' }); ``` ``` 2023-12-01 10:01:39.697 Electron[92515:6921708] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray' *** First throw call stack: ( 0 CoreFoundation 0x000000019b98f154 __exceptionPreprocess + 176 1 libobjc.A.dylib 0x000000019b4ae4d4 objc_exception_throw + 60 2 CoreFoundation 0x000000019b9bc1b4 CFArrayApply + 0 3 Electron Framework 0x0000000108aa4734 _ZN4heap4base5Stack18ClearStackSegmentsEv + 342460 4 Electron Framework 0x0000000108aa48ec _ZN4heap4base5Stack18ClearStackSegmentsEv + 342900 5 Electron Framework 0x000000010891b6c8 _ZNK2v88internal20CodeCommentsIterator4sizeEv + 128336 6 Electron Framework 0x000000010891c760 _ZNK2v88internal20CodeCommentsIterator4sizeEv + 132584 7 Electron Framework 0x000000010891c64c _ZNK2v88internal20CodeCommentsIterator4sizeEv + 132308 8 ??? 0x0000000157e4ea50 0x0 + 5769587280 9 ??? 0x0000000157e4ce7c 0x0 + 5769580156 10 ??? 0x0000000157e4ce7c 0x0 + 5769580156 11 ??? 0x0000000157e4ce7c 0x0 + 5769580156 12 ??? 0x00000001504f10d4 0x0 + 5642326228 13 ??? 0x00000001504f20cc 0x0 + 5642330316 14 ??? 0x0000000157e4aca8 0x0 + 5769571496 15 ??? 0x0000000157e4a998 0x0 + 5769570712 16 Electron Framework 0x000000010995d250 _ZN2v88internal9Execution4CallEPNS0_7IsolateENS0_6HandleINS0_6ObjectEEES6_iPS6_ + 444 17 Electron Framework 0x0000000109852d60 _ZN2v88Function4CallENS_5LocalINS_7ContextEEENS1_INS_5ValueEEEiPS5_ + 520 18 Electron Framework 0x000000010ecd8f08 _ZN4node16EmitAsyncDestroyEPNS_11EnvironmentENS_13async_contextE + 304248 19 Electron Framework 0x00000001088c5a9c uv_timer_get_due_in + 152 20 Electron Framework 0x00000001088c89b8 uv_run + 636 21 Electron Framework 0x0000000108a4ee4c _ZN4node24FreeArrayBufferAllocatorEPNS_20ArrayBufferAllocatorE + 14612 22 Electron Framework 0x000000010b687bd4 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 17950948 23 Electron Framework 0x000000010b6a0670 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 18051968 24 Electron Framework 0x0000000108adae1c _ZN8electron5fuses45IsLoadBrowserProcessSpecificV8SnapshotEnabledEv + 90896 25 Electron Framework 0x0000000108818010 Electron Framework + 1769488 26 Electron Framework 0x0000000108ada4dc _ZN8electron5fuses45IsLoadBrowserProcessSpecificV8SnapshotEnabledEv + 88528 27 CoreFoundation 0x000000019b91663c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 28 CoreFoundation 0x000000019b9165d0 __CFRunLoopDoSource0 + 176 29 CoreFoundation 0x000000019b916340 __CFRunLoopDoSources0 + 244 30 CoreFoundation 0x000000019b914f48 __CFRunLoopRun + 828 31 CoreFoundation 0x000000019b9144b8 CFRunLoopRunSpecific + 612 32 HIToolbox 0x00000001a515ec40 RunCurrentEventLoopInMode + 292 33 HIToolbox 0x00000001a515e8d0 ReceiveNextEventCommon + 220 34 HIToolbox 0x00000001a515e7d4 _BlockUntilNextEventMatchingListInModeWithFilter + 76 35 AppKit 0x000000019eb35d44 _DPSNextEvent + 636 36 AppKit 0x000000019eb34ee0 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716 37 AppKit 0x000000019eb29344 -[NSApplication run] + 464 38 Electron Framework 0x0000000108adba88 _ZN8electron5fuses45IsLoadBrowserProcessSpecificV8SnapshotEnabledEv + 94076 39 Electron Framework 0x0000000108ad9f58 _ZN8electron5fuses45IsLoadBrowserProcessSpecificV8SnapshotEnabledEv + 87116 40 Electron Framework 0x000000010b6a10a8 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 18054584 41 Electron Framework 0x000000010b66d62c _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 17843004 42 Electron Framework 0x000000010a90687c _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3790220 43 Electron Framework 0x000000010a908188 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3796632 44 Electron Framework 0x000000010a904508 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3781144 45 Electron Framework 0x0000000108bb8090 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 13728 46 Electron Framework 0x0000000108bb8fac _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 17596 47 Electron Framework 0x0000000108bb8dfc _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 17164 48 Electron Framework 0x0000000108bb797c _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 11916 49 Electron Framework 0x0000000108bb7a8c _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 12188 50 Electron Framework 0x00000001088d9c10 ElectronMain + 128 51 dyld 0x000000019b4dff28 start + 2236 ) ```
https://github.com/electron/electron/issues/40676
https://github.com/electron/electron/pull/40996
df7f07a8af35a7b96c892374f0b51f3d432fc705
7e6fb97a2f4659d1416300a1c38f7294af081fb2
2023-12-01T16:05:56Z
c++
2024-01-18T12:21:15Z
spec/api-dialog-spec.ts
import { expect } from 'chai'; import { dialog, BrowserWindow } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import { ifit } from './lib/spec-helpers'; import { setTimeout } from 'node:timers/promises'; describe('dialog module', () => { describe('showOpenDialog', () => { afterEach(closeAllWindows); ifit(process.platform !== 'win32')('should not throw for valid cases', () => { expect(() => { dialog.showOpenDialog({ title: 'i am title' }); }).to.not.throw(); expect(() => { const w = new BrowserWindow(); dialog.showOpenDialog(w, { title: 'i am title' }); }).to.not.throw(); }); it('throws errors when the options are invalid', () => { expect(() => { dialog.showOpenDialog({ properties: false as any }); }).to.throw(/Properties must be an array/); expect(() => { dialog.showOpenDialog({ title: 300 as any }); }).to.throw(/Title must be a string/); expect(() => { dialog.showOpenDialog({ buttonLabel: [] as any }); }).to.throw(/Button label must be a string/); expect(() => { dialog.showOpenDialog({ defaultPath: {} as any }); }).to.throw(/Default path must be a string/); expect(() => { dialog.showOpenDialog({ message: {} as any }); }).to.throw(/Message must be a string/); }); }); describe('showSaveDialog', () => { afterEach(closeAllWindows); ifit(process.platform !== 'win32')('should not throw for valid cases', () => { expect(() => { dialog.showSaveDialog({ title: 'i am title' }); }).to.not.throw(); expect(() => { const w = new BrowserWindow(); dialog.showSaveDialog(w, { title: 'i am title' }); }).to.not.throw(); }); it('throws errors when the options are invalid', () => { expect(() => { dialog.showSaveDialog({ title: 300 as any }); }).to.throw(/Title must be a string/); expect(() => { dialog.showSaveDialog({ buttonLabel: [] as any }); }).to.throw(/Button label must be a string/); expect(() => { dialog.showSaveDialog({ defaultPath: {} as any }); }).to.throw(/Default path must be a string/); expect(() => { dialog.showSaveDialog({ message: {} as any }); }).to.throw(/Message must be a string/); expect(() => { dialog.showSaveDialog({ nameFieldLabel: {} as any }); }).to.throw(/Name field label must be a string/); }); }); describe('showMessageBox', () => { afterEach(closeAllWindows); // parentless message boxes are synchronous on macOS // dangling message boxes on windows cause a DCHECK: https://source.chromium.org/chromium/chromium/src/+/main:base/win/message_window.cc;drc=7faa4bf236a866d007dc5672c9ce42660e67a6a6;l=68 ifit(process.platform !== 'darwin' && process.platform !== 'win32')('should not throw for a parentless message box', () => { expect(() => { dialog.showMessageBox({ message: 'i am message' }); }).to.not.throw(); }); ifit(process.platform !== 'win32')('should not throw for valid cases', () => { expect(() => { const w = new BrowserWindow(); dialog.showMessageBox(w, { message: 'i am message' }); }).to.not.throw(); }); it('throws errors when the options are invalid', () => { expect(() => { dialog.showMessageBox(undefined as any, { type: 'not-a-valid-type' as any, message: '' }); }).to.throw(/Invalid message box type/); expect(() => { dialog.showMessageBox(null as any, { buttons: false as any, message: '' }); }).to.throw(/Buttons must be an array/); expect(() => { dialog.showMessageBox({ title: 300 as any, message: '' }); }).to.throw(/Title must be a string/); expect(() => { dialog.showMessageBox({ message: [] as any }); }).to.throw(/Message must be a string/); expect(() => { dialog.showMessageBox({ detail: 3.14 as any, message: '' }); }).to.throw(/Detail must be a string/); expect(() => { dialog.showMessageBox({ checkboxLabel: false as any, message: '' }); }).to.throw(/checkboxLabel must be a string/); }); }); describe('showMessageBox with signal', () => { afterEach(closeAllWindows); it('closes message box immediately', async () => { const controller = new AbortController(); const signal = controller.signal; const w = new BrowserWindow(); const p = dialog.showMessageBox(w, { signal, message: 'i am message' }); controller.abort(); const result = await p; expect(result.response).to.equal(0); }); it('closes message box after a while', async () => { const controller = new AbortController(); const signal = controller.signal; const w = new BrowserWindow(); const p = dialog.showMessageBox(w, { signal, message: 'i am message' }); await setTimeout(500); controller.abort(); const result = await p; expect(result.response).to.equal(0); }); it('cancels message box', async () => { const controller = new AbortController(); const signal = controller.signal; const w = new BrowserWindow(); const p = dialog.showMessageBox(w, { signal, message: 'i am message', buttons: ['OK', 'Cancel'], cancelId: 1 }); controller.abort(); const result = await p; expect(result.response).to.equal(1); }); it('cancels message box after a while', async () => { const controller = new AbortController(); const signal = controller.signal; const w = new BrowserWindow(); const p = dialog.showMessageBox(w, { signal, message: 'i am message', buttons: ['OK', 'Cancel'], cancelId: 1 }); await setTimeout(500); controller.abort(); const result = await p; expect(result.response).to.equal(1); }); }); describe('showErrorBox', () => { it('throws errors when the options are invalid', () => { expect(() => { (dialog.showErrorBox as any)(); }).to.throw(/Insufficient number of arguments/); expect(() => { dialog.showErrorBox(3 as any, 'four'); }).to.throw(/Error processing argument at index 0/); expect(() => { dialog.showErrorBox('three', 4 as any); }).to.throw(/Error processing argument at index 1/); }); }); describe('showCertificateTrustDialog', () => { it('throws errors when the options are invalid', () => { expect(() => { (dialog.showCertificateTrustDialog as any)(); }).to.throw(/options must be an object/); expect(() => { dialog.showCertificateTrustDialog({} as any); }).to.throw(/certificate must be an object/); expect(() => { dialog.showCertificateTrustDialog({ certificate: {} as any, message: false as any }); }).to.throw(/message must be a string/); }); }); });
closed
electron/electron
https://github.com/electron/electron
40,985
[Bug]: `-webkit-app-region: drag` doesn't 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 29.0.0-alpha.9, 29.0.0-alpha.8 ### What operating system are you using? Windows ### Operating System Version Windows 11 23H2 (22631) ### What arch are you using? x64 ### Last Known Working Electron version 29.0.0-alpha.7 ### Expected Behavior If `-webkit-app-region: drag` was used, it should be possible to click on the region and drag the `Window`. ### Actual Behavior It will behave as if the property is not applied. ### Testcase Gist URL https://gist.github.com/5e1d4f4331881ef8c608b8ab61cef9ac ### Additional Information _No response_
https://github.com/electron/electron/issues/40985
https://github.com/electron/electron/pull/41030
a05bfd332d1553aaa096f4a63d60242d46fac98f
3e6a038af77cc01e16bf139dc68dd8eb45483c7b
2024-01-13T01:50:06Z
c++
2024-01-25T00:12:54Z
patches/chromium/.patches
build_gn.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_avoid_private_macos_api_usage.patch.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch upload_list_add_loadsync_method.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch process_singleton.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch add_maximized_parameter_to_linuxui_getwindowframeprovider.patch add_electron_deps_to_license_credits_file.patch fix_crash_loading_non-standard_schemes_in_iframes.patch create_browser_v8_snapshot_file_name_fuse.patch feat_configure_launch_options_for_service_process.patch feat_ensure_mas_builds_of_the_same_application_can_use_safestorage.patch fix_on-screen-keyboard_hides_on_input_blur_in_webview.patch preconnect_manager.patch fix_remove_caption-removing_style_call.patch build_allow_electron_to_use_exec_script.patch chore_introduce_blocking_api_for_electron.patch chore_patch_out_partition_attribute_dcheck_for_webviews.patch chore_patch_out_profile_methods_in_profile_selections_cc.patch add_gin_converter_support_for_arraybufferview.patch chore_defer_usb_service_getdevices_request_until_usb_service_is.patch refactor_expose_hostimportmoduledynamically_and.patch feat_expose_documentloader_setdefersloading_on_webdocumentloader.patch fix_remove_profiles_from_spellcheck_service.patch chore_patch_out_profile_methods_in_chrome_browser_pdf.patch chore_patch_out_profile_methods_in_titlebar_config.patch fix_disabling_background_throttling_in_compositor.patch fix_select_the_first_menu_item_when_opened_via_keyboard.patch fix_return_v8_value_from_localframe_requestexecutescript.patch fix_harden_blink_scriptstate_maybefrom.patch chore_add_buildflag_guard_around_new_include.patch fix_use_delegated_generic_capturer_when_available.patch build_remove_ent_content_analysis_assert.patch expose_webblob_path_to_allow_embedders_to_get_file_paths.patch fix_move_autopipsettingshelper_behind_branding_buildflag.patch revert_remove_the_allowaggressivethrottlingwithwebsocket_feature.patch fix_activate_background_material_on_windows.patch feat_allow_passing_of_objecttemplate_to_objecttemplatebuilder.patch chore_remove_check_is_test_on_script_injection_tracker.patch fix_restore_original_resize_performance_on_macos.patch feat_allow_code_cache_in_custom_schemes.patch enable_partition_alloc_ref_count_size.patch build_run_reclient_cfg_generator_after_chrome.patch
closed
electron/electron
https://github.com/electron/electron
40,985
[Bug]: `-webkit-app-region: drag` doesn't 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 29.0.0-alpha.9, 29.0.0-alpha.8 ### What operating system are you using? Windows ### Operating System Version Windows 11 23H2 (22631) ### What arch are you using? x64 ### Last Known Working Electron version 29.0.0-alpha.7 ### Expected Behavior If `-webkit-app-region: drag` was used, it should be possible to click on the region and drag the `Window`. ### Actual Behavior It will behave as if the property is not applied. ### Testcase Gist URL https://gist.github.com/5e1d4f4331881ef8c608b8ab61cef9ac ### Additional Information _No response_
https://github.com/electron/electron/issues/40985
https://github.com/electron/electron/pull/41030
a05bfd332d1553aaa096f4a63d60242d46fac98f
3e6a038af77cc01e16bf139dc68dd8eb45483c7b
2024-01-13T01:50:06Z
c++
2024-01-25T00:12:54Z
patches/chromium/fix_drag_regions_not_working_after_navigation_in_wco_app.patch
closed
electron/electron
https://github.com/electron/electron
40,985
[Bug]: `-webkit-app-region: drag` doesn't 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 29.0.0-alpha.9, 29.0.0-alpha.8 ### What operating system are you using? Windows ### Operating System Version Windows 11 23H2 (22631) ### What arch are you using? x64 ### Last Known Working Electron version 29.0.0-alpha.7 ### Expected Behavior If `-webkit-app-region: drag` was used, it should be possible to click on the region and drag the `Window`. ### Actual Behavior It will behave as if the property is not applied. ### Testcase Gist URL https://gist.github.com/5e1d4f4331881ef8c608b8ab61cef9ac ### Additional Information _No response_
https://github.com/electron/electron/issues/40985
https://github.com/electron/electron/pull/41030
a05bfd332d1553aaa096f4a63d60242d46fac98f
3e6a038af77cc01e16bf139dc68dd8eb45483c7b
2024-01-13T01:50:06Z
c++
2024-01-25T00:12:54Z
shell/renderer/electron_render_frame_observer.cc
// Copyright (c) 2017 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/renderer/electron_render_frame_observer.h" #include <utility> #include <vector> #include "base/command_line.h" #include "base/memory/ref_counted_memory.h" #include "base/trace_event/trace_event.h" #include "content/public/renderer/render_frame.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "ipc/ipc_message_macros.h" #include "net/base/net_module.h" #include "net/grit/net_resources.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/options_switches.h" #include "shell/common/world_ids.h" #include "shell/renderer/renderer_client_base.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/web_preferences/web_preferences.h" #include "third_party/blink/public/platform/web_isolated_world_info.h" #include "third_party/blink/public/web/blink.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_draggable_region.h" #include "third_party/blink/public/web/web_element.h" #include "third_party/blink/public/web/web_local_frame.h" #include "third_party/blink/public/web/web_script_source.h" #include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" // nogncheck #include "ui/base/resource/resource_bundle.h" namespace electron { namespace { scoped_refptr<base::RefCountedMemory> NetResourceProvider(int key) { if (key == IDR_DIR_HEADER_HTML) { return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes( IDR_DIR_HEADER_HTML); } return nullptr; } } // namespace ElectronRenderFrameObserver::ElectronRenderFrameObserver( content::RenderFrame* frame, RendererClientBase* renderer_client) : content::RenderFrameObserver(frame), render_frame_(frame), renderer_client_(renderer_client) { // Initialise resource for directory listing. net::NetModule::SetResourceProvider(NetResourceProvider); } void ElectronRenderFrameObserver::DidClearWindowObject() { // Do a delayed Node.js initialization for child window. // Check DidInstallConditionalFeatures below for the background. auto* web_frame = static_cast<blink::WebLocalFrameImpl*>(render_frame_->GetWebFrame()); if (has_delayed_node_initialization_ && !web_frame->IsOnInitialEmptyDocument()) { v8::Isolate* isolate = blink::MainThreadIsolate(); v8::HandleScope handle_scope(isolate); v8::Handle<v8::Context> context = web_frame->MainWorldScriptContext(); v8::MicrotasksScope microtasks_scope( isolate, context->GetMicrotaskQueue(), v8::MicrotasksScope::kDoNotRunMicrotasks); v8::Context::Scope context_scope(context); // DidClearWindowObject only emits for the main world. DidInstallConditionalFeatures(context, MAIN_WORLD_ID); } renderer_client_->DidClearWindowObject(render_frame_); } void ElectronRenderFrameObserver::DidInstallConditionalFeatures( v8::Handle<v8::Context> context, int world_id) { // When a child window is created with window.open, its WebPreferences will // be copied from its parent, and Chromium will initialize JS context in it // immediately. // Normally the WebPreferences is overridden in browser before navigation, // but this behavior bypasses the browser side navigation and the child // window will get wrong WebPreferences in the initialization. // This will end up initializing Node.js in the child window with wrong // WebPreferences, leads to problem that child window having node integration // while "nodeIntegration=no" is passed. // We work around this issue by delaying the child window's initialization of // Node.js if this is the initial empty document, and only do it when the // actual page has started to load. auto* web_frame = static_cast<blink::WebLocalFrameImpl*>(render_frame_->GetWebFrame()); if (web_frame->Opener() && web_frame->IsOnInitialEmptyDocument()) { // FIXME(zcbenz): Chromium does not do any browser side navigation for // window.open('about:blank'), so there is no way to override WebPreferences // of it. We should not delay Node.js initialization as there will be no // further loadings. // Please check http://crbug.com/1215096 for updates which may help remove // this hack. GURL url = web_frame->GetDocument().Url(); if (!url.IsAboutBlank()) { has_delayed_node_initialization_ = true; return; } } has_delayed_node_initialization_ = false; auto* isolate = context->GetIsolate(); v8::MicrotasksScope microtasks_scope( isolate, context->GetMicrotaskQueue(), v8::MicrotasksScope::kDoNotRunMicrotasks); if (ShouldNotifyClient(world_id)) renderer_client_->DidCreateScriptContext(context, render_frame_); auto prefs = render_frame_->GetBlinkPreferences(); bool use_context_isolation = prefs.context_isolation; // This logic matches the EXPLAINED logic in electron_renderer_client.cc // to avoid explaining it twice go check that implementation in // DidCreateScriptContext(); bool is_main_world = IsMainWorld(world_id); bool is_main_frame = render_frame_->IsMainFrame(); bool allow_node_in_sub_frames = prefs.node_integration_in_sub_frames; bool should_create_isolated_context = use_context_isolation && is_main_world && (is_main_frame || allow_node_in_sub_frames); if (should_create_isolated_context) { CreateIsolatedWorldContext(); if (!renderer_client_->IsWebViewFrame(context, render_frame_)) renderer_client_->SetupMainWorldOverrides(context, render_frame_); } } void ElectronRenderFrameObserver::DraggableRegionsChanged() { blink::WebVector<blink::WebDraggableRegion> webregions = render_frame_->GetWebFrame()->GetDocument().DraggableRegions(); std::vector<mojom::DraggableRegionPtr> regions; for (auto& webregion : webregions) { auto region = mojom::DraggableRegion::New(); render_frame_->ConvertViewportToWindow(&webregion.bounds); region->bounds = webregion.bounds; region->draggable = webregion.draggable; regions.push_back(std::move(region)); } mojo::AssociatedRemote<mojom::ElectronWebContentsUtility> web_contents_utility_remote; render_frame_->GetRemoteAssociatedInterfaces()->GetInterface( &web_contents_utility_remote); web_contents_utility_remote->UpdateDraggableRegions(std::move(regions)); } void ElectronRenderFrameObserver::WillReleaseScriptContext( v8::Local<v8::Context> context, int world_id) { if (ShouldNotifyClient(world_id)) renderer_client_->WillReleaseScriptContext(context, render_frame_); } void ElectronRenderFrameObserver::OnDestruct() { delete this; } void ElectronRenderFrameObserver::DidMeaningfulLayout( blink::WebMeaningfulLayout layout_type) { if (layout_type == blink::WebMeaningfulLayout::kVisuallyNonEmpty) { mojo::AssociatedRemote<mojom::ElectronWebContentsUtility> web_contents_utility_remote; render_frame_->GetRemoteAssociatedInterfaces()->GetInterface( &web_contents_utility_remote); web_contents_utility_remote->OnFirstNonEmptyLayout(); } } void ElectronRenderFrameObserver::CreateIsolatedWorldContext() { auto* frame = render_frame_->GetWebFrame(); blink::WebIsolatedWorldInfo info; // This maps to the name shown in the context combo box in the Console tab // of the dev tools. info.human_readable_name = blink::WebString::FromUTF8("Electron Isolated Context"); // Setup document's origin policy in isolated world info.security_origin = frame->GetDocument().GetSecurityOrigin(); blink::SetIsolatedWorldInfo(WorldIDs::ISOLATED_WORLD_ID, info); // Create initial script context in isolated world blink::WebScriptSource source("void 0"); frame->ExecuteScriptInIsolatedWorld( WorldIDs::ISOLATED_WORLD_ID, source, blink::BackForwardCacheAware::kPossiblyDisallow); } bool ElectronRenderFrameObserver::IsMainWorld(int world_id) { return world_id == WorldIDs::MAIN_WORLD_ID; } bool ElectronRenderFrameObserver::IsIsolatedWorld(int world_id) { return world_id == WorldIDs::ISOLATED_WORLD_ID; } bool ElectronRenderFrameObserver::ShouldNotifyClient(int world_id) { auto prefs = render_frame_->GetBlinkPreferences(); // This is necessary because if an iframe is created and a source is not // set, the iframe loads about:blank and creates a script context for the // same. We don't want to create a Node.js environment here because if the src // is later set, the JS necessary to do that triggers illegal access errors // when the initial about:blank Node.js environment is cleaned up. See: // https://source.chromium.org/chromium/chromium/src/+/main:content/renderer/render_frame_impl.h;l=870-892;drc=4b6001440a18740b76a1c63fa2a002cc941db394 GURL url = render_frame_->GetWebFrame()->GetDocument().Url(); bool allow_node_in_sub_frames = prefs.node_integration_in_sub_frames; if (allow_node_in_sub_frames && url.IsAboutBlank() && !render_frame_->IsMainFrame()) return false; if (prefs.context_isolation && (render_frame_->IsMainFrame() || allow_node_in_sub_frames)) return IsIsolatedWorld(world_id); return IsMainWorld(world_id); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,573
Async hook stack corruption in event callbacks with `setTimeout`
In investigating another bug, I discovered an async hook stack corruption bug consistently reproducible on Windows with the right combination of `setTimeout` calls and errors in `BrowserWindow` event callbacks. Reproducible back to Electron v19. Refs https://github.com/electron/electron/commit/6b97beb4897b47c1bad698c45bc01fbdae162ceb. <details><summary>Stacktrace 🏁</summary> <p> ``` Error: async hook stack has become corrupted (actual: 14, expected: 0) 1: 00007FF729DFAB38 node::Win32SymbolDebuggingContext::GetStackTrace+24 [o:\third_party\electron_node\src\debug_utils.cc]:L269 2: 00007FF729DFA29D node::DumpBacktrace+129 [o:\third_party\electron_node\src\debug_utils.cc]:L310 3: 00007FF729DC8ABC node::AsyncHooks::FailWithCorruptedAsyncStack+94 [o:\third_party\electron_node\src\env.cc]:L1515 4: 00007FF729DC8A5D node::AsyncHooks::pop_async_context+623 [o:\third_party\electron_node\src\env.cc]:L135 5: 00007FF729E0DAE4 node::InternalCallbackScope::Close+132 [o:\third_party\electron_node\src\api\callback.cc]:L123 6: 00007FF729E0D9C3 node::InternalCallbackScope::~InternalCallbackScope+13 [o:\third_party\electron_node\src\api\callback.cc]:L93 7: 00007FF729DED2E2 node::Environment::RunTimers+930 [o:\third_party\electron_node\src\env.cc]:L1227 8: 00007FF729E15112 uv__run_timers+65 [o:\third_party\electron_node\deps\uv\src\timer.c]:L168 9: 00007FF729E121EC uv_run+124 [o:\third_party\electron_node\deps\uv\src\win\core.c]:L613 10: 00007FF7241561B7 electron::NodeBindings::UvRunOnce+311 [o:\electron\shell\common\node_bindings.cc]:L875 11: 00007FF723F5A2A9 base::OnceCallback<void ()>::Run+83 [o:\base\functional\callback.h]:L155 12: 00007FF729058C85 base::TaskAnnotator::RunTaskImpl+421 [o:\base\task\common\task_annotator.cc]:L216 13: 00007FF729E86E57 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl+2007 [o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc]:L461 14: 00007FF729E86188 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork+296 [o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc]:L335 15: 00007FF72900B552 base::MessagePumpForUI::DoRunLoop+434 [o:\base\message_loop\message_pump_win.cc]:L213 16: 00007FF72900A2D0 base::MessagePumpWin::Run+240 [o:\base\message_loop\message_pump_win.cc]:L79 17: 00007FF729E88268 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run+616 [o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc]:L629 18: 00007FF729079D61 base::RunLoop::Run+657 [o:\base\run_loop.cc]:L136 19: 00007FF727C3AAE3 content::BrowserMainLoop::RunMainMessageLoop+159 [o:\content\browser\browser_main_loop.cc]:L1088 20: 00007FF727C3CE4E content::BrowserMainRunnerImpl::Run+46 [o:\content\browser\browser_main_runner_impl.cc]:L159 21: 00007FF727C36C2F content::BrowserMain+175 [o:\content\browser\browser_main.cc]:L34 22: 00007FF724337C80 content::RunBrowserProcessMain+352 [o:\content\app\content_main_runner_impl.cc]:L710 23: 00007FF72433A2D6 content::ContentMainRunnerImpl::RunBrowser+1230 [o:\content\app\content_main_runner_impl.cc]:L1296 24: 00007FF724339C78 content::ContentMainRunnerImpl::Run+1592 [o:\content\app\content_main_runner_impl.cc]:L1144 25: 00007FF7243347E9 content::RunContentProcess+1502 [o:\content\app\content_main.cc]:L333 26: 00007FF72433493F content::ContentMain+113 [o:\content\app\content_main.cc]:L346 27: 00007FF723F515C9 wWinMain+1149 [o:\electron\shell\app\electron_main_win.cc]:L239 28: 00007FF72ED12E92 __scrt_common_main_seh+262 [D:\a\_work\1\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl]:L288 29: 00007FFEFDC80A9C uaw_wcsrchr+962524 30: 00007FFEFDC17C10 uaw_wcsrchr+532816 31: 00007FFEFF8FB8B8 ZwWaitLowEventPair+1757544 Electron exited with code 1. ``` </p> </details> <details><summary>Repro Sample ♻️ </summary> <p> ```js const { app, BrowserWindow } = require('electron') function createWindow () { const mainWindow = new BrowserWindow() mainWindow.loadURL('https://github.com') mainWindow.on('maximize', () => { console.log('window maximize!') setTimeout(() => { mainWindow.minimize() }) }); mainWindow.on('restore', () => { throw new Error('hey') }) mainWindow.on('minimize', () => { console.log('window minimize!') setTimeout(() => { mainWindow.restore() }) }); mainWindow.maximize() } app.whenReady().then(() => { createWindow() app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) ``` </p> </details>
https://github.com/electron/electron/issues/40573
https://github.com/electron/electron/pull/40576
db2bf1a0d1be6b81ca2d1a6b693b78753d3ba6ea
8104c7908a2e281cdb2e380dd2ec49c3ead7fa3e
2023-11-21T10:00:07Z
c++
2024-01-26T18:53:07Z
shell/browser/api/electron_api_auto_updater.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_auto_updater.h" #include "base/time/time.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_window.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/time_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/node_includes.h" namespace electron::api { gin::WrapperInfo AutoUpdater::kWrapperInfo = {gin::kEmbedderNativeGin}; AutoUpdater::AutoUpdater() { auto_updater::AutoUpdater::SetDelegate(this); } AutoUpdater::~AutoUpdater() { auto_updater::AutoUpdater::SetDelegate(nullptr); } void AutoUpdater::OnError(const std::string& message) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Object> wrapper; if (GetWrapper(isolate).ToLocal(&wrapper)) { auto error = v8::Exception::Error(gin::StringToV8(isolate, message)); gin_helper::EmitEvent( isolate, wrapper, "error", error->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), // Message is also emitted to keep compatibility with old code. message); } } void AutoUpdater::OnError(const std::string& message, const int code, const std::string& domain) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Object> wrapper; if (GetWrapper(isolate).ToLocal(&wrapper)) { auto error = v8::Exception::Error(gin::StringToV8(isolate, message)); auto errorObject = error->ToObject(isolate->GetCurrentContext()).ToLocalChecked(); auto context = isolate->GetCurrentContext(); // add two new params for better error handling errorObject ->Set(context, gin::StringToV8(isolate, "code"), v8::Integer::New(isolate, code)) .Check(); errorObject ->Set(context, gin::StringToV8(isolate, "domain"), gin::StringToV8(isolate, domain)) .Check(); gin_helper::EmitEvent(isolate, wrapper, "error", errorObject, message); } } void AutoUpdater::OnCheckingForUpdate() { Emit("checking-for-update"); } void AutoUpdater::OnUpdateAvailable() { Emit("update-available"); } void AutoUpdater::OnUpdateNotAvailable() { Emit("update-not-available"); } void AutoUpdater::OnUpdateDownloaded(const std::string& release_notes, const std::string& release_name, const base::Time& release_date, const std::string& url) { Emit("update-downloaded", release_notes, release_name, release_date, url, // Keep compatibility with old APIs. base::BindRepeating(&AutoUpdater::QuitAndInstall, base::Unretained(this))); } void AutoUpdater::OnWindowAllClosed() { QuitAndInstall(); } void AutoUpdater::QuitAndInstall() { Emit("before-quit-for-update"); // If we don't have any window then quitAndInstall immediately. if (WindowList::IsEmpty()) { auto_updater::AutoUpdater::QuitAndInstall(); return; } // Otherwise do the restart after all windows have been closed. WindowList::AddObserver(this); WindowList::CloseAllWindows(); } // static gin::Handle<AutoUpdater> AutoUpdater::Create(v8::Isolate* isolate) { return gin::CreateHandle(isolate, new AutoUpdater()); } gin::ObjectTemplateBuilder AutoUpdater::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin_helper::EventEmitterMixin<AutoUpdater>::GetObjectTemplateBuilder( isolate) .SetMethod("checkForUpdates", &auto_updater::AutoUpdater::CheckForUpdates) .SetMethod("getFeedURL", &auto_updater::AutoUpdater::GetFeedURL) .SetMethod("setFeedURL", &auto_updater::AutoUpdater::SetFeedURL) #if DCHECK_IS_ON() .SetMethod("isVersionAllowedForUpdate", &auto_updater::AutoUpdater::IsVersionAllowedForUpdate) #endif .SetMethod("quitAndInstall", &AutoUpdater::QuitAndInstall); } const char* AutoUpdater::GetTypeName() { return "AutoUpdater"; } } // namespace electron::api namespace { using electron::api::AutoUpdater; 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("autoUpdater", AutoUpdater::Create(isolate)); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_auto_updater, Initialize)
closed
electron/electron
https://github.com/electron/electron
40,573
Async hook stack corruption in event callbacks with `setTimeout`
In investigating another bug, I discovered an async hook stack corruption bug consistently reproducible on Windows with the right combination of `setTimeout` calls and errors in `BrowserWindow` event callbacks. Reproducible back to Electron v19. Refs https://github.com/electron/electron/commit/6b97beb4897b47c1bad698c45bc01fbdae162ceb. <details><summary>Stacktrace 🏁</summary> <p> ``` Error: async hook stack has become corrupted (actual: 14, expected: 0) 1: 00007FF729DFAB38 node::Win32SymbolDebuggingContext::GetStackTrace+24 [o:\third_party\electron_node\src\debug_utils.cc]:L269 2: 00007FF729DFA29D node::DumpBacktrace+129 [o:\third_party\electron_node\src\debug_utils.cc]:L310 3: 00007FF729DC8ABC node::AsyncHooks::FailWithCorruptedAsyncStack+94 [o:\third_party\electron_node\src\env.cc]:L1515 4: 00007FF729DC8A5D node::AsyncHooks::pop_async_context+623 [o:\third_party\electron_node\src\env.cc]:L135 5: 00007FF729E0DAE4 node::InternalCallbackScope::Close+132 [o:\third_party\electron_node\src\api\callback.cc]:L123 6: 00007FF729E0D9C3 node::InternalCallbackScope::~InternalCallbackScope+13 [o:\third_party\electron_node\src\api\callback.cc]:L93 7: 00007FF729DED2E2 node::Environment::RunTimers+930 [o:\third_party\electron_node\src\env.cc]:L1227 8: 00007FF729E15112 uv__run_timers+65 [o:\third_party\electron_node\deps\uv\src\timer.c]:L168 9: 00007FF729E121EC uv_run+124 [o:\third_party\electron_node\deps\uv\src\win\core.c]:L613 10: 00007FF7241561B7 electron::NodeBindings::UvRunOnce+311 [o:\electron\shell\common\node_bindings.cc]:L875 11: 00007FF723F5A2A9 base::OnceCallback<void ()>::Run+83 [o:\base\functional\callback.h]:L155 12: 00007FF729058C85 base::TaskAnnotator::RunTaskImpl+421 [o:\base\task\common\task_annotator.cc]:L216 13: 00007FF729E86E57 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl+2007 [o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc]:L461 14: 00007FF729E86188 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork+296 [o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc]:L335 15: 00007FF72900B552 base::MessagePumpForUI::DoRunLoop+434 [o:\base\message_loop\message_pump_win.cc]:L213 16: 00007FF72900A2D0 base::MessagePumpWin::Run+240 [o:\base\message_loop\message_pump_win.cc]:L79 17: 00007FF729E88268 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run+616 [o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc]:L629 18: 00007FF729079D61 base::RunLoop::Run+657 [o:\base\run_loop.cc]:L136 19: 00007FF727C3AAE3 content::BrowserMainLoop::RunMainMessageLoop+159 [o:\content\browser\browser_main_loop.cc]:L1088 20: 00007FF727C3CE4E content::BrowserMainRunnerImpl::Run+46 [o:\content\browser\browser_main_runner_impl.cc]:L159 21: 00007FF727C36C2F content::BrowserMain+175 [o:\content\browser\browser_main.cc]:L34 22: 00007FF724337C80 content::RunBrowserProcessMain+352 [o:\content\app\content_main_runner_impl.cc]:L710 23: 00007FF72433A2D6 content::ContentMainRunnerImpl::RunBrowser+1230 [o:\content\app\content_main_runner_impl.cc]:L1296 24: 00007FF724339C78 content::ContentMainRunnerImpl::Run+1592 [o:\content\app\content_main_runner_impl.cc]:L1144 25: 00007FF7243347E9 content::RunContentProcess+1502 [o:\content\app\content_main.cc]:L333 26: 00007FF72433493F content::ContentMain+113 [o:\content\app\content_main.cc]:L346 27: 00007FF723F515C9 wWinMain+1149 [o:\electron\shell\app\electron_main_win.cc]:L239 28: 00007FF72ED12E92 __scrt_common_main_seh+262 [D:\a\_work\1\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl]:L288 29: 00007FFEFDC80A9C uaw_wcsrchr+962524 30: 00007FFEFDC17C10 uaw_wcsrchr+532816 31: 00007FFEFF8FB8B8 ZwWaitLowEventPair+1757544 Electron exited with code 1. ``` </p> </details> <details><summary>Repro Sample ♻️ </summary> <p> ```js const { app, BrowserWindow } = require('electron') function createWindow () { const mainWindow = new BrowserWindow() mainWindow.loadURL('https://github.com') mainWindow.on('maximize', () => { console.log('window maximize!') setTimeout(() => { mainWindow.minimize() }) }); mainWindow.on('restore', () => { throw new Error('hey') }) mainWindow.on('minimize', () => { console.log('window minimize!') setTimeout(() => { mainWindow.restore() }) }); mainWindow.maximize() } app.whenReady().then(() => { createWindow() app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) ``` </p> </details>
https://github.com/electron/electron/issues/40573
https://github.com/electron/electron/pull/40576
db2bf1a0d1be6b81ca2d1a6b693b78753d3ba6ea
8104c7908a2e281cdb2e380dd2ec49c3ead7fa3e
2023-11-21T10:00:07Z
c++
2024-01-26T18:53:07Z
shell/common/gin_helper/event_emitter_caller.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/common/gin_helper/event_emitter_caller.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/node_includes.h" namespace gin_helper::internal { v8::Local<v8::Value> CallMethodWithArgs(v8::Isolate* isolate, v8::Local<v8::Object> obj, const char* method, ValueVector* args) { // Perform microtask checkpoint after running JavaScript. gin_helper::MicrotasksScope microtasks_scope( isolate, obj->GetCreationContextChecked()->GetMicrotaskQueue(), true); // Use node::MakeCallback to call the callback, and it will also run pending // tasks in Node.js. v8::MaybeLocal<v8::Value> ret = node::MakeCallback( isolate, obj, method, args->size(), args->data(), {0, 0}); // If the JS function throws an exception (doesn't return a value) the result // of MakeCallback will be empty and therefore ToLocal will be false, in this // case we need to return "false" as that indicates that the event emitter did // not handle the event v8::Local<v8::Value> localRet; if (ret.ToLocal(&localRet)) { return localRet; } return v8::Boolean::New(isolate, false); } } // namespace gin_helper::internal
closed
electron/electron
https://github.com/electron/electron
40,573
Async hook stack corruption in event callbacks with `setTimeout`
In investigating another bug, I discovered an async hook stack corruption bug consistently reproducible on Windows with the right combination of `setTimeout` calls and errors in `BrowserWindow` event callbacks. Reproducible back to Electron v19. Refs https://github.com/electron/electron/commit/6b97beb4897b47c1bad698c45bc01fbdae162ceb. <details><summary>Stacktrace 🏁</summary> <p> ``` Error: async hook stack has become corrupted (actual: 14, expected: 0) 1: 00007FF729DFAB38 node::Win32SymbolDebuggingContext::GetStackTrace+24 [o:\third_party\electron_node\src\debug_utils.cc]:L269 2: 00007FF729DFA29D node::DumpBacktrace+129 [o:\third_party\electron_node\src\debug_utils.cc]:L310 3: 00007FF729DC8ABC node::AsyncHooks::FailWithCorruptedAsyncStack+94 [o:\third_party\electron_node\src\env.cc]:L1515 4: 00007FF729DC8A5D node::AsyncHooks::pop_async_context+623 [o:\third_party\electron_node\src\env.cc]:L135 5: 00007FF729E0DAE4 node::InternalCallbackScope::Close+132 [o:\third_party\electron_node\src\api\callback.cc]:L123 6: 00007FF729E0D9C3 node::InternalCallbackScope::~InternalCallbackScope+13 [o:\third_party\electron_node\src\api\callback.cc]:L93 7: 00007FF729DED2E2 node::Environment::RunTimers+930 [o:\third_party\electron_node\src\env.cc]:L1227 8: 00007FF729E15112 uv__run_timers+65 [o:\third_party\electron_node\deps\uv\src\timer.c]:L168 9: 00007FF729E121EC uv_run+124 [o:\third_party\electron_node\deps\uv\src\win\core.c]:L613 10: 00007FF7241561B7 electron::NodeBindings::UvRunOnce+311 [o:\electron\shell\common\node_bindings.cc]:L875 11: 00007FF723F5A2A9 base::OnceCallback<void ()>::Run+83 [o:\base\functional\callback.h]:L155 12: 00007FF729058C85 base::TaskAnnotator::RunTaskImpl+421 [o:\base\task\common\task_annotator.cc]:L216 13: 00007FF729E86E57 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl+2007 [o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc]:L461 14: 00007FF729E86188 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork+296 [o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc]:L335 15: 00007FF72900B552 base::MessagePumpForUI::DoRunLoop+434 [o:\base\message_loop\message_pump_win.cc]:L213 16: 00007FF72900A2D0 base::MessagePumpWin::Run+240 [o:\base\message_loop\message_pump_win.cc]:L79 17: 00007FF729E88268 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run+616 [o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc]:L629 18: 00007FF729079D61 base::RunLoop::Run+657 [o:\base\run_loop.cc]:L136 19: 00007FF727C3AAE3 content::BrowserMainLoop::RunMainMessageLoop+159 [o:\content\browser\browser_main_loop.cc]:L1088 20: 00007FF727C3CE4E content::BrowserMainRunnerImpl::Run+46 [o:\content\browser\browser_main_runner_impl.cc]:L159 21: 00007FF727C36C2F content::BrowserMain+175 [o:\content\browser\browser_main.cc]:L34 22: 00007FF724337C80 content::RunBrowserProcessMain+352 [o:\content\app\content_main_runner_impl.cc]:L710 23: 00007FF72433A2D6 content::ContentMainRunnerImpl::RunBrowser+1230 [o:\content\app\content_main_runner_impl.cc]:L1296 24: 00007FF724339C78 content::ContentMainRunnerImpl::Run+1592 [o:\content\app\content_main_runner_impl.cc]:L1144 25: 00007FF7243347E9 content::RunContentProcess+1502 [o:\content\app\content_main.cc]:L333 26: 00007FF72433493F content::ContentMain+113 [o:\content\app\content_main.cc]:L346 27: 00007FF723F515C9 wWinMain+1149 [o:\electron\shell\app\electron_main_win.cc]:L239 28: 00007FF72ED12E92 __scrt_common_main_seh+262 [D:\a\_work\1\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl]:L288 29: 00007FFEFDC80A9C uaw_wcsrchr+962524 30: 00007FFEFDC17C10 uaw_wcsrchr+532816 31: 00007FFEFF8FB8B8 ZwWaitLowEventPair+1757544 Electron exited with code 1. ``` </p> </details> <details><summary>Repro Sample ♻️ </summary> <p> ```js const { app, BrowserWindow } = require('electron') function createWindow () { const mainWindow = new BrowserWindow() mainWindow.loadURL('https://github.com') mainWindow.on('maximize', () => { console.log('window maximize!') setTimeout(() => { mainWindow.minimize() }) }); mainWindow.on('restore', () => { throw new Error('hey') }) mainWindow.on('minimize', () => { console.log('window minimize!') setTimeout(() => { mainWindow.restore() }) }); mainWindow.maximize() } app.whenReady().then(() => { createWindow() app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) ``` </p> </details>
https://github.com/electron/electron/issues/40573
https://github.com/electron/electron/pull/40576
db2bf1a0d1be6b81ca2d1a6b693b78753d3ba6ea
8104c7908a2e281cdb2e380dd2ec49c3ead7fa3e
2023-11-21T10:00:07Z
c++
2024-01-26T18:53:07Z
shell/renderer/electron_api_service_impl.cc
// Copyright (c) 2019 Slack Technologies, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "electron/shell/renderer/electron_api_service_impl.h" #include <memory> #include <tuple> #include <utility> #include <vector> #include "base/environment.h" #include "base/trace_event/trace_event.h" #include "gin/data_object_builder.h" #include "mojo/public/cpp/system/platform_handle.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/heap_snapshot.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/thread_restrictions.h" #include "shell/common/v8_value_serializer.h" #include "shell/renderer/electron_render_frame_observer.h" #include "shell/renderer/renderer_client_base.h" #include "third_party/blink/public/mojom/frame/user_activation_notification_type.mojom-shared.h" #include "third_party/blink/public/web/blink.h" #include "third_party/blink/public/web/web_local_frame.h" #include "third_party/blink/public/web/web_message_port_converter.h" namespace electron { namespace { const char kIpcKey[] = "ipcNative"; // Gets the private object under kIpcKey v8::Local<v8::Object> GetIpcObject(v8::Local<v8::Context> context) { auto* isolate = context->GetIsolate(); auto binding_key = gin::StringToV8(isolate, kIpcKey); auto private_binding_key = v8::Private::ForApi(isolate, binding_key); auto global_object = context->Global(); auto value = global_object->GetPrivate(context, private_binding_key).ToLocalChecked(); if (value.IsEmpty() || !value->IsObject()) { LOG(ERROR) << "Attempted to get the 'ipcNative' object but it was missing"; return v8::Local<v8::Object>(); } return value->ToObject(context).ToLocalChecked(); } void InvokeIpcCallback(v8::Local<v8::Context> context, const std::string& callback_name, std::vector<v8::Local<v8::Value>> args) { TRACE_EVENT0("devtools.timeline", "FunctionCall"); auto* isolate = context->GetIsolate(); auto ipcNative = GetIpcObject(context); if (ipcNative.IsEmpty()) return; // Only set up the node::CallbackScope if there's a node environment. // Sandboxed renderers don't have a node environment. node::Environment* env = node::Environment::GetCurrent(context); std::unique_ptr<node::CallbackScope> callback_scope; if (env) { node::async_context async_context = {}; callback_scope = std::make_unique<node::CallbackScope>(isolate, ipcNative, async_context); } auto callback_key = gin::ConvertToV8(isolate, callback_name) ->ToString(context) .ToLocalChecked(); auto callback_value = ipcNative->Get(context, callback_key).ToLocalChecked(); DCHECK(callback_value->IsFunction()); // set by init.ts auto callback = callback_value.As<v8::Function>(); std::ignore = callback->Call(context, ipcNative, args.size(), args.data()); } void EmitIPCEvent(v8::Local<v8::Context> context, bool internal, const std::string& channel, std::vector<v8::Local<v8::Value>> ports, v8::Local<v8::Value> args) { auto* isolate = context->GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope(context); v8::MicrotasksScope script_scope(isolate, context->GetMicrotaskQueue(), v8::MicrotasksScope::kRunMicrotasks); std::vector<v8::Local<v8::Value>> argv = { gin::ConvertToV8(isolate, internal), gin::ConvertToV8(isolate, channel), gin::ConvertToV8(isolate, ports), args}; InvokeIpcCallback(context, "onMessage", argv); } } // namespace ElectronApiServiceImpl::~ElectronApiServiceImpl() = default; ElectronApiServiceImpl::ElectronApiServiceImpl( content::RenderFrame* render_frame, RendererClientBase* renderer_client) : content::RenderFrameObserver(render_frame), renderer_client_(renderer_client) { registry_.AddInterface<mojom::ElectronRenderer>(base::BindRepeating( &ElectronApiServiceImpl::BindTo, base::Unretained(this))); } void ElectronApiServiceImpl::BindTo( mojo::PendingReceiver<mojom::ElectronRenderer> receiver) { if (document_created_) { if (receiver_.is_bound()) receiver_.reset(); receiver_.Bind(std::move(receiver)); receiver_.set_disconnect_handler(base::BindOnce( &ElectronApiServiceImpl::OnConnectionError, GetWeakPtr())); } else { pending_receiver_ = std::move(receiver); } } void ElectronApiServiceImpl::OnInterfaceRequestForFrame( const std::string& interface_name, mojo::ScopedMessagePipeHandle* interface_pipe) { registry_.TryBindInterface(interface_name, interface_pipe); } void ElectronApiServiceImpl::DidCreateDocumentElement() { document_created_ = true; if (pending_receiver_) { if (receiver_.is_bound()) receiver_.reset(); receiver_.Bind(std::move(pending_receiver_)); receiver_.set_disconnect_handler(base::BindOnce( &ElectronApiServiceImpl::OnConnectionError, GetWeakPtr())); } } void ElectronApiServiceImpl::OnDestruct() { delete this; } void ElectronApiServiceImpl::OnConnectionError() { if (receiver_.is_bound()) receiver_.reset(); } void ElectronApiServiceImpl::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments) { blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); if (!frame) return; v8::Isolate* isolate = blink::MainThreadIsolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Context> context = renderer_client_->GetContext(frame, isolate); v8::Context::Scope context_scope(context); v8::Local<v8::Value> args = gin::ConvertToV8(isolate, arguments); EmitIPCEvent(context, internal, channel, {}, args); } void ElectronApiServiceImpl::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message) { blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); if (!frame) return; v8::Isolate* isolate = blink::MainThreadIsolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Context> context = renderer_client_->GetContext(frame, isolate); v8::Context::Scope context_scope(context); v8::Local<v8::Value> message_value = DeserializeV8Value(isolate, message); std::vector<v8::Local<v8::Value>> ports; for (auto& port : message.ports) { ports.emplace_back( blink::WebMessagePortConverter::EntangleAndInjectMessagePortChannel( context, std::move(port))); } std::vector<v8::Local<v8::Value>> args = {message_value}; EmitIPCEvent(context, false, channel, ports, gin::ConvertToV8(isolate, args)); } void ElectronApiServiceImpl::TakeHeapSnapshot( mojo::ScopedHandle file, TakeHeapSnapshotCallback callback) { ScopedAllowBlockingForElectron allow_blocking; base::ScopedPlatformFile platform_file; if (mojo::UnwrapPlatformFile(std::move(file), &platform_file) != MOJO_RESULT_OK) { LOG(ERROR) << "Unable to get the file handle from mojo."; std::move(callback).Run(false); return; } base::File base_file(std::move(platform_file)); bool success = electron::TakeHeapSnapshot(blink::MainThreadIsolate(), &base_file); std::move(callback).Run(success); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,573
Async hook stack corruption in event callbacks with `setTimeout`
In investigating another bug, I discovered an async hook stack corruption bug consistently reproducible on Windows with the right combination of `setTimeout` calls and errors in `BrowserWindow` event callbacks. Reproducible back to Electron v19. Refs https://github.com/electron/electron/commit/6b97beb4897b47c1bad698c45bc01fbdae162ceb. <details><summary>Stacktrace 🏁</summary> <p> ``` Error: async hook stack has become corrupted (actual: 14, expected: 0) 1: 00007FF729DFAB38 node::Win32SymbolDebuggingContext::GetStackTrace+24 [o:\third_party\electron_node\src\debug_utils.cc]:L269 2: 00007FF729DFA29D node::DumpBacktrace+129 [o:\third_party\electron_node\src\debug_utils.cc]:L310 3: 00007FF729DC8ABC node::AsyncHooks::FailWithCorruptedAsyncStack+94 [o:\third_party\electron_node\src\env.cc]:L1515 4: 00007FF729DC8A5D node::AsyncHooks::pop_async_context+623 [o:\third_party\electron_node\src\env.cc]:L135 5: 00007FF729E0DAE4 node::InternalCallbackScope::Close+132 [o:\third_party\electron_node\src\api\callback.cc]:L123 6: 00007FF729E0D9C3 node::InternalCallbackScope::~InternalCallbackScope+13 [o:\third_party\electron_node\src\api\callback.cc]:L93 7: 00007FF729DED2E2 node::Environment::RunTimers+930 [o:\third_party\electron_node\src\env.cc]:L1227 8: 00007FF729E15112 uv__run_timers+65 [o:\third_party\electron_node\deps\uv\src\timer.c]:L168 9: 00007FF729E121EC uv_run+124 [o:\third_party\electron_node\deps\uv\src\win\core.c]:L613 10: 00007FF7241561B7 electron::NodeBindings::UvRunOnce+311 [o:\electron\shell\common\node_bindings.cc]:L875 11: 00007FF723F5A2A9 base::OnceCallback<void ()>::Run+83 [o:\base\functional\callback.h]:L155 12: 00007FF729058C85 base::TaskAnnotator::RunTaskImpl+421 [o:\base\task\common\task_annotator.cc]:L216 13: 00007FF729E86E57 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl+2007 [o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc]:L461 14: 00007FF729E86188 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork+296 [o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc]:L335 15: 00007FF72900B552 base::MessagePumpForUI::DoRunLoop+434 [o:\base\message_loop\message_pump_win.cc]:L213 16: 00007FF72900A2D0 base::MessagePumpWin::Run+240 [o:\base\message_loop\message_pump_win.cc]:L79 17: 00007FF729E88268 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run+616 [o:\base\task\sequence_manager\thread_controller_with_message_pump_impl.cc]:L629 18: 00007FF729079D61 base::RunLoop::Run+657 [o:\base\run_loop.cc]:L136 19: 00007FF727C3AAE3 content::BrowserMainLoop::RunMainMessageLoop+159 [o:\content\browser\browser_main_loop.cc]:L1088 20: 00007FF727C3CE4E content::BrowserMainRunnerImpl::Run+46 [o:\content\browser\browser_main_runner_impl.cc]:L159 21: 00007FF727C36C2F content::BrowserMain+175 [o:\content\browser\browser_main.cc]:L34 22: 00007FF724337C80 content::RunBrowserProcessMain+352 [o:\content\app\content_main_runner_impl.cc]:L710 23: 00007FF72433A2D6 content::ContentMainRunnerImpl::RunBrowser+1230 [o:\content\app\content_main_runner_impl.cc]:L1296 24: 00007FF724339C78 content::ContentMainRunnerImpl::Run+1592 [o:\content\app\content_main_runner_impl.cc]:L1144 25: 00007FF7243347E9 content::RunContentProcess+1502 [o:\content\app\content_main.cc]:L333 26: 00007FF72433493F content::ContentMain+113 [o:\content\app\content_main.cc]:L346 27: 00007FF723F515C9 wWinMain+1149 [o:\electron\shell\app\electron_main_win.cc]:L239 28: 00007FF72ED12E92 __scrt_common_main_seh+262 [D:\a\_work\1\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl]:L288 29: 00007FFEFDC80A9C uaw_wcsrchr+962524 30: 00007FFEFDC17C10 uaw_wcsrchr+532816 31: 00007FFEFF8FB8B8 ZwWaitLowEventPair+1757544 Electron exited with code 1. ``` </p> </details> <details><summary>Repro Sample ♻️ </summary> <p> ```js const { app, BrowserWindow } = require('electron') function createWindow () { const mainWindow = new BrowserWindow() mainWindow.loadURL('https://github.com') mainWindow.on('maximize', () => { console.log('window maximize!') setTimeout(() => { mainWindow.minimize() }) }); mainWindow.on('restore', () => { throw new Error('hey') }) mainWindow.on('minimize', () => { console.log('window minimize!') setTimeout(() => { mainWindow.restore() }) }); mainWindow.maximize() } app.whenReady().then(() => { createWindow() app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) ``` </p> </details>
https://github.com/electron/electron/issues/40573
https://github.com/electron/electron/pull/40576
db2bf1a0d1be6b81ca2d1a6b693b78753d3ba6ea
8104c7908a2e281cdb2e380dd2ec49c3ead7fa3e
2023-11-21T10:00:07Z
c++
2024-01-26T18:53:07Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as http from 'node:http'; import * as os from 'node:os'; import { AddressInfo } from 'node:net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; const fixtures = path.resolve(__dirname, 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { it('sets the correct class name on the prototype', () => { expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow'); }); describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. const wr = new WeakRef(w); await setTimeout(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = once(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = once(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, '-before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await once(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await once(w.webContents, '-before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); for (const win of windows) win.show(); for (const win of windows) win.focus(); for (const win of windows) win.destroy(); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w: BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server: http.Server; let url: string; let postData = null as any; before(async () => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); it('is triggered when navigating from chrome: to http:', async () => { let hasEmittedWillNavigate = false; const willNavigatePromise = new Promise((resolve) => { w.webContents.once('will-navigate', e => { e.preventDefault(); hasEmittedWillNavigate = true; resolve(e.url); }); }); await w.loadURL('chrome://gpu'); // shouldn't emit for browser-initiated request via loadURL expect(hasEmittedWillNavigate).to.equal(false); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await willNavigatePromise; expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('chrome://gpu/'); }); }); describe('will-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); describe('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); url = (await listen(server)).url; }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(url + '/navigate'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(url + '/redirect'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(url + '/in-page'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = once(w, 'maximize'); const shown = once(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await setTimeout(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); ifit(process.platform === 'darwin')('should attach child window to parent', async () => { const wShow = once(w, 'show'); w.show(); await wShow; const c = new BrowserWindow({ show: false, parent: w }); const cShow = once(c, 'show'); c.showInactive(); await cShow; // verifying by checking that the child tracks the parent's visibility const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); closeWindow(c); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); ifit(process.platform === 'darwin')('it does not activate the app if focusing an inactive panel', async () => { // Show to focus app, then remove existing window w.show(); w.destroy(); // We first need to resign app focus for this test to work const isInactive = once(app, 'did-resign-active'); childProcess.execSync('osascript -e \'tell application "Finder" to activate\''); await isInactive; // Create new window w = new BrowserWindow({ type: 'panel', height: 200, width: 200, center: true, show: false }); const isShow = once(w, 'show'); const isFocus = once(w, 'focus'); w.showInactive(); w.focus(); await isShow; await isFocus; const getActiveAppOsa = 'tell application "System Events" to get the name of the first process whose frontmost is true'; const activeApp = childProcess.execSync(`osascript -e '${getActiveAppOsa}'`).toString().trim(); expect(activeApp).to.equal('Finder'); }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { afterEach(closeAllWindows); it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); it('should not crash when called on a modal child window', async () => { const shown = once(w, 'show'); w.show(); await shown; const child = new BrowserWindow({ modal: true, parent: w }); expect(() => { child.moveTop(); }).to.not.throw(); }); }); describe('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; for (const sourceId of fakeSourceIds) { 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]; for (const sourceId of fakeSourceIds) { 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']; for (const sourceId of fakeSourceIds) { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); } }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = once(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = once(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.showAllTabs()', () => { it('does not throw', () => { expect(() => { w.showAllTabs(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); describe('BrowserWindow.tabbingIdentifier', () => { it('is undefined if no tabbingIdentifier was set', () => { const w = new BrowserWindow({ show: false }); expect(w.tabbingIdentifier).to.be.undefined('tabbingIdentifier'); }); it('returns the window tabbingIdentifier', () => { const w = new BrowserWindow({ show: false, tabbingIdentifier: 'group1' }); expect(w.tabbingIdentifier).to.equal('group1'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves when the window is occluded', async () => { const w1 = new BrowserWindow({ show: false }); w1.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w1, 'ready-to-show'); w1.show(); const w2 = new BrowserWindow({ show: false }); w2.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w2, 'ready-to-show'); w2.show(); const visibleImage = await w1.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); }); it('resolves when the window is not visible', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.minimize(); const hiddenImage = await w.capturePage(); expect(hiddenImage.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w: BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w: BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = once(w, 'always-on-top-changed') as Promise<[any, boolean]>; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect(c._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w: BrowserWindow; let server: http.Server; let url: string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); url = (await listen(server)).url; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = once(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('titlebar'); w.setVibrancy('selection'); w.setVibrancy(null); w.setVibrancy('menu'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created') as [any, WebContents]; expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); bv1.webContents.destroy(); bv2.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await once(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await once(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await once(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await once(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await once(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replaceAll('\\', '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('node:events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window') as [BrowserWindow, Electron.DidCreateWindowDetails]; const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replaceAll('\\', '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await once(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await once(app, 'browser-window-created') as [any, BrowserWindow]; // Ask the popup window for details. const detailsAnswer = once(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); const errorPattern = /Failed to read a named property 'document' from 'Window': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./; expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(errorPattern); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(errorPattern); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences!.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => once(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); expect(test.nodeEvents).to.equal(true); expect(test.nodeTimers).to.equal(true); expect(test.nodeUrl).to.equal(true); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Failed to read a named property \'toString\' from \'Location\': Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences!.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await once(w.webContents, '-before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await once(w.webContents, '-before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.close(); await once(w.webContents, '-before-unload-fired'); w.close(); await once(w.webContents, '-before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.reload(); // Chromium does not emit '-before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await once(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit '-before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); // TODO(codebytere): figure out how to make these pass in CI on Windows. ifdescribe(process.platform !== 'win32')('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); it('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); it('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = once(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = once(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('can handle child window close and reparent multiple times', async () => { const w = new BrowserWindow({ show: false }); let c: BrowserWindow | null; for (let i = 0; i < 5; i++) { c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; } await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('only shows the intended window when a child with siblings is shown', async () => { const w = new BrowserWindow({ show: false }); const childOne = new BrowserWindow({ show: false, parent: w }); const childTwo = new BrowserWindow({ show: false, parent: w }); const parentShown = once(w, 'show'); w.show(); await parentShown; expect(childOne.isVisible()).to.be.false('childOne is visible'); expect(childTwo.isVisible()).to.be.false('childTwo is visible'); const childOneShown = once(childOne, 'show'); childOne.show(); await childOneShown; expect(childOne.isVisible()).to.be.true('childOne is not visible'); expect(childTwo.isVisible()).to.be.false('childTwo is visible'); }); ifit(process.platform === 'darwin')('child matches parent visibility when parent visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); ifit(process.platform === 'darwin')('parent matches child visibility when child visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(c, 'minimize'); c.minimize(); await minimized; expect(c.isVisible()).to.be.false('child is visible'); const restored = once(c, 'restore'); c.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); it('closes a grandchild window when a middle child window is destroyed', async () => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); const closed = once(childWindow, 'closed'); window.close(); await closed; expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = once(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('can reparent when the first parent is destroyed', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); c.setParentWindow(w1); expect(w1.getChildWindows().length).to.equal(1); const closed = once(w1, 'closed'); w1.destroy(); await closed; c.setParentWindow(w2); await setTimeout(); const children = w2.getChildWindows(); expect(children[0]).to.equal(c); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); ifit(process.platform === 'win32')('do not change window with frame bounds when maximized', () => { const w = new BrowserWindow({ show: true, frame: true, thickFrame: true }); expect(w.isResizable()).to.be.true('resizable'); w.maximize(); expect(w.isMaximized()).to.be.true('maximized'); const bounds = w.getBounds(); w.setResizable(false); expectBoundsEqual(w.getBounds(), bounds); w.setResizable(true); expectBoundsEqual(w.getBounds(), bounds); }); ifit(process.platform === 'win32')('do not change window without frame bounds when maximized', () => { const w = new BrowserWindow({ show: true, frame: false, thickFrame: true }); expect(w.isResizable()).to.be.true('resizable'); w.maximize(); expect(w.isMaximized()).to.be.true('maximized'); const bounds = w.getBounds(); w.setResizable(false); expectBoundsEqual(w.getBounds(), bounds); w.setResizable(true); expectBoundsEqual(w.getBounds(), bounds); }); ifit(process.platform === 'win32')('do not change window transparent without frame bounds when maximized', () => { const w = new BrowserWindow({ show: true, frame: false, thickFrame: true, transparent: true }); expect(w.isResizable()).to.be.true('resizable'); w.maximize(); expect(w.isMaximized()).to.be.true('maximized'); const bounds = w.getBounds(); w.setResizable(false); expectBoundsEqual(w.getBounds(), bounds); w.setResizable(true); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('loading main frame state', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform !== 'darwin')('when fullscreen state is changed', () => { it('correctly remembers state prior to fullscreen change', async () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); it('correctly remembers state prior to fullscreen change with autoHide', async () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); it('does not open non-fullscreenable child windows in fullscreen if parent is fullscreen', async () => { const w = new BrowserWindow(); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const child = new BrowserWindow({ parent: w, resizable: false, fullscreenable: false }); const shown = once(child, 'show'); await shown; expect(child.resizable).to.be.false('resizable'); expect(child.fullScreen).to.be.false('fullscreen'); expect(child.fullScreenable).to.be.false('fullscreenable'); }); it('is set correctly with different resizable values', async () => { const w1 = new BrowserWindow({ resizable: false, fullscreenable: false }); const w2 = new BrowserWindow({ resizable: true, fullscreenable: false }); const w3 = new BrowserWindow({ fullscreenable: false }); expect(w1.isFullScreenable()).to.be.false('isFullScreenable'); expect(w2.isFullScreenable()).to.be.false('isFullScreenable'); expect(w3.isFullScreenable()).to.be.false('isFullScreenable'); }); it('does not disable maximize button if window is resizable', () => { const w = new BrowserWindow({ resizable: true, fullscreenable: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setResizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); const isValidWindow = require('@electron-ci/is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences()!.contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = once(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = once(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); describe('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(1000); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(1000); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); await setTimeout(1000); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
41,142
[Bug]: Electron crashes on exit 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 30.0.0-nightly.20231214 ### What operating system are you using? macOS ### Operating System Version 13.5 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 30.0.0-nightly.20231213 ### Expected Behavior 1. Launch app attached to the https://github.com/electron/electron/issues/41141 2. Close the app 3. App exits with no error/crash ### Actual Behavior 3. App crashes (~50% reproducibility rate) with following stack: [callstack.txt](https://github.com/electron/electron/files/14065635/callstack.txt) ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/41142
https://github.com/electron/electron/pull/41154
ffec3127d55a31c6735b4364fec5250dbbc5ac64
fc917985ae8165e0cbcc11b3bebbcc995b1bd271
2024-01-26T14:00:54Z
c++
2024-01-30T10:53:19Z
shell/browser/api/electron_api_web_contents_view.cc
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_web_contents_view.h" #include "base/no_destructor.h" #include "gin/data_object_builder.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/browser.h" #include "shell/browser/native_window.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/constructor.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "third_party/skia/include/core/SkRegion.h" #include "ui/base/hit_test.h" #include "ui/views/layout/flex_layout_types.h" #include "ui/views/view_class_properties.h" #include "ui/views/widget/widget.h" #if BUILDFLAG(IS_MAC) #include "shell/browser/ui/cocoa/delayed_native_view_host.h" #endif namespace electron::api { WebContentsView::WebContentsView(v8::Isolate* isolate, gin::Handle<WebContents> web_contents) #if BUILDFLAG(IS_MAC) : View(new DelayedNativeViewHost(web_contents->inspectable_web_contents() ->GetView() ->GetNativeView())), #else : View(web_contents->inspectable_web_contents()->GetView()->GetView()), #endif web_contents_(isolate, web_contents.ToV8()), api_web_contents_(web_contents.get()) { #if !BUILDFLAG(IS_MAC) // On macOS the View is a newly-created |DelayedNativeViewHost| and it is our // responsibility to delete it. On other platforms the View is created and // managed by InspectableWebContents. set_delete_view(false); #endif view()->SetProperty( views::kFlexBehaviorKey, views::FlexSpecification(views::MinimumFlexSizeRule::kScaleToMinimum, views::MaximumFlexSizeRule::kUnbounded)); Observe(web_contents->web_contents()); } WebContentsView::~WebContentsView() { if (api_web_contents_) // destroy() called without closing WebContents api_web_contents_->Destroy(); } gin::Handle<WebContents> WebContentsView::GetWebContents(v8::Isolate* isolate) { if (api_web_contents_) return gin::CreateHandle(isolate, api_web_contents_.get()); else return gin::Handle<WebContents>(); } void WebContentsView::SetBackgroundColor(std::optional<WrappedSkColor> color) { View::SetBackgroundColor(color); if (api_web_contents_) { api_web_contents_->SetBackgroundColor(color); // Also update the web preferences object otherwise the view will be reset // on the next load URL call auto* web_preferences = WebContentsPreferences::From(api_web_contents_->web_contents()); if (web_preferences) { web_preferences->SetBackgroundColor(color); } } } int WebContentsView::NonClientHitTest(const gfx::Point& point) { gfx::Point local_point(point); views::View::ConvertPointFromWidget(view(), &local_point); SkRegion* region = api_web_contents_->draggable_region(); if (region && region->contains(local_point.x(), local_point.y())) return HTCAPTION; return HTNOWHERE; } void WebContentsView::WebContentsDestroyed() { api_web_contents_ = nullptr; web_contents_.Reset(); } void WebContentsView::OnViewAddedToWidget(views::View* observed_view) { DCHECK_EQ(observed_view, view()); views::Widget* widget = view()->GetWidget(); auto* native_window = static_cast<NativeWindow*>( widget->GetNativeWindowProperty(electron::kElectronNativeWindowKey)); if (!native_window) return; native_window->AddDraggableRegionProvider(this); } void WebContentsView::OnViewRemovedFromWidget(views::View* observed_view) { DCHECK_EQ(observed_view, view()); views::Widget* widget = view()->GetWidget(); auto* native_window = static_cast<NativeWindow*>( widget->GetNativeWindowProperty(kElectronNativeWindowKey)); if (!native_window) return; native_window->RemoveDraggableRegionProvider(this); } // static gin::Handle<WebContentsView> WebContentsView::Create( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Value> arg = gin::DataObjectBuilder(isolate) .Set("webPreferences", web_preferences) .Build(); v8::Local<v8::Object> web_contents_view_obj; if (GetConstructor(isolate) ->NewInstance(context, 1, &arg) .ToLocal(&web_contents_view_obj)) { gin::Handle<WebContentsView> web_contents_view; if (gin::ConvertFromV8(isolate, web_contents_view_obj, &web_contents_view)) return web_contents_view; } return gin::Handle<WebContentsView>(); } // static v8::Local<v8::Function> WebContentsView::GetConstructor(v8::Isolate* isolate) { static base::NoDestructor<v8::Global<v8::Function>> constructor; if (constructor.get()->IsEmpty()) { constructor->Reset( isolate, gin_helper::CreateConstructor<WebContentsView>( isolate, base::BindRepeating(&WebContentsView::New))); } return v8::Local<v8::Function>::New(isolate, *constructor.get()); } // static gin_helper::WrappableBase* WebContentsView::New(gin_helper::Arguments* args) { gin_helper::Dictionary web_preferences; { v8::Local<v8::Value> options_value; if (args->GetNext(&options_value)) { gin_helper::Dictionary options; if (!gin::ConvertFromV8(args->isolate(), options_value, &options)) { args->ThrowError("options must be an object"); return nullptr; } v8::Local<v8::Value> web_preferences_value; if (options.Get("webPreferences", &web_preferences_value)) { if (!gin::ConvertFromV8(args->isolate(), web_preferences_value, &web_preferences)) { args->ThrowError("options.webPreferences must be an object"); return nullptr; } } } } if (web_preferences.IsEmpty()) web_preferences = gin_helper::Dictionary::CreateEmpty(args->isolate()); if (!web_preferences.Has(options::kShow)) web_preferences.Set(options::kShow, false); auto web_contents = WebContents::CreateFromWebPreferences(args->isolate(), web_preferences); // Constructor call. auto* view = new WebContentsView(args->isolate(), web_contents); view->InitWithArgs(args); return view; } // static void WebContentsView::BuildPrototype( v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(gin::StringToV8(isolate, "WebContentsView")); gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) .SetMethod("setBackgroundColor", &WebContentsView::SetBackgroundColor) .SetProperty("webContents", &WebContentsView::GetWebContents); } } // namespace electron::api namespace { using electron::api::WebContentsView; 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("WebContentsView", WebContentsView::GetConstructor(isolate)); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents_view, Initialize)
closed
electron/electron
https://github.com/electron/electron
41,136
[Bug]: Regression on the printBackground parameter
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 28.2.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 22.04 ### What arch are you using? x64 ### Last Known Working Electron version 27 ### Expected Behavior When the printBackground parameter of printToPDF is enabled, backgrounds should appear in the PDF. ### Actual Behavior The backgrounds are not visible. ### Testcase Gist URL https://gist.github.com/drivron/1e1be91efbbbbc61e4a528d0e362be9f ### Additional Information _No response_
https://github.com/electron/electron/issues/41136
https://github.com/electron/electron/pull/41161
6786fde576276b8915a4e486ff0c35a3bc1036c0
90c7d6c82383c237977d33ae3da5eeafa93aefc3
2024-01-26T08:25:59Z
c++
2024-01-30T20:47:55Z
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 <optional> #include <set> #include <string> #include <string_view> #include <utility> #include <vector> #include "base/containers/contains.h" #include "base/containers/fixed_flat_map.h" #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/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.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/embedder_support/user_agent_utils.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/navigation_controller_impl.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/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/input/native_web_keyboard_event.h" #include "content/public/common/referrer_type_converters.h" #include "content/public/common/result_codes.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 "media/base/mime_util.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_navigation_throttle.h" #include "shell/browser/file_select_helper.h" #include "shell/browser/native_window.h" #include "shell/browser/osr/osr_render_widget_host_view.h" #include "shell/browser/osr/osr_web_contents_view.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/optional_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/language_util.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "shell/common/thread_restrictions.h" #include "shell/common/v8_value_serializer.h" #include "storage/browser/file_system/isolated_context.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(IS_WIN) #include "shell/browser/native_window_views.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/linux/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 "chrome/browser/printing/print_view_manager_base.h" #include "components/printing/browser/print_manager_utils.h" #include "components/printing/browser/print_to_pdf/pdf_print_result.h" #include "components/printing/browser/print_to_pdf/pdf_print_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" // nogncheck #include "printing/page_range.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #endif #endif // BUILDFLAG(ENABLE_PRINTING) #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_document_helper.h" // nogncheck #include "shell/browser/electron_pdf_document_helper_client.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif #if !IS_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) { using Val = printing::mojom::MarginType; static constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, Val>({ {"custom", Val::kCustomMargins}, {"default", Val::kDefaultMargins}, {"none", Val::kNoMargins}, {"printableArea", Val::kPrintableAreaMargins}, }); return FromV8WithLookup(isolate, val, Lookup, out); } }; template <> struct Converter<printing::mojom::DuplexMode> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::DuplexMode* out) { using Val = printing::mojom::DuplexMode; static constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, Val>({ {"longEdge", Val::kLongEdge}, {"shortEdge", Val::kShortEdge}, {"simplex", Val::kSimplex}, }); return FromV8WithLookup(isolate, val, Lookup, out); } }; #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::JavaScriptDialogType> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, content::JavaScriptDialogType val) { switch (val) { case content::JAVASCRIPT_DIALOG_TYPE_ALERT: return gin::ConvertToV8(isolate, "alert"); case content::JAVASCRIPT_DIALOG_TYPE_CONFIRM: return gin::ConvertToV8(isolate, "confirm"); case content::JAVASCRIPT_DIALOG_TYPE_PROMPT: return gin::ConvertToV8(isolate, "prompt"); } } }; template <> struct Converter<content::SavePageType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::SavePageType* out) { using Val = content::SavePageType; static constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, Val>({ {"htmlcomplete", Val::SAVE_PAGE_TYPE_AS_COMPLETE_HTML}, {"htmlonly", Val::SAVE_PAGE_TYPE_AS_ONLY_HTML}, {"mhtml", Val::SAVE_PAGE_TYPE_AS_MHTML}, }); return FromV8WithLowerLookup(isolate, val, Lookup, out); } }; 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 Val = electron::api::WebContents::Type; static constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, Val>({ {"backgroundPage", Val::kBackgroundPage}, {"browserView", Val::kBrowserView}, {"offscreen", Val::kOffScreen}, {"webview", Val::kWebView}, }); return FromV8WithLookup(isolate, val, Lookup, out); } }; 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::api { namespace { constexpr std::string_view CursorTypeToString( ui::mojom::CursorType cursor_type) { switch (cursor_type) { case ui::mojom::CursorType::kPointer: return "pointer"; case ui::mojom::CursorType::kCross: return "crosshair"; case ui::mojom::CursorType::kHand: return "hand"; case ui::mojom::CursorType::kIBeam: return "text"; case ui::mojom::CursorType::kWait: return "wait"; case ui::mojom::CursorType::kHelp: return "help"; case ui::mojom::CursorType::kEastResize: return "e-resize"; case ui::mojom::CursorType::kNorthResize: return "n-resize"; case ui::mojom::CursorType::kNorthEastResize: return "ne-resize"; case ui::mojom::CursorType::kNorthWestResize: return "nw-resize"; case ui::mojom::CursorType::kSouthResize: return "s-resize"; case ui::mojom::CursorType::kSouthEastResize: return "se-resize"; case ui::mojom::CursorType::kSouthWestResize: return "sw-resize"; case ui::mojom::CursorType::kWestResize: return "w-resize"; case ui::mojom::CursorType::kNorthSouthResize: return "ns-resize"; case ui::mojom::CursorType::kEastWestResize: return "ew-resize"; case ui::mojom::CursorType::kNorthEastSouthWestResize: return "nesw-resize"; case ui::mojom::CursorType::kNorthWestSouthEastResize: return "nwse-resize"; case ui::mojom::CursorType::kColumnResize: return "col-resize"; case ui::mojom::CursorType::kRowResize: return "row-resize"; case ui::mojom::CursorType::kMiddlePanning: return "m-panning"; case ui::mojom::CursorType::kMiddlePanningVertical: return "m-panning-vertical"; case ui::mojom::CursorType::kMiddlePanningHorizontal: return "m-panning-horizontal"; case ui::mojom::CursorType::kEastPanning: return "e-panning"; case ui::mojom::CursorType::kNorthPanning: return "n-panning"; case ui::mojom::CursorType::kNorthEastPanning: return "ne-panning"; case ui::mojom::CursorType::kNorthWestPanning: return "nw-panning"; case ui::mojom::CursorType::kSouthPanning: return "s-panning"; case ui::mojom::CursorType::kSouthEastPanning: return "se-panning"; case ui::mojom::CursorType::kSouthWestPanning: return "sw-panning"; case ui::mojom::CursorType::kWestPanning: return "w-panning"; case ui::mojom::CursorType::kMove: return "move"; case ui::mojom::CursorType::kVerticalText: return "vertical-text"; case ui::mojom::CursorType::kCell: return "cell"; case ui::mojom::CursorType::kContextMenu: return "context-menu"; case ui::mojom::CursorType::kAlias: return "alias"; case ui::mojom::CursorType::kProgress: return "progress"; case ui::mojom::CursorType::kNoDrop: return "nodrop"; case ui::mojom::CursorType::kCopy: return "copy"; case ui::mojom::CursorType::kNone: return "none"; case ui::mojom::CursorType::kNotAllowed: return "not-allowed"; case ui::mojom::CursorType::kZoomIn: return "zoom-in"; case ui::mojom::CursorType::kZoomOut: return "zoom-out"; case ui::mojom::CursorType::kGrab: return "grab"; case ui::mojom::CursorType::kGrabbing: return "grabbing"; case ui::mojom::CursorType::kCustom: return "custom"; case ui::mojom::CursorType::kNull: return "null"; case ui::mojom::CursorType::kDndNone: return "drag-drop-none"; case ui::mojom::CursorType::kDndMove: return "drag-drop-move"; case ui::mojom::CursorType::kDndCopy: return "drag-drop-copy"; case ui::mojom::CursorType::kDndLink: return "drag-drop-link"; case ui::mojom::CursorType::kNorthSouthNoResize: return "ns-no-resize"; case ui::mojom::CursorType::kEastWestNoResize: return "ew-no-resize"; case ui::mojom::CursorType::kNorthEastSouthWestNoResize: return "nesw-no-resize"; case ui::mojom::CursorType::kNorthWestSouthEastNoResize: return "nwse-no-resize"; default: return "default"; } } base::IDMap<WebContents*>& GetAllWebContents() { static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents; return *s_all_web_contents; } void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, base::ScopedClosureRunner capture_handle, const SkBitmap& bitmap) { auto ui_task_runner = content::GetUIThreadTaskRunner({}); if (!ui_task_runner->RunsTasksInCurrentSequence()) { ui_task_runner->PostTask( FROM_HERE, base::BindOnce(&OnCapturePageDone, std::move(promise), std::move(capture_handle), bitmap)); return; } // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); capture_handle.RunAndReset(); } std::optional<base::TimeDelta> GetCursorBlinkInterval() { #if BUILDFLAG(IS_MAC) std::optional<base::TimeDelta> system_value( ui::TextInsertionCaretBlinkPeriodFromDefaults()); if (system_value) return *system_value; #elif BUILDFLAG(IS_LINUX) if (auto* linux_ui = ui::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 std::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::apple::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; #else scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name)); #endif } // This function returns a validated device name. // If the user passed one to webContents.print(), we check that it's valid and // return it or fail if the network doesn't recognize it. If the user didn't // pass a device name, we first try to return the system default printer. If one // isn't set, then pull all the printers and use the first one or fail if none // exist. std::pair<std::string, std::u16string> GetDeviceNameToUse( const std::u16string& device_name) { #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. ScopedAllowBlockingForElectron allow_blocking; #endif if (!device_name.empty()) { if (!IsDeviceNameValid(device_name)) return std::make_pair("Invalid deviceName provided", std::u16string()); return std::make_pair(std::string(), device_name); } 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"; 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()) return std::make_pair("No printers available on the network", std::u16string()); 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::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); } base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) { base::Value::Dict value; value.Set("type", file_system.type); value.Set("fileSystemName", file_system.file_system_name); value.Set("rootURL", file_system.root_url); value.Set("fileSystemPath", file_system.file_system_path); return 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::Dict& file_system_paths = pref_service->GetDict(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; for (auto it : file_system_paths) { 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) { return base::Contains(GetAddedFileSystemPaths(web_contents), file_system_path); } content::RenderFrameHost* GetRenderFrameHost( content::NavigationHandle* navigation_handle) { 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(); } return frame_host; } } // 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::kExtensionPopup: case extensions::mojom::ViewType::kBackgroundContents: case extensions::mojom::ViewType::kExtensionGuest: case extensions::mojom::ViewType::kTabContents: case extensions::mojom::ViewType::kOffscreenDocument: case extensions::mojom::ViewType::kExtensionSidePanel: 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)) #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()); SetUserAgent(GetBrowserContext()->GetUserAgent()); 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)) #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)) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { // Read options. options.Get("backgroundThrottling", &background_throttling_); // Get type options.Get("type", &type_); // Get transparent for guest view options.Get("transparent", &guest_transparent_); bool b = false; if (options.Get(options::kOffscreen, &b) && b) type_ = Type::kOffScreen; // Init embedder earlier options.Get("embedder", &embedder_); // Whether to enable DevTools. options.Get("devTools", &enable_devtools_); bool initially_shown = true; 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 (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 { web_contents = content::WebContents::Create(params); } } 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()); } 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); // Nothing to do with ZoomController, but this function gets called in all // init cases! content::RenderViewHost* host = web_contents->GetRenderViewHost(); if (host) host->GetWidget()->AddInputEventObserver(this); } 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()); SetUserAgent(GetBrowserContext()->GetUserAgent()); 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) PrintViewManagerElectron::CreateForWebContents(web_contents.get()); #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() { if (owner_window_) { owner_window_->RemoveBackgroundThrottlingSource(this); } if (web_contents()) { content::RenderViewHost* host = web_contents()->GetRenderViewHost(); if (host) host->GetWidget()->RemoveInputEventObserver(this); } 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 asynchronously 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(&WebContents::DeleteThisIfAlive, GetWeakPtr())); } } void WebContents::Close(std::optional<gin_helper::Dictionary> options) { bool dispatch_beforeunload = false; if (options) options->Get("waitForBeforeUnload", &dispatch_beforeunload); if (dispatch_beforeunload && web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) { NotifyUserActivation(); web_contents()->DispatchBeforeUnload(false /* auto_cancel */); } else { web_contents()->Close(); } } 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 blink::mojom::WindowFeatures& window_features, 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, window_features.bounds.x(), window_features.bounds.y(), window_features.bounds.width(), window_features.bounds.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) { // Note that Chromium does not emit this for navigations. // Emit returns true if preventDefault() was called, so !Emit will be true if // the event should proceed. *proceed_to_fire_unload = !Emit("-before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { if (!Emit("content-bounds-updated", 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(); } Destroy(); } 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) { // 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) { // For backwards compatibility, pretend that `kRawKeyDown` events are // actually `kKeyDown`. content::NativeWebKeyboardEvent tweaked_event(event); if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown) tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown); bool prevent_default = Emit("before-input-event", tweaked_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 { if (!owner_window()) return false; return owner_window()->IsFullscreen() || is_html_fullscreen(); } 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 notify_download, 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(requesting_frame, callback); } 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; } owner_window()->set_fullscreen_transition_type( NativeWindow::FullScreenTransitionType::kHTML); exclusive_access_manager_.fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); 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; } 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); auto result = gin_helper::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::OnRequestToLockMouse(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::OnRequestToLockMouse, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_.mouse_lock_controller()->LostMouseLock(); } void WebContents::OnRequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked, bool allowed) { if (allowed) { exclusive_access_manager_.keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } else { web_contents->GotResponseToKeyboardLockRequest(false); } } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestKeyboardLockPermission( esc_key_locked, base::BindOnce(&WebContents::OnRequestKeyboardLock, base::Unretained(this))); } 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 url::Origin& 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)); } const void* const kJavaScriptDialogManagerKey = &kJavaScriptDialogManagerKey; content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { // Indirect these delegate methods through a helper object whose lifetime is // bound to that of the content::WebContents. This prevents the // content::WebContents from calling methods on the Electron WebContents in // the event that the Electron one is destroyed before the content one, as // happens sometimes during shutdown or when webviews are involved. class JSDialogManagerHelper : public content::JavaScriptDialogManager, public base::SupportsUserData::Data { public: void RunJavaScriptDialog(content::WebContents* web_contents, content::RenderFrameHost* rfh, content::JavaScriptDialogType dialog_type, const std::u16string& message_text, const std::u16string& default_prompt_text, DialogClosedCallback callback, bool* did_suppress_message) override { auto* wc = WebContents::From(web_contents); if (wc) wc->RunJavaScriptDialog(web_contents, rfh, dialog_type, message_text, default_prompt_text, std::move(callback), did_suppress_message); } void RunBeforeUnloadDialog(content::WebContents* web_contents, content::RenderFrameHost* rfh, bool is_reload, DialogClosedCallback callback) override { auto* wc = WebContents::From(web_contents); if (wc) wc->RunBeforeUnloadDialog(web_contents, rfh, is_reload, std::move(callback)); } void CancelDialogs(content::WebContents* web_contents, bool reset_state) override { auto* wc = WebContents::From(web_contents); if (wc) wc->CancelDialogs(web_contents, reset_state); } }; if (!source->GetUserData(kJavaScriptDialogManagerKey)) source->SetUserData(kJavaScriptDialogManagerKey, std::make_unique<JSDialogManagerHelper>()); return static_cast<JSDialogManagerHelper*>( source->GetUserData(kJavaScriptDialogManagerKey)); } void WebContents::OnAudioStateChanged(bool audible) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>(); gin::Dictionary dict(isolate, event_object); dict.Set("audible", audible); EmitWithoutEvent("audio-state-changed", event); } void WebContents::BeforeUnloadFired(bool proceed) { // 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) SetBackgroundColor(web_preferences->GetBackgroundColor()); 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->MaybeSetupMojoConnection(); } void WebContents::OnBackgroundColorChanged() { std::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); auto 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. // // 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) { if (new_host->IsInPrimaryMainFrame()) { if (old_host) old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this); if (new_host) new_host->GetRenderWidgetHost()->AddInputEventObserver(this); } // 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::FromRenderFrameHost(new_host); 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) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto 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) { // See DocumentLoader::StartLoadingResponse() - when we navigate to a media // resource the original request for the media resource, which resulted in a // committed navigation, is simply discarded. The media element created // inside the MediaDocument then makes *another new* request for the same // media resource. bool is_media_document = media::IsSupportedMediaMimeType(web_contents()->GetContentsMimeType()); if (error_code == net::ERR_ABORTED && is_media_document) return; 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_name, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_process_id = -1, frame_routing_id = -1; content::RenderFrameHost* frame_host = GetRenderFrameHost(navigation_handle); 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(); content::RenderFrameHost* initiator_frame_host = navigation_handle->GetInitiatorFrameToken().has_value() ? content::RenderFrameHost::FromFrameToken( content::GlobalRenderFrameHostToken( navigation_handle->GetInitiatorProcessId(), navigation_handle->GetInitiatorFrameToken().value())) : nullptr; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>(); gin_helper::Dictionary dict(isolate, event_object); dict.Set("url", url); dict.Set("isSameDocument", is_same_document); dict.Set("isMainFrame", is_main_frame); dict.SetGetter("frame", frame_host); dict.SetGetter("initiator", initiator_frame_host); EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); return event->GetDefaultPrevented(); } 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()->GetPrimaryMainFrame()) { Emit("ready-to-show"); } } // This object wraps the InvokeCallback so that if it gets GC'd by V8, we can // still call the callback and send an error. Not doing so causes a Mojo DCHECK, // since Mojo requires callbacks to be called before they are destroyed. class ReplyChannel : public gin::Wrappable<ReplyChannel> { public: using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback; static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate, InvokeCallback callback) { return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback))); } // gin::Wrappable static gin::WrapperInfo kWrapperInfo; gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override { return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate) .SetMethod("sendReply", &ReplyChannel::SendReply); } const char* GetTypeName() override { return "ReplyChannel"; } void SendError(const std::string& msg) { v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate(); // If there's no current context, it means we're shutting down, so we // don't need to send an event. if (!isolate->GetCurrentContext().IsEmpty()) { v8::HandleScope scope(isolate); auto message = gin::DataObjectBuilder(isolate).Set("error", msg).Build(); SendReply(isolate, message); } } private: explicit ReplyChannel(InvokeCallback callback) : callback_(std::move(callback)) {} ~ReplyChannel() override { if (callback_) SendError("reply was never sent"); } bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) { if (!callback_) return false; blink::CloneableMessage message; if (!gin::ConvertFromV8(isolate, arg, &message)) { return false; } std::move(callback_).Run(std::move(message)); return true; } InvokeCallback callback_; }; gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin}; gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender( v8::Isolate* isolate, content::RenderFrameHost* frame, electron::mojom::ElectronApiIPC::InvokeCallback callback) { v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) { if (callback) { // We must always invoke the callback if present. ReplyChannel::Create(isolate, std::move(callback)) ->SendError("WebContents was destroyed"); } return gin::Handle<gin_helper::internal::Event>(); } gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>()); if (callback) dict.Set("_replyChannel", ReplyChannel::Create(isolate, std::move(callback))); if (frame) { dict.Set("frameId", frame->GetRoutingID()); dict.Set("processId", frame->GetProcess()->GetID()); } return event; } 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::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) { if (owner_window() && owner_window()->has_frame()) return; draggable_region_ = DraggableRegionsToSkRegion(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. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "setInspectedTabId", base::Value(ID())); // 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::SetOwnerBaseWindow(std::optional<BaseWindow*> owner_window) { SetOwnerWindow(GetWebContents(), owner_window ? (*owner_window)->window() : nullptr); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window_) { owner_window_->RemoveBackgroundThrottlingSource(this); } if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); owner_window_->AddBackgroundThrottlingSource(this); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); } 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; if (owner_window_) { owner_window_->UpdateBackgroundThrottlingState(); } auto* rfh = web_contents()->GetPrimaryMainFrame(); 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()->GetPrimaryMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents() ->GetPrimaryMainFrame() ->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)) SetUserAgent(user_agent); 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; // It's not safe to start a new navigation or otherwise discard the current // one while the call that started it is still on the stack. See // http://crbug.com/347742. auto& ctrl_impl = static_cast<content::NavigationControllerImpl&>( web_contents()->GetController()); if (ctrl_impl.in_navigate_to_pending_entry()) { Emit("did-fail-load", static_cast<int>(net::ERR_FAILED), net::ErrorToShortString(net::ERR_FAILED), url.possibly_invalid_spec(), true); return; } // Discard non-committed entries to ensure 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, gin::Arguments* args) { std::map<std::string, std::string> headers; gin_helper::Dictionary options; if (args->GetNext(&options)) { if (options.Has("headers") && !options.Get("headers", &headers)) { args->ThrowTypeError("Invalid value for headers - must be an object"); return; } } std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); for (const auto& [name, value] : headers) { download_params->add_request_header(name, value); } auto* download_manager = web_contents()->GetBrowserContext()->GetDownloadManager(); 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(); } v8::Local<v8::Value> WebContents::GetWebRTCUDPPortRange( v8::Isolate* isolate) const { auto* prefs = web_contents()->GetMutableRendererPrefs(); auto dict = gin_helper::Dictionary::CreateEmpty(isolate); dict.Set("min", static_cast<uint32_t>(prefs->webrtc_udp_min_port)); dict.Set("max", static_cast<uint32_t>(prefs->webrtc_udp_max_port)); return dict.GetHandle(); } void WebContents::SetWebRTCUDPPortRange(gin::Arguments* args) { uint32_t min = 0, max = 0; gin_helper::Dictionary range; if (!args->GetNext(&range) || !range.Get("min", &min) || !range.Get("max", &max)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'min' and 'max' are both required"); return; } if ((0 == min && 0 != max) || max > UINT16_MAX) { gin_helper::ErrorThrower(args->isolate()) .ThrowError( "'min' and 'max' must be in the (0, 65535] range or [0, 0]"); return; } if (min > max) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'max' must be greater than or equal to 'min'"); return; } auto* prefs = web_contents()->GetMutableRendererPrefs(); if (prefs->webrtc_udp_min_port == static_cast<uint16_t>(min) && prefs->webrtc_udp_max_port == static_cast<uint16_t>(max)) { return; } prefs->webrtc_udp_min_port = min; prefs->webrtc_udp_max_port = max; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetPrimaryMainFrame(); 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->GetPrimaryMainFrame(); 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. #if !IS_MAS_BUILD() CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { blink::UserAgentOverride ua_override; ua_override.ua_string_override = user_agent; if (!user_agent.empty()) ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata(); web_contents()->SetUserAgentOverride(ua_override, 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; std::string title; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); options.Get("title", &title); } } DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->SetDevToolsTitle(base::UTF8ToUTF16(title)); 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(); } std::u16string WebContents::GetDevToolsTitle() { if (type_ == Type::kRemote) return std::u16string(); DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetDevToolsTitle(); } void WebContents::SetDevToolsTitle(const std::u16string& title) { inspectable_web_contents_->SetDevToolsTitle(title); } 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()->GetPrimaryMainFrame(); 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()->GetPrimaryMainFrame(); 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::OnGetDeviceNameToUse( base::Value::Dict print_settings, printing::CompletionCallback print_callback, bool silent, // <error, device_name> 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. print_settings.Set(printing::kSettingDeviceName, info.second); 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()->GetPrimaryMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { auto options = gin_helper::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 auto margins = gin_helper::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); 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_dict; // Chromium uses 1-based page ranges, so increment each by 1. range_dict.Set(printing::kSettingPageRangeFrom, from + 1); range_dict.Set(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range_dict)); } 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::DICT); 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(&GetDeviceNameToUse, device_name), base::BindOnce(&WebContents::OnGetDeviceNameToUse, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), silent)); } // Partially duplicated and modified from // headless/lib/browser/protocol/page_handler.cc;l=41 v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); // This allows us to track headless printing calls. auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID); auto landscape = settings.GetDict().FindBool("landscape"); auto display_header_footer = settings.GetDict().FindBool("displayHeaderFooter"); auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds"); auto scale = settings.GetDict().FindDouble("scale"); auto paper_width = settings.GetDict().FindDouble("paperWidth"); auto paper_height = settings.GetDict().FindDouble("paperHeight"); auto margin_top = settings.GetDict().FindDouble("marginTop"); auto margin_bottom = settings.GetDict().FindDouble("marginBottom"); auto margin_left = settings.GetDict().FindDouble("marginLeft"); auto margin_right = settings.GetDict().FindDouble("marginRight"); auto page_ranges = *settings.GetDict().FindString("pageRanges"); auto header_template = *settings.GetDict().FindString("headerTemplate"); auto footer_template = *settings.GetDict().FindString("footerTemplate"); auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize"); auto generate_tagged_pdf = settings.GetDict().FindBool("generateTaggedPDF"); auto generate_document_outline = settings.GetDict().FindBool("generateDocumentOutline"); absl::variant<printing::mojom::PrintPagesParamsPtr, std::string> print_pages_params = print_to_pdf::GetPrintPagesParams( web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(), landscape, display_header_footer, print_background, scale, paper_width, paper_height, margin_top, margin_bottom, margin_left, margin_right, std::make_optional(header_template), std::make_optional(footer_template), prefer_css_page_size, generate_tagged_pdf, generate_document_outline); if (absl::holds_alternative<std::string>(print_pages_params)) { auto error = absl::get<std::string>(print_pages_params); promise.RejectWithErrorMessage("Invalid print parameters: " + error); return handle; } auto* manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!manager) { promise.RejectWithErrorMessage("Failed to find print manager"); return handle; } auto params = std::move( absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params)); params->params->document_cookie = unique_id.value_or(0); manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges, std::move(params), base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(), std::move(promise))); return handle; } void WebContents::OnPDFCreated( gin_helper::Promise<v8::Local<v8::Value>> promise, print_to_pdf::PdfPrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + print_to_pdf::PdfPrintResultToString(print_result)); return; } v8::Isolate* isolate = promise.isolate(); gin_helper::Locker locker(isolate); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope( v8::Local<v8::Context>::New(isolate, promise.GetContext())); v8::Local<v8::Value> buffer = node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()), data->size()) .ToLocalChecked(); promise.Resolve(buffer); } #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::CenterSelection() { web_contents()->CenterSelection(); } 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::ScrollToTopOfDocument() { web_contents()->ScrollToTopOfDocument(); } void WebContents::ScrollToBottomOfDocument() { web_contents()->ScrollToBottomOfDocument(); } void WebContents::AdjustSelectionByCharacterOffset(gin::Arguments* args) { int start_adjust = 0; int end_adjust = 0; gin_helper::Dictionary dict; if (args->GetNext(&dict)) { dict.Get("start", &start_adjust); dict.Get("matchCase", &end_adjust); } // The selection menu is a Chrome-specific piece of UI. // TODO(codebytere): maybe surface as an event in the future? web_contents()->AdjustSelectionByCharacterOffset( start_adjust, end_adjust, false /* show_selection_menu */); } 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()->GetPrimaryMainFrame(); 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()) { GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); } 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)) { // For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`. if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown) keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown); 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()) { GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); } 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::ScopedAllowApplicationTasksInNativeNestedLoop 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) { gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); gfx::Rect rect; args->GetNext(&rect); bool stay_hidden = false; bool stay_awake = false; if (args && args->Length() == 2) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("stayHidden", &stay_hidden); options.Get("stayAwake", &stay_awake); } } auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view || view->GetViewBounds().size().IsEmpty()) { promise.Resolve(gfx::Image()); return handle; } if (!view->IsSurfaceAvailableForCopy()) { promise.RejectWithErrorMessage( "Current display surface not available for capture"); return handle; } auto capture_handle = web_contents()->IncrementCapturerCount( rect.size(), stay_hidden, stay_awake); // 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), std::move(capture_handle))); return handle; } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const ui::Cursor& cursor) { if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor.type()), 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.type())); } } 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 { return type_ == Type::kOffScreen; } 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; } void WebContents::Invalidate() { if (IsOffScreen()) { auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); } 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()->GetPrimaryMainFrame(); } content::RenderFrameHost* WebContents::Opener() { return web_contents()->GetOpener(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame(); 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(); } void WebContents::SetBackgroundColor(std::optional<SkColor> maybe_color) { SkColor color = maybe_color.value_or((IsGuest() && guest_transparent_) || type_ == Type::kBrowserView ? SK_ColorTRANSPARENT : SK_ColorWHITE); web_contents()->SetPageBaseBackgroundColor(color); content::RenderFrameHost* rfh = web_contents()->GetPrimaryMainFrame(); if (!rfh) return; content::RenderWidgetHostView* rwhv = rfh->GetView(); if (rwhv) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } void WebContents::OnInputEvent(const blink::WebInputEvent& event) { Emit("input-event", event); } void WebContents::RunJavaScriptDialog(content::WebContents* web_contents, content::RenderFrameHost* rfh, content::JavaScriptDialogType dialog_type, const std::u16string& message_text, const std::u16string& default_prompt_text, DialogClosedCallback callback, bool* did_suppress_message) { CHECK_EQ(web_contents, this->web_contents()); auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto info = gin::DataObjectBuilder(isolate) .Set("frame", rfh) .Set("dialogType", dialog_type) .Set("messageText", message_text) .Set("defaultPromptText", default_prompt_text) .Build(); EmitWithoutEvent("-run-dialog", info, std::move(callback)); } void WebContents::RunBeforeUnloadDialog(content::WebContents* web_contents, content::RenderFrameHost* rfh, bool is_reload, DialogClosedCallback callback) { // TODO: asyncify? bool default_prevented = Emit("will-prevent-unload"); std::move(callback).Run(default_prevented, std::u16string()); } void WebContents::CancelDialogs(content::WebContents* web_contents, bool reset_state) { auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitWithoutEvent( "-cancel-dialogs", gin::DataObjectBuilder(isolate).Set("resetState", reset_state).Build()); } 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()->GetPrimaryMainFrame(); 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(); ScopedAllowBlockingForElectron allow_blocking; uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE; // The snapshot file is passed to an untrusted process. flags = base::File::AddFlagsForPassingToUntrustedProcess(flags); base::File file(file_path, flags); if (!file.IsValid()) { promise.RejectWithErrorMessage( "Failed to take heap snapshot with invalid file path " + #if BUILDFLAG(IS_WIN) base::WideToUTF8(file_path.value())); #else file_path.value()); #endif return handle; } auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage( "Failed to take heap snapshot with invalid webContents main frame"); return handle; } if (!frame_host->IsRenderFrameLive()) { promise.RejectWithErrorMessage( "Failed to take heap snapshot with nonexistent render frame"); 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("Failed to take heap snapshot"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } 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) { if (!owner_window()) return is_html_fullscreen(); bool in_transition = owner_window()->fullscreen_transition_state() != NativeWindow::FullScreenTransitionState::kNone; bool is_html_transition = owner_window()->fullscreen_transition_type() == NativeWindow::FullScreenTransitionType::kHTML; return is_html_fullscreen() || (in_transition && is_html_transition); } content::FullscreenState WebContents::GetFullscreenState( const content::WebContents* source) const { // `const_cast` here because EAM does not have const getters return const_cast<ExclusiveAccessManager*>(&exclusive_access_manager_) ->fullscreen_controller() ->GetFullscreenState(source); } 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) { return PictureInPictureWindowManager::GetInstance() ->EnterVideoPictureInPicture(web_contents); } void WebContents::ExitPictureInPicture() { PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); } 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)) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "canceledSaveURL", base::Value(url)); return; } } saved_files_[url] = path; // Notify DevTools. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "savedURL", base::Value(url), base::Value(path.AsUTF8Unsafe())); 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. inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL", base::Value(url)); 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()) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List())); 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::Value::List file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(std::move(file_system_value))); } 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); base::Value::Dict file_system_value = CreateFileSystemValue(file_system); auto* pref_service = GetPrefService(GetDevToolsWebContents()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Set(path.AsUTF8Unsafe(), type); std::string error = ""; // No error inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemAdded", base::Value(error), base::Value(std::move(file_system_value))); } 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()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Remove(path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemRemoved", base::Value(path)); } 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::optional<base::Value> parsed_excluded_folders = base::JSONReader::Read(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetList()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsOpenInNewTab(const std::string& url) { Emit("devtools-open-url", url); } 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::Value::Dict color; color.Set("r", r); color.Set("g", g); color.Set("b", b); color.Set("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color))); } #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) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id), base::Value(file_system_path), base::Value(total_work)); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingWorked", base::Value(request_id), base::Value(file_system_path), base::Value(worked)); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone", base::Value(request_id), base::Value(file_system_path)); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::Value::List file_paths_value; for (const auto& file_path : file_paths) file_paths_value.Append(file_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "searchCompleted", base::Value(request_id), base::Value(file_system_path), base::Value(std::move(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(), [&](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; }); } } // static void WebContents::FillObjectTemplate(v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = GetClassName(); 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. gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("close", &WebContents::Close) .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("getDevToolsTitle", &WebContents::GetDevToolsTitle) .SetMethod("setDevToolsTitle", &WebContents::SetDevToolsTitle) .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("centerSelection", &WebContents::CenterSelection) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("scrollToTop", &WebContents::ScrollToTopOfDocument) .SetMethod("scrollToBottom", &WebContents::ScrollToBottomOfDocument) .SetMethod("adjustSelection", &WebContents::AdjustSelectionByCharacterOffset) .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) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) .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("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("setWebRTCUDPPortRange", &WebContents::SetWebRTCUDPPortRange) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("getWebRTCUDPPortRange", &WebContents::GetWebRTCUDPPortRange) .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) .SetProperty("opener", &WebContents::Opener) .SetMethod("_setOwnerWindow", &WebContents::SetOwnerBaseWindow) .Build(); } const char* WebContents::GetTypeName() { return GetClassName(); } 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); web_contents->SetBackgroundColor( existing_preferences->GetBackgroundColor()); } } 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 std::list<WebContents*> WebContents::GetWebContentsList() { std::list<WebContents*> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(iter.GetCurrentValue()); } return list; } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace electron::api namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; using electron::api::WebFrameMain; 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> WebContentsFromFrame(v8::Isolate* isolate, WebFrameMain* web_frame) { content::RenderFrameHost* rfh = web_frame->render_frame_host(); content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh); WebContents* contents = WebContents::From(source); 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("fromFrame", &WebContentsFromFrame); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
41,064
[Bug]: webContents.PrintToPdf() fails with "Invalid print parameter: Content area is empty."
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 28.1.2 ### What operating system are you using? Windows ### Operating System Version Windows 11 Pro, version 22H2, OS Build 22621.3007 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior 1. I pass the `PrintToPDFOptions` of `webContents.PrintToPdf()` from the UI to the IPC. 2. if I specify an excessive `margins` value (e.g. 10), I get an error with the message `Invalid print parameter: Content area is empty.` 3. again, if I set a minimum `margins` value (e.g. 0) in the UI, it should work fine ### Actual Behavior - After the error, the error still occurs even with a minimum `margins` value. (e.g. 0) - After the error, I have to re-run `Electron` to get it to work. - I haven't checked if recreating the `BrowserWindow` will make it okay. ### Testcase Gist URL _No response_ ### Additional Information @codebytere - The `print_to_pdf::GetPrintPagesParams()` in [electron_api_web_contents.cc](https://github.com/electron/electron/blob/1300e83884595a3c89c24bd4d42f3a1bbbb6fe7d/shell/browser/api/electron_api_web_contents.cc#L3179) is a static function, which is affected by the previous error. - It looks like `print_to_pdf` is a Chromium open source module, and I'd like to know what process manages it.
https://github.com/electron/electron/issues/41064
https://github.com/electron/electron/pull/41157
85bebfb18073d623f1963f8c5a6d9b24295d691d
6df34436171f5b0fad1fd343de08621ce3a8b669
2024-01-21T14:29:41Z
c++
2024-01-31T09:48:41Z
lib/browser/api/web-contents.ts
import { app, ipcMain, session, webFrameMain, dialog } from 'electron/main'; import type { BrowserWindowConstructorOptions, LoadURLOptions, MessageBoxOptions, WebFrameMain } 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'; import { IpcMainImpl } from '@electron/internal/browser/ipc-main-impl'; import * as deprecate from '@electron/internal/common/deprecate'; // session is not used here, the purpose is to make sure session is initialized // before the webContents module. // eslint-disable-next-line no-unused-expressions session; const webFrameMainBinding = process._linkedBinding('electron_browser_web_frame_main'); let nextId = 0; const getNextId = function () { return ++nextId; }; type PostData = LoadURLOptions['postData'] // Stock page sizes const PDFPageSizes: Record<string, ElectronInternal.MediaSize> = { Letter: { custom_display_name: 'Letter', height_microns: 279400, name: 'NA_LETTER', width_microns: 215900 }, Legal: { custom_display_name: 'Legal', height_microns: 355600, name: 'NA_LEGAL', width_microns: 215900 }, Tabloid: { height_microns: 431800, name: 'NA_LEDGER', width_microns: 279400, custom_display_name: 'Tabloid' }, A0: { custom_display_name: 'A0', height_microns: 1189000, name: 'ISO_A0', width_microns: 841000 }, A1: { custom_display_name: 'A1', height_microns: 841000, name: 'ISO_A1', width_microns: 594000 }, A2: { custom_display_name: 'A2', height_microns: 594000, name: 'ISO_A2', width_microns: 420000 }, A3: { custom_display_name: 'A3', height_microns: 420000, name: 'ISO_A3', width_microns: 297000 }, A4: { custom_display_name: 'A4', height_microns: 297000, name: 'ISO_A4', is_default: 'true', width_microns: 210000 }, A5: { custom_display_name: 'A5', height_microns: 210000, name: 'ISO_A5', width_microns: 148000 }, A6: { custom_display_name: 'A6', height_microns: 148000, name: 'ISO_A6', width_microns: 105000 } } as const; const paperFormats: Record<string, ElectronInternal.PageSize> = { letter: { width: 8.5, height: 11 }, legal: { width: 8.5, height: 14 }, tabloid: { width: 11, height: 17 }, ledger: { width: 17, height: 11 }, a0: { width: 33.1, height: 46.8 }, a1: { width: 23.4, height: 33.1 }, a2: { width: 16.54, height: 23.4 }, a3: { width: 11.7, height: 16.54 }, a4: { width: 8.27, height: 11.7 }, a5: { width: 5.83, height: 8.27 }, a6: { width: 4.13, height: 5.83 } } 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); }; // 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; }; // 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); }; function checkType<T> (value: T, type: 'number' | 'boolean' | 'string' | 'object', name: string): T { // eslint-disable-next-line valid-typeof if (typeof value !== type) { throw new TypeError(`${name} must be a ${type}`); } return value; } function parsePageSize (pageSize: string | ElectronInternal.PageSize) { if (typeof pageSize === 'string') { const format = paperFormats[pageSize.toLowerCase()]; if (!format) { throw new Error(`Invalid pageSize ${pageSize}`); } return { paperWidth: format.width, paperHeight: format.height }; } else if (typeof pageSize === 'object') { if (typeof pageSize.width !== 'number' || typeof pageSize.height !== 'number') { throw new TypeError('width and height properties are required for pageSize'); } return { paperWidth: pageSize.width, paperHeight: pageSize.height }; } else { throw new TypeError('pageSize must be a string or an object'); } } // Translate the options of printToPDF. let pendingPromise: Promise<any> | undefined; WebContents.prototype.printToPDF = async function (options) { const margins = checkType(options.margins ?? {}, 'object', 'margins'); const printSettings = { requestID: getNextId(), landscape: checkType(options.landscape ?? false, 'boolean', 'landscape'), displayHeaderFooter: checkType(options.displayHeaderFooter ?? false, 'boolean', 'displayHeaderFooter'), headerTemplate: checkType(options.headerTemplate ?? '', 'string', 'headerTemplate'), footerTemplate: checkType(options.footerTemplate ?? '', 'string', 'footerTemplate'), printBackground: checkType(options.printBackground ?? false, 'boolean', 'printBackground'), scale: checkType(options.scale ?? 1.0, 'number', 'scale'), marginTop: checkType(margins.top ?? 0.4, 'number', 'margins.top'), marginBottom: checkType(margins.bottom ?? 0.4, 'number', 'margins.bottom'), marginLeft: checkType(margins.left ?? 0.4, 'number', 'margins.left'), marginRight: checkType(margins.right ?? 0.4, 'number', 'margins.right'), pageRanges: checkType(options.pageRanges ?? '', 'string', 'pageRanges'), preferCSSPageSize: checkType(options.preferCSSPageSize ?? false, 'boolean', 'preferCSSPageSize'), generateTaggedPDF: checkType(options.generateTaggedPDF ?? false, 'boolean', 'generateTaggedPDF'), generateDocumentOutline: checkType(options.generateDocumentOutline ?? false, 'boolean', 'generateDocumentOutline'), ...parsePageSize(options.pageSize ?? 'letter') }; if (this._printToPDF) { if (pendingPromise) { pendingPromise = pendingPromise.then(() => this._printToPDF(printSettings)); } else { pendingPromise = this._printToPDF(printSettings); } return pendingPromise; } else { throw new Error('Printing feature is disabled'); } }; // TODO(codebytere): deduplicate argument sanitization by moving rest of // print param logic into new file shared between printToPDF and print WebContents.prototype.print = function (options: ElectronInternal.WebContentsPrintOptions, callback) { if (typeof options !== 'object') { throw new TypeError('webContents.print(): Invalid print settings specified.'); } const printSettings: Record<string, any> = { ...options }; const pageSize = options.pageSize ?? 'A4'; 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 RangeError('height and width properties must be minimum 352 microns.'); } printSettings.mediaSize = { name: 'CUSTOM', custom_display_name: 'Custom', height_microns: height, width_microns: width, imageable_area_left_microns: 0, imageable_area_bottom_microns: 0, imageable_area_right_microns: width, imageable_area_top_microns: height }; } else if (typeof pageSize === 'string' && PDFPageSizes[pageSize]) { const mediaSize = PDFPageSizes[pageSize]; printSettings.mediaSize = { ...mediaSize, imageable_area_left_microns: 0, imageable_area_bottom_microns: 0, imageable_area_right_microns: mediaSize.width_microns, imageable_area_top_microns: mediaSize.height_microns }; } else { throw new Error(`Unsupported pageSize: ${pageSize}`); } if (this._print) { if (callback) { this._print(printSettings, callback); } else { this._print(printSettings); } } else { console.error('Error: Printing feature is disabled.'); } }; 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 TypeError('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 })); }; type LoadError = { errorCode: number, errorDescription: string, url: string }; WebContents.prototype.loadURL = function (url, options) { const p = new Promise<void>((resolve, reject) => { const resolveAndCleanup = () => { removeListeners(); resolve(); }; let error: LoadError | undefined; const rejectAndCleanup = ({ errorCode, errorDescription, url }: LoadError) => { 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 = () => { if (error) { rejectAndCleanup(error); } else { resolveAndCleanup(); } }; const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => { if (!error && isMainFrame) { error = { errorCode, errorDescription, url: validatedURL }; } }; let navigationStarted = false; let browserInitiatedInPageNavigation = 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({ errorCode: -3, errorDescription: 'ERR_ABORTED', url }); } browserInitiatedInPageNavigation = navigationStarted && isSameDocument; 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. if (!error) { error = { errorCode: -2, errorDescription: 'ERR_FAILED', url: url }; } finishListener(); }; const finishListenerWhenUserInitiatedNavigation = () => { if (!browserInitiatedInPageNavigation) { finishListener(); } }; const removeListeners = () => { this.removeListener('did-finish-load', finishListener); this.removeListener('did-fail-load', failListener); this.removeListener('did-navigate-in-page', finishListenerWhenUserInitiatedNavigation); 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-navigate-in-page', finishListenerWhenUserInitiatedNavigation); 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 ?? {}); 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') { return { browserWindowConstructorOptions: typeof response.overrideBrowserWindowOptions === 'object' ? response.overrideBrowserWindowOptions : null, 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 addSenderToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent, sender: Electron.WebContents) => { event.sender = sender; 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._replyChannel.sendReply(value), get: () => {} }); }; const getWebFrameForEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => { if (!event.processId || !event.frameId) return null; return webFrameMainBinding.fromIdOrNull(event.processId, event.frameId); }; 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; const ipc = new IpcMainImpl(); Object.defineProperty(this, 'ipc', { get () { return ipc; }, enumerable: true }); // 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[]) { addSenderToEvent(event, this); if (internal) { ipcMainInternal.emit(channel, event, ...args); } else { addReplyToEvent(event); this.emit('ipc-message', event, channel, ...args); const maybeWebFrame = getWebFrameForEvent(event); maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, ...args); ipc.emit(channel, event, ...args); ipcMain.emit(channel, event, ...args); } }); this.on('-ipc-invoke' as any, async function (this: Electron.WebContents, event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) { addSenderToEvent(event, this); const replyWithResult = (result: any) => event._replyChannel.sendReply({ result }); const replyWithError = (error: Error) => { console.error(`Error occurred in handler for '${channel}':`, error); event._replyChannel.sendReply({ error: error.toString() }); }; const maybeWebFrame = getWebFrameForEvent(event); const targets: (ElectronInternal.IpcMainInternal| undefined)[] = internal ? [ipcMainInternal] : [maybeWebFrame?.ipc, ipc, ipcMain]; const target = targets.find(target => target && (target as any)._invokeHandlers.has(channel)); if (target) { const handler = (target as any)._invokeHandlers.get(channel); try { replyWithResult(await Promise.resolve(handler(event, ...args))); } catch (err) { replyWithError(err as Error); } } else { replyWithError(new Error(`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[]) { addSenderToEvent(event, this); addReturnValueToEvent(event); if (internal) { ipcMainInternal.emit(channel, event, ...args); } else { addReplyToEvent(event); const maybeWebFrame = getWebFrameForEvent(event); if (this.listenerCount('ipc-message-sync') === 0 && ipc.listenerCount(channel) === 0 && ipcMain.listenerCount(channel) === 0 && (!maybeWebFrame || maybeWebFrame.ipc.listenerCount(channel) === 0)) { console.warn(`WebContents #${this.id} called ipcRenderer.sendSync() with '${channel}' channel without listeners.`); } this.emit('ipc-message-sync', event, channel, ...args); maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, ...args); ipc.emit(channel, event, ...args); ipcMain.emit(channel, event, ...args); } }); this.on('-ipc-ports' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) { addSenderToEvent(event, this); event.ports = ports.map(p => new MessagePortMain(p)); const maybeWebFrame = getWebFrameForEvent(event); maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, message); ipc.emit(channel, event, message); ipcMain.emit(channel, event, message); }); 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.`); } }); this.on('-before-unload-fired' as any, function (this: Electron.WebContents, event: Electron.Event, proceed: boolean) { const type = this.getType(); // These are the "interactive" types, i.e. ones a user might be looking at. // All other types should ignore the "proceed" signal and unload // regardless. if (type === 'window' || type === 'offscreen' || type === 'browserView') { if (!proceed) { return event.preventDefault(); } } }); // 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: Electron.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 }; let result: ReturnType<typeof this._callWindowOpenHandler>; try { result = this._callWindowOpenHandler(event, details); } catch (err) { event.preventDefault(); throw err; } const options = result.browserWindowConstructorOptions; if (!event.defaultPrevented) { openGuestWindow({ embedder: this, 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: Electron.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 }; let result: ReturnType<typeof this._callWindowOpenHandler>; try { result = this._callWindowOpenHandler(event, details); } catch (err) { event.preventDefault(); throw err; } 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; const { webPreferences: parsedWebPreferences } = parseFeatures(rawFeatures); const webPreferences = makeWebPreferences({ embedder: this, insecureParsedWebPreferences: parsedWebPreferences, secureOverrideWebPreferences }); windowOpenOverriddenOptions = { ...windowOpenOverriddenOptions, webPreferences }; this._setNextChildWebPreferences(webPreferences); } }); // Create a new browser window for "window.open" this.on('-add-new-contents' as any, (event: Electron.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({ embedder: this, 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 originCounts = new Map<string, number>(); const openDialogs = new Set<AbortController>(); this.on('-run-dialog' as any, async (info: {frame: WebFrameMain, dialogType: 'prompt' | 'confirm' | 'alert', messageText: string, defaultPromptText: string}, callback: (success: boolean, user_input: string) => void) => { const originUrl = new URL(info.frame.url); const origin = originUrl.protocol === 'file:' ? originUrl.href : originUrl.origin; if ((originCounts.get(origin) ?? 0) < 0) return callback(false, ''); const prefs = this.getLastWebPreferences(); if (!prefs || prefs.disableDialogs) return callback(false, ''); // We don't support prompt() for some reason :) if (info.dialogType === 'prompt') return callback(false, ''); originCounts.set(origin, (originCounts.get(origin) ?? 0) + 1); // TODO: translate? const checkbox = originCounts.get(origin)! > 1 && prefs.safeDialogs ? prefs.safeDialogsMessage || 'Prevent this app from creating additional dialogs' : ''; const parent = this.getOwnerBrowserWindow(); const abortController = new AbortController(); const options: MessageBoxOptions = { message: info.messageText, checkboxLabel: checkbox, signal: abortController.signal, ...(info.dialogType === 'confirm') ? { buttons: ['OK', 'Cancel'], defaultId: 0, cancelId: 1 } : { buttons: ['OK'], defaultId: -1, // No default button cancelId: 0 } }; openDialogs.add(abortController); const promise = parent && !prefs.offscreen ? dialog.showMessageBox(parent, options) : dialog.showMessageBox(options); try { const result = await promise; if (abortController.signal.aborted || this.isDestroyed()) return; if (result.checkboxChecked) originCounts.set(origin, -1); return callback(result.response === 0, ''); } finally { openDialogs.delete(abortController); } }); this.on('-cancel-dialogs' as any, () => { for (const controller of openDialogs) { controller.abort(); } openDialogs.clear(); }); app.emit('web-contents-created', { sender: this, preventDefault () {}, get defaultPrevented () { return false; } }, 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 fromFrame (frame: Electron.WebFrameMain) { return binding.fromFrame(frame); } 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
41,064
[Bug]: webContents.PrintToPdf() fails with "Invalid print parameter: Content area is empty."
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 28.1.2 ### What operating system are you using? Windows ### Operating System Version Windows 11 Pro, version 22H2, OS Build 22621.3007 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior 1. I pass the `PrintToPDFOptions` of `webContents.PrintToPdf()` from the UI to the IPC. 2. if I specify an excessive `margins` value (e.g. 10), I get an error with the message `Invalid print parameter: Content area is empty.` 3. again, if I set a minimum `margins` value (e.g. 0) in the UI, it should work fine ### Actual Behavior - After the error, the error still occurs even with a minimum `margins` value. (e.g. 0) - After the error, I have to re-run `Electron` to get it to work. - I haven't checked if recreating the `BrowserWindow` will make it okay. ### Testcase Gist URL _No response_ ### Additional Information @codebytere - The `print_to_pdf::GetPrintPagesParams()` in [electron_api_web_contents.cc](https://github.com/electron/electron/blob/1300e83884595a3c89c24bd4d42f3a1bbbb6fe7d/shell/browser/api/electron_api_web_contents.cc#L3179) is a static function, which is affected by the previous error. - It looks like `print_to_pdf` is a Chromium open source module, and I'd like to know what process manages it.
https://github.com/electron/electron/issues/41064
https://github.com/electron/electron/pull/41157
85bebfb18073d623f1963f8c5a6d9b24295d691d
6df34436171f5b0fad1fd343de08621ce3a8b669
2024-01-21T14:29:41Z
c++
2024-01-31T09:48:41Z
spec/api-web-contents-spec.ts
import { expect } from 'chai'; import { AddressInfo } from 'node:net'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as http from 'node:http'; import { BrowserWindow, ipcMain, webContents, session, app, BrowserView, WebContents } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import { ifdescribe, defer, waitUntil, listen, ifit } from './lib/spec-helpers'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; const pdfjs = require('pdfjs-dist'); const fixturesPath = path.resolve(__dirname, 'fixtures'); const mainFixturesPath = path.resolve(__dirname, 'fixtures'); const features = process._linkedBinding('electron_common_features'); describe('webContents module', () => { describe('getAllWebContents() API', () => { afterEach(closeAllWindows); it('returns an array of web contents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html')); await once(w.webContents, 'did-attach-webview') as [any, WebContents]; w.webContents.openDevTools(); await once(w.webContents, 'devtools-opened'); const all = webContents.getAllWebContents().sort((a, b) => { return a.id - b.id; }); expect(all).to.have.length(3); expect(all[0].getType()).to.equal('window'); expect(all[all.length - 2].getType()).to.equal('webview'); expect(all[all.length - 1].getType()).to.equal('remote'); }); }); describe('fromId()', () => { it('returns undefined for an unknown id', () => { expect(webContents.fromId(12345)).to.be.undefined(); }); }); describe('fromFrame()', () => { it('returns WebContents for mainFrame', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); expect(webContents.fromFrame(contents.mainFrame)).to.equal(contents); }); it('returns undefined for disposed frame', async () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); const { mainFrame } = contents; contents.destroy(); await waitUntil(() => typeof webContents.fromFrame(mainFrame) === 'undefined'); }); it('throws when passing invalid argument', async () => { let errored = false; try { webContents.fromFrame({} as any); } catch { errored = true; } expect(errored).to.be.true(); }); }); describe('fromDevToolsTargetId()', () => { it('returns WebContents for attached DevTools target', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); try { await w.webContents.debugger.attach('1.3'); const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo'); expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents); } finally { await w.webContents.debugger.detach(); } }); it('returns undefined for an unknown id', () => { expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined(); }); }); describe('will-prevent-unload event', function () { afterEach(closeAllWindows); it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('does not emit if beforeunload returns undefined in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); view.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits if beforeunload returns false in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, 'will-prevent-unload'); }); it('emits if beforeunload returns false in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(view.webContents, 'will-prevent-unload'); }); it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', event => event.preventDefault()); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); const wait = once(w, 'closed'); w.close(); await wait; }); }); describe('webContents.send(channel, args...)', () => { afterEach(closeAllWindows); it('throws an error when the channel is missing', () => { const w = new BrowserWindow({ show: false }); expect(() => { (w.webContents.send as any)(); }).to.throw('Missing required channel argument'); expect(() => { w.webContents.send(null as any); }).to.throw('Missing required channel argument'); }); it('does not block node async APIs when sent before document is ready', (done) => { // Please reference https://github.com/electron/electron/issues/19368 if // this test fails. ipcMain.once('async-node-api-done', () => { done(); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, sandbox: false, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html')); setTimeout(50).then(() => { w.webContents.send('test'); }); }); }); ifdescribe(features.isPrintingEnabled())('webContents.print()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('throws when invalid settings are passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print(true); }).to.throw('webContents.print(): Invalid print settings specified.'); }); it('throws when an invalid pageSize is passed', () => { const badSize = 5; expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({ pageSize: badSize }); }).to.throw(`Unsupported pageSize: ${badSize}`); }); it('throws when an invalid callback is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({}, true); }).to.throw('webContents.print(): Invalid optional callback provided.'); }); it('fails when an invalid deviceName is passed', (done) => { w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => { expect(success).to.equal(false); expect(reason).to.match(/Invalid deviceName provided/); done(); }); }); it('throws when an invalid pageSize is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {}); }).to.throw('Unsupported pageSize: i-am-a-bad-pagesize'); }); it('throws when an invalid custom pageSize is passed', () => { expect(() => { w.webContents.print({ pageSize: { width: 100, height: 200 } }); }).to.throw('height and width properties must be minimum 352 microns.'); }); it('does not crash with custom margins', () => { expect(() => { w.webContents.print({ silent: true, margins: { marginType: 'custom', top: 1, bottom: 1, left: 1, right: 1 } }); }).to.not.throw(); }); }); describe('webContents.executeJavaScript', () => { describe('in about:blank', () => { const expected = 'hello, world!'; const expectedErrorMsg = 'woops!'; const code = `(() => "${expected}")()`; const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`; const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`; const errorTypes = new Set([ Error, ReferenceError, EvalError, RangeError, SyntaxError, TypeError, URIError ]); let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } }); await w.loadURL('about:blank'); }); after(closeAllWindows); it('resolves the returned promise with the result', async () => { const result = await w.webContents.executeJavaScript(code); expect(result).to.equal(expected); }); it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => { const result = await w.webContents.executeJavaScript(asyncCode); expect(result).to.equal(expected); }); it('rejects the returned promise if an async error is thrown', async () => { await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg); }); it('rejects the returned promise with an error if an Error.prototype is thrown', async () => { for (const error of errorTypes) { await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`)) .to.eventually.be.rejectedWith(error); } }); }); describe('on a real page', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('works after page load and during subframe load', async () => { await w.loadURL(serverUrl); // initiate a sub-frame load, then try and execute script during it await w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/slow' document.body.appendChild(iframe) null // don't return the iframe `); await w.webContents.executeJavaScript('console.log(\'hello\')'); }); it('executes after page load', async () => { const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()'); w.loadURL(serverUrl); const result = await executeJavaScript; expect(result).to.equal('test'); }); }); }); describe('webContents.executeJavaScriptInIsolatedWorld', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadURL('about:blank'); }); it('resolves the returned promise with the result', async () => { await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]); const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]); const mainWorldResult = await w.webContents.executeJavaScript('window.X'); expect(isolatedResult).to.equal(123); expect(mainWorldResult).to.equal(undefined); }); }); describe('loadURL() promise API', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('resolves when done loading', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('resolves when done loading a file URL', async () => { await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled(); }); it('resolves when navigating within the page', async () => { await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await setTimeout(); await expect(w.loadURL(w.getURL() + '#foo')).to.eventually.be.fulfilled(); }); it('resolves after browser initiated navigation', async () => { let finishedLoading = false; w.webContents.on('did-finish-load', function () { finishedLoading = true; }); await w.loadFile(path.join(fixturesPath, 'pages', 'navigate_in_page_and_wait.html')); expect(finishedLoading).to.be.true(); }); it('rejects when failing to load a file URL', async () => { await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FILE_NOT_FOUND'); }); // FIXME: Temporarily disable on WOA until // https://github.com/electron/electron/issues/20008 is resolved ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('rejects when loading fails due to DNS not resolved', async () => { await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected() .and.have.property('code', 'ERR_NAME_NOT_RESOLVED'); }); it('rejects when navigation is cancelled due to a bad scheme', async () => { await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FAILED'); }); it('does not crash when loading a new URL with emulation settings set', async () => { const setEmulation = async () => { if (w.webContents) { w.webContents.debugger.attach('1.3'); const deviceMetrics = { width: 700, height: 600, deviceScaleFactor: 2, mobile: true, dontSetVisibleSize: true }; await w.webContents.debugger.sendCommand( 'Emulation.setDeviceMetricsOverride', deviceMetrics ); } }; try { await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await setEmulation(); await w.loadURL('data:text/html,<h1>HELLO</h1>'); await setEmulation(); } catch (e) { expect((e as Error).message).to.match(/Debugger is already attached to the target/); } }); it('fails if loadURL is called inside a non-reentrant critical section', (done) => { w.webContents.once('did-fail-load', (_event, _errorCode, _errorDescription, validatedURL) => { expect(validatedURL).to.contain('blank.html'); done(); }); w.webContents.once('did-start-loading', () => { w.loadURL(`file://${fixturesPath}/pages/blank.html`); }); w.loadURL('data:text/html,<h1>HELLO</h1>'); }); it('sets appropriate error information on rejection', async () => { let err: any; try { await w.loadURL('file:non-existent'); } catch (e) { err = e; } expect(err).not.to.be.null(); expect(err.code).to.eql('ERR_FILE_NOT_FOUND'); expect(err.errno).to.eql(-6); expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent'); }); it('rejects if the load is aborted', async () => { const s = http.createServer(() => { /* never complete the request */ }); const { port } = await listen(s); const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/); // load a different file before the first load completes, causing the // first load to be aborted. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await p; s.close(); }); it("doesn't reject when a subframe fails to load", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="http://err.name.not.resolved"></iframe>'); resp = res; // don't end the response yet }); const { port } = await listen(s); const p = new Promise<void>(resolve => { w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.end(); await main; s.close(); }); it("doesn't resolve when a subframe loads", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="about:blank"></iframe>'); resp = res; // don't end the response yet }); const { port } = await listen(s); const p = new Promise<void>(resolve => { w.webContents.on('did-frame-finish-load', (event, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.destroy(); // cause the main request to fail await expect(main).to.eventually.be.rejected() .and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING s.close(); }); it('subsequent load failures reject each time', async () => { await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected(); await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected(); }); }); describe('getFocusedWebContents() API', () => { afterEach(closeAllWindows); // FIXME ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('returns the focused web contents', async () => { const w = new BrowserWindow({ show: true }); await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id); const devToolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools(); await devToolsOpened; expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.devToolsWebContents!.id); const devToolsClosed = once(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id); }); it('does not crash when called on a detached dev tools window', async () => { const w = new BrowserWindow({ show: true }); w.webContents.openDevTools({ mode: 'detach' }); w.webContents.inspectElement(100, 100); // For some reason we have to wait for two focused events...? await once(w.webContents, 'devtools-focused'); expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); // Work around https://github.com/electron/electron/issues/19985 await setTimeout(); const devToolsClosed = once(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); }); }); describe('setDevToolsWebContents() API', () => { afterEach(closeAllWindows); it('sets arbitrary webContents as devtools', async () => { const w = new BrowserWindow({ show: false }); const devtools = new BrowserWindow({ show: false }); const promise = once(devtools.webContents, 'dom-ready'); w.webContents.setDevToolsWebContents(devtools.webContents); w.webContents.openDevTools(); await promise; expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true(); const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name'); expect(result).to.equal('InspectorFrontendHostImpl'); devtools.destroy(); }); }); describe('isFocused() API', () => { it('returns false when the window is hidden', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(w.isVisible()).to.be.false(); expect(w.webContents.isFocused()).to.be.false(); }); }); describe('isCurrentlyAudible() API', () => { afterEach(closeAllWindows); it('returns whether audio is playing', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript(` window.context = new AudioContext // Start in suspended state, because of the // new web audio api policy. context.suspend() window.oscillator = context.createOscillator() oscillator.connect(context.destination) oscillator.start() `); let p = once(w.webContents, 'audio-state-changed'); w.webContents.executeJavaScript('context.resume()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.true(); p = once(w.webContents, 'audio-state-changed'); w.webContents.executeJavaScript('oscillator.stop()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.false(); }); }); describe('openDevTools() API', () => { afterEach(closeAllWindows); it('can show window with activation', async () => { const w = new BrowserWindow({ show: false }); const focused = once(w, 'focus'); w.show(); await focused; expect(w.isFocused()).to.be.true(); const blurred = once(w, 'blur'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await Promise.all([ once(w.webContents, 'devtools-opened'), once(w.webContents, 'devtools-focused') ]); await blurred; expect(w.isFocused()).to.be.false(); }); it('can show window without activation', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); }); it('can show a DevTools window with custom title', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false, title: 'myTitle' }); await devtoolsOpened; expect(w.webContents.getDevToolsTitle()).to.equal('myTitle'); }); it('can re-open devtools', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); const devtoolsClosed = once(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devtoolsClosed; expect(w.webContents.isDevToolsOpened()).to.be.false(); const devtoolsOpened2 = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await devtoolsOpened2; expect(w.webContents.isDevToolsOpened()).to.be.true(); }); }); describe('setDevToolsTitle() API', () => { afterEach(closeAllWindows); it('can set devtools title with function', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); w.webContents.setDevToolsTitle('newTitle'); expect(w.webContents.getDevToolsTitle()).to.equal('newTitle'); }); }); describe('before-input-event event', () => { afterEach(closeAllWindows); it('can prevent document keyboard events', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); const keyDown = new Promise(resolve => { ipcMain.once('keydown', (event, key) => resolve(key)); }); w.webContents.once('before-input-event', (event, input) => { if (input.key === 'a') event.preventDefault(); }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' }); expect(await keyDown).to.equal('b'); }); it('has the correct properties', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testBeforeInput = async (opts: any) => { const modifiers = []; if (opts.shift) modifiers.push('shift'); if (opts.control) modifiers.push('control'); if (opts.alt) modifiers.push('alt'); if (opts.meta) modifiers.push('meta'); if (opts.isAutoRepeat) modifiers.push('isAutoRepeat'); const p = once(w.webContents, 'before-input-event') as Promise<[any, Electron.Input]>; w.webContents.sendInputEvent({ type: opts.type, keyCode: opts.keyCode, modifiers: modifiers as any }); const [, input] = await p; expect(input.type).to.equal(opts.type); expect(input.key).to.equal(opts.key); expect(input.code).to.equal(opts.code); expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat); expect(input.shift).to.equal(opts.shift); expect(input.control).to.equal(opts.control); expect(input.alt).to.equal(opts.alt); expect(input.meta).to.equal(opts.meta); }; await testBeforeInput({ type: 'keyDown', key: 'A', code: 'KeyA', keyCode: 'a', shift: true, control: true, alt: true, meta: true, isAutoRepeat: true }); await testBeforeInput({ type: 'keyUp', key: '.', code: 'Period', keyCode: '.', shift: false, control: true, alt: true, meta: false, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: '!', code: 'Digit1', keyCode: '1', shift: true, control: false, alt: false, meta: true, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: 'Tab', code: 'Tab', keyCode: 'Tab', shift: false, control: true, alt: false, meta: false, isAutoRepeat: true }); }); }); // On Mac, zooming isn't done with the mouse wheel. ifdescribe(process.platform !== 'darwin')('zoom-changed', () => { afterEach(closeAllWindows); it('is emitted with the correct zoom-in info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: 1, wheelTicksX: 0, wheelTicksY: 1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string]; expect(zoomDirection).to.equal('in'); }; await testZoomChanged(); }); it('is emitted with the correct zoom-out info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: -1, wheelTicksX: 0, wheelTicksY: -1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string]; expect(zoomDirection).to.equal('out'); }; await testZoomChanged(); }); }); describe('sendInputEvent(event)', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); }); afterEach(closeAllWindows); it('can send keydown events', async () => { const keydown = once(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send keydown events with modifiers', async () => { const keydown = once(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); it('can send keydown events with special keys', async () => { const keydown = once(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Tab'); expect(code).to.equal('Tab'); expect(keyCode).to.equal(9); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.true(); }); it('can send char events', async () => { const keypress = once(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can correctly convert accelerators to key codes', async () => { const keyup = once(ipcMain, 'keyup'); w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'keyUp' }); await keyup; const inputText = await w.webContents.executeJavaScript('document.getElementById("input").value'); expect(inputText).to.equal('+ + +'); }); it('can send char events with modifiers', async () => { const keypress = once(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); }); describe('insertCSS', () => { afterEach(closeAllWindows); it('supports inserting CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.webContents.insertCSS('body { background-repeat: round; }'); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('round'); }); it('supports removing inserted CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const key = await w.webContents.insertCSS('body { background-repeat: round; }'); await w.webContents.removeInsertedCSS(key); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('repeat'); }); }); describe('inspectElement()', () => { afterEach(closeAllWindows); it('supports inspecting an element in the devtools', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const event = once(w.webContents, 'devtools-opened'); w.webContents.inspectElement(10, 10); await event; }); }); describe('startDrag({file, icon})', () => { it('throws errors for a missing file or a missing/empty icon', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any); }).to.throw('Must specify either \'file\' or \'files\' option'); expect(() => { w.webContents.startDrag({ file: __filename } as any); }).to.throw('\'icon\' parameter is required'); expect(() => { w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') }); }).to.throw(/Failed to load image from path (.+)/); }); }); describe('focus APIs', () => { describe('focus()', () => { afterEach(closeAllWindows); it('does not blur the focused window when the web contents is hidden', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.show(); await w.loadURL('about:blank'); w.focus(); const child = new BrowserWindow({ show: false }); child.loadURL('about:blank'); child.webContents.focus(); const currentFocused = w.isFocused(); const childFocused = child.isFocused(); child.close(); expect(currentFocused).to.be.true(); expect(childFocused).to.be.false(); }); }); const moveFocusToDevTools = async (win: BrowserWindow) => { const devToolsOpened = once(win.webContents, 'devtools-opened'); win.webContents.openDevTools({ mode: 'right' }); await devToolsOpened; win.webContents.devToolsWebContents!.focus(); }; describe('focus event', () => { afterEach(closeAllWindows); it('is triggered when web contents is focused', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await moveFocusToDevTools(w); const focusPromise = once(w.webContents, 'focus'); w.webContents.focus(); await expect(focusPromise).to.eventually.be.fulfilled(); }); }); describe('blur event', () => { afterEach(closeAllWindows); it('is triggered when web contents is blurred', async () => { const w = new BrowserWindow({ show: true }); await w.loadURL('about:blank'); w.webContents.focus(); const blurPromise = once(w.webContents, 'blur'); await moveFocusToDevTools(w); await expect(blurPromise).to.eventually.be.fulfilled(); }); }); }); describe('getOSProcessId()', () => { afterEach(closeAllWindows); it('returns a valid process id', async () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getOSProcessId()).to.equal(0); await w.loadURL('about:blank'); expect(w.webContents.getOSProcessId()).to.be.above(0); }); }); describe('getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns a valid stream id', () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty(); }); }); describe('userAgent APIs', () => { it('is not empty by default', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); expect(userAgent).to.be.a('string').that.is.not.empty(); }); it('can set the user agent (functions)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); w.webContents.setUserAgent('my-user-agent'); expect(w.webContents.getUserAgent()).to.equal('my-user-agent'); w.webContents.setUserAgent(userAgent); expect(w.webContents.getUserAgent()).to.equal(userAgent); }); it('can set the user agent (properties)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.userAgent; w.webContents.userAgent = 'my-user-agent'; expect(w.webContents.userAgent).to.equal('my-user-agent'); w.webContents.userAgent = userAgent; expect(w.webContents.userAgent).to.equal(userAgent); }); }); describe('audioMuted APIs', () => { it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.setAudioMuted(true); expect(w.webContents.isAudioMuted()).to.be.true(); w.webContents.setAudioMuted(false); expect(w.webContents.isAudioMuted()).to.be.false(); }); it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.audioMuted = true; expect(w.webContents.audioMuted).to.be.true(); w.webContents.audioMuted = false; expect(w.webContents.audioMuted).to.be.false(); }); }); describe('zoom api', () => { const hostZoomMap: Record<string, number> = { host1: 0.3, host2: 0.7, host3: 0.2 }; before(() => { const protocol = session.defaultSession.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { const response = `<script> const {ipcRenderer} = require('electron') ipcRenderer.send('set-zoom', window.location.hostname) ipcRenderer.on(window.location.hostname + '-zoom-set', () => { ipcRenderer.send(window.location.hostname + '-zoom-level') }) </script>`; callback({ data: response, mimeType: 'text/html' }); }); }); after(() => { const protocol = session.defaultSession.protocol; protocol.unregisterProtocol(standardScheme); }); afterEach(closeAllWindows); it('throws on an invalid zoomFactor', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { w.webContents.setZoomFactor(0.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); expect(() => { w.webContents.setZoomFactor(-2.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); }); it('can set the correct zoom level (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.getZoomLevel(); expect(zoomLevel).to.eql(0.0); w.webContents.setZoomLevel(0.5); const newZoomLevel = w.webContents.getZoomLevel(); expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.setZoomLevel(0); } }); it('can set the correct zoom level (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.eql(0.0); w.webContents.zoomLevel = 0.5; const newZoomLevel = w.webContents.zoomLevel; expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.zoomLevel = 0; } }); it('can set the correct zoom factor (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.getZoomFactor(); expect(zoomFactor).to.eql(1.0); w.webContents.setZoomFactor(0.5); const newZoomFactor = w.webContents.getZoomFactor(); expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.setZoomFactor(1.0); } }); it('can set the correct zoom factor (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.zoomFactor; expect(zoomFactor).to.eql(1.0); w.webContents.zoomFactor = 0.5; const newZoomFactor = w.webContents.zoomFactor; expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.zoomFactor = 1.0; } }); it('can persist zoom level across navigation', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let finalNavigation = false; ipcMain.on('set-zoom', (e, host) => { const zoomLevel = hostZoomMap[host]; if (!finalNavigation) w.webContents.zoomLevel = zoomLevel; e.sender.send(`${host}-zoom-set`); }); ipcMain.on('host1-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host1; expect(zoomLevel).to.equal(expectedZoomLevel); if (finalNavigation) { done(); } else { w.loadURL(`${standardScheme}://host2`); } } catch (e) { done(e); } }); ipcMain.once('host2-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host2; expect(zoomLevel).to.equal(expectedZoomLevel); finalNavigation = true; w.webContents.goBack(); } catch (e) { done(e); } }); w.loadURL(`${standardScheme}://host1`); }); it('can propagate zoom level across same session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false }); defer(() => { w2.setClosable(true); w2.close(); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel1).to.equal(zoomLevel2); }); it('cannot propagate zoom level across different session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false, webPreferences: { partition: 'temp' } }); const protocol = w2.webContents.session.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { callback('hello'); }); defer(() => { w2.setClosable(true); w2.close(); protocol.unregisterProtocol(standardScheme); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); it('can persist when it contains iframe', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { setTimeout(200).then(() => { res.end(); }); }); listen(server).then(({ url }) => { const content = `<iframe src=${url}></iframe>`; w.webContents.on('did-frame-finish-load', (e, isMainFrame) => { if (!isMainFrame) { try { const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(2.0); w.webContents.zoomLevel = 0; done(); } catch (e) { done(e); } finally { server.close(); } } }); w.webContents.on('dom-ready', () => { w.webContents.zoomLevel = 2.0; }); w.loadURL(`data:text/html,${content}`); }); }); it('cannot propagate when used with webframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const w2 = new BrowserWindow({ show: false }); const temporaryZoomSet = once(ipcMain, 'temporary-zoom-set'); w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html')); await temporaryZoomSet; const finalZoomLevel = w.webContents.getZoomLevel(); await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html')); const zoomLevel1 = w.webContents.zoomLevel; const zoomLevel2 = w2.webContents.zoomLevel; w2.setClosable(true); w2.close(); expect(zoomLevel1).to.equal(finalZoomLevel); expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); describe('with unique domains', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before(async () => { server = http.createServer((req, res) => { setTimeout().then(() => res.end('hey')); }); serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); after(() => { server.close(); }); it('cannot persist zoom level after navigation with webFrame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const source = ` const {ipcRenderer, webFrame} = require('electron') webFrame.setZoomLevel(0.6) ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel()) `; const zoomLevelPromise = once(ipcMain, 'zoom-level-set'); await w.loadURL(serverUrl); await w.webContents.executeJavaScript(source); let [, zoomLevel] = await zoomLevelPromise; expect(zoomLevel).to.equal(0.6); const loadPromise = once(w.webContents, 'did-finish-load'); await w.loadURL(crossSiteUrl); await loadPromise; zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(0); }); }); }); describe('webrtc ip policy api', () => { afterEach(closeAllWindows); it('can set and get webrtc ip policies', () => { const w = new BrowserWindow({ show: false }); const policies = [ 'default', 'default_public_interface_only', 'default_public_and_private_interfaces', 'disable_non_proxied_udp' ] as const; for (const policy of policies) { w.webContents.setWebRTCIPHandlingPolicy(policy); expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy); } }); }); describe('webrtc udp port range policy api', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('check default webrtc udp port range is { min: 0, max: 0 }', () => { const settings = w.webContents.getWebRTCUDPPortRange(); expect(settings).to.deep.equal({ min: 0, max: 0 }); }); it('can set and get webrtc udp port range policy with correct arguments', () => { w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 }); const settings = w.webContents.getWebRTCUDPPortRange(); expect(settings).to.deep.equal({ min: 1, max: 65535 }); }); it('can not set webrtc udp port range policy with invalid arguments', () => { expect(() => { w.webContents.setWebRTCUDPPortRange({ min: 0, max: 65535 }); }).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]"); expect(() => { w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65536 }); }).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]"); expect(() => { w.webContents.setWebRTCUDPPortRange({ min: 60000, max: 56789 }); }).to.throw("'max' must be greater than or equal to 'min'"); }); it('can reset webrtc udp port range policy to default with { min: 0, max: 0 }', () => { w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 }); const settings = w.webContents.getWebRTCUDPPortRange(); expect(settings).to.deep.equal({ min: 1, max: 65535 }); w.webContents.setWebRTCUDPPortRange({ min: 0, max: 0 }); const defaultSetting = w.webContents.getWebRTCUDPPortRange(); expect(defaultSetting).to.deep.equal({ min: 0, max: 0 }); }); }); describe('opener api', () => { afterEach(closeAllWindows); it('can get opener with window.open()', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>; w.webContents.executeJavaScript('window.open("about:blank")', true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame); }); it('has no opener when using "noopener"', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>; w.webContents.executeJavaScript('window.open("about:blank", undefined, "noopener")', true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.be.null(); }); it('can get opener with a[target=_blank][rel=opener]', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>; w.webContents.executeJavaScript(`(function() { const a = document.createElement('a'); a.target = '_blank'; a.rel = 'opener'; a.href = 'about:blank'; a.click(); }())`, true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame); }); it('has no opener with a[target=_blank][rel=noopener]', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>; w.webContents.executeJavaScript(`(function() { const a = document.createElement('a'); a.target = '_blank'; a.rel = 'noopener'; a.href = 'about:blank'; a.click(); }())`, true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.be.null(); }); }); describe('render view deleted events', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before(async () => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${crossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else if (req.url === '/first-window-open') { res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`); } else if (req.url === '/second-window-open') { res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>'); } else { res.end(); } }; setTimeout().then(respond); }); serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); after(() => { server.close(); }); afterEach(closeAllWindows); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); w.webContents.on('did-finish-load', () => { w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted'); }); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const parentWindow = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; let childWindow: BrowserWindow | null = null; const destroyed = once(parentWindow.webContents, 'destroyed'); const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; const childWindowCreated = new Promise<void>((resolve) => { app.once('browser-window-created', (event, window) => { childWindow = window; window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); resolve(); }); }); parentWindow.loadURL(`${serverUrl}/first-window-open`); await childWindowCreated; childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); parentWindow.close(); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed'); }); it('emits current-render-view-deleted if the current RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; w.webContents.on('current-render-view-deleted' as any, () => { currentRenderViewDeletedEmitted = true; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted'); }); it('emits render-view-deleted if any RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let rvhDeletedCount = 0; w.webContents.on('render-view-deleted' as any, () => { rvhDeletedCount++; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; const expectedRenderViewDeletedEventCount = 1; expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times'); }); }); describe('setIgnoreMenuShortcuts(ignore)', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.setIgnoreMenuShortcuts(true); w.webContents.setIgnoreMenuShortcuts(false); }).to.not.throw(); }); }); const crashPrefs = [ { nodeIntegration: true }, { sandbox: true } ]; const nicePrefs = (o: any) => { let s = ''; for (const key of Object.keys(o)) { s += `${key}=${o[key]}, `; } return `(${s.slice(0, s.length - 2)})`; }; for (const prefs of crashPrefs) { describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('isCrashed() is false by default', () => { expect(w.webContents.isCrashed()).to.equal(false); }); it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => { expect(w.webContents.isCrashed()).to.equal(false); const crashEvent = once(w.webContents, 'render-process-gone') as Promise<[any, Electron.RenderProcessGoneDetails]>; w.webContents.forcefullyCrashRenderer(); const [, details] = await crashEvent; expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed'); expect(w.webContents.isCrashed()).to.equal(true); }); it('a crashed process is recoverable with reload()', async () => { expect(w.webContents.isCrashed()).to.equal(false); w.webContents.forcefullyCrashRenderer(); w.webContents.reload(); expect(w.webContents.isCrashed()).to.equal(false); }); }); } // Destroying webContents in its event listener is going to crash when // Electron is built in Debug mode. describe('destroy()', () => { let server: http.Server; let serverUrl: string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/200': response.end(); break; default: done(new Error('unsupported endpoint')); } }); listen(server).then(({ url }) => { serverUrl = url; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', url: '/200' }, { name: 'dom-ready', url: '/200' }, { name: 'did-stop-loading', url: '/200' }, { name: 'did-finish-load', url: '/200' }, // FIXME: Multiple Emit calls inside an observer assume that object // will be alive till end of the observer. Synchronous `destroy` api // violates this contract and crashes. { name: 'did-frame-finish-load', url: '/200' }, { name: 'did-fail-load', url: '/net-error' } ]; for (const e of events) { it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () { // This test is flaky on Windows CI and we don't know why, but the // purpose of this test is to make sure Electron does not crash so it // is fine to retry this test for a few times. this.retries(3); const contents = (webContents as typeof ElectronInternal.WebContents).create(); const originalEmit = contents.emit.bind(contents); contents.emit = (...args) => { return originalEmit(...args); }; contents.once(e.name as any, () => contents.destroy()); const destroyed = once(contents, 'destroyed'); contents.loadURL(serverUrl + e.url); await destroyed; }); } }); describe('did-change-theme-color event', () => { afterEach(closeAllWindows); it('is triggered with correct theme color', (done) => { const w = new BrowserWindow({ show: true }); let count = 0; w.webContents.on('did-change-theme-color', (e, color) => { try { if (count === 0) { count += 1; expect(color).to.equal('#FFEEDD'); w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); } else if (count === 1) { expect(color).to.be.null(); done(); } } catch (e) { done(e); } }); w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html')); }); }); describe('console-message event', () => { afterEach(closeAllWindows); it('is triggered with correct log message', (done) => { const w = new BrowserWindow({ show: true }); w.webContents.on('console-message', (e, level, message) => { // Don't just assert as Chromium might emit other logs that we should ignore. if (message === 'a') { done(); } }); w.loadFile(path.join(fixturesPath, 'pages', 'a.html')); }); }); describe('ipc-message event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends an asynchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); w.webContents.executeJavaScript(` require('electron').ipcRenderer.send('message', 'Hello World!') `); const [, channel, message] = await once(w.webContents, 'ipc-message'); expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); }); }); describe('ipc-message-sync event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends a synchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); const promise: Promise<[string, string]> = new Promise(resolve => { w.webContents.once('ipc-message-sync', (event, channel, arg) => { event.returnValue = 'foobar'; resolve([channel, arg]); }); }); const result = await w.webContents.executeJavaScript(` require('electron').ipcRenderer.sendSync('message', 'Hello World!') `); const [channel, message] = await promise; expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); expect(result).to.equal('foobar'); }); }); describe('referrer', () => { afterEach(closeAllWindows); it('propagates referrer information to new target=_blank windows', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } finally { server.close(); } } res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>'); }); listen(server).then(({ url }) => { w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url + '/'); expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin'); return { action: 'allow' }; }); w.webContents.executeJavaScript('a.click()'); }); w.loadURL(url); }); }); it('propagates referrer information to windows opened with window.open', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } } res.end(''); }); listen(server).then(({ url }) => { w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url + '/'); expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin'); return { action: 'allow' }; }); w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")'); }); w.loadURL(url); }); }); }); describe('webframe messages in sandboxed contents', () => { afterEach(closeAllWindows); it('responds to executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const result = await w.webContents.executeJavaScript('37 + 5'); expect(result).to.equal(42); }); }); describe('preload-error event', () => { afterEach(closeAllWindows); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('is triggered when unhandled exception is thrown', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>; w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('Hello World!'); }); it('is triggered on syntax errors', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>; w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('foobar is not defined'); }); it('is triggered when preload script loading fails', async () => { const preload = path.join(fixturesPath, 'module', 'preload-invalid.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>; w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.contain('preload-invalid.js'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('takeHeapSnapshot()', () => { afterEach(closeAllWindows); it('works with sandboxed renderers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); const cleanup = () => { try { fs.unlinkSync(filePath); } catch { // ignore error } }; try { await w.webContents.takeHeapSnapshot(filePath); const stats = fs.statSync(filePath); expect(stats.size).not.to.be.equal(0); } finally { cleanup(); } }); it('fails with invalid file path', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const badPath = path.join('i', 'am', 'a', 'super', 'bad', 'path'); const promise = w.webContents.takeHeapSnapshot(badPath); return expect(promise).to.be.eventually.rejectedWith(Error, `Failed to take heap snapshot with invalid file path ${badPath}`); }); it('fails with invalid render process', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); w.webContents.destroy(); const promise = w.webContents.takeHeapSnapshot(filePath); return expect(promise).to.be.eventually.rejectedWith(Error, 'Failed to take heap snapshot with nonexistent render frame'); }); }); describe('setBackgroundThrottling()', () => { afterEach(closeAllWindows); it('does not crash when allowing', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(true); }); it('does not crash when called via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); w.setBackgroundThrottling(true); }); it('does not crash when disallowing', () => { const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } }); w.webContents.setBackgroundThrottling(false); }); }); describe('getBackgroundThrottling()', () => { afterEach(closeAllWindows); it('works via getter', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); expect(w.webContents.getBackgroundThrottling()).to.equal(false); w.webContents.setBackgroundThrottling(true); expect(w.webContents.getBackgroundThrottling()).to.equal(true); }); it('works via property', () => { const w = new BrowserWindow({ show: false }); w.webContents.backgroundThrottling = false; expect(w.webContents.backgroundThrottling).to.equal(false); w.webContents.backgroundThrottling = true; expect(w.webContents.backgroundThrottling).to.equal(true); }); it('works via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); w.setBackgroundThrottling(false); expect(w.getBackgroundThrottling()).to.equal(false); w.setBackgroundThrottling(true); expect(w.getBackgroundThrottling()).to.equal(true); }); }); ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = await w.webContents.getPrintersAsync(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('printToPDF()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); afterEach(closeAllWindows); it('rejects on incorrectly typed parameters', async () => { const badTypes = { landscape: [], displayHeaderFooter: '123', printBackground: 2, scale: 'not-a-number', pageSize: 'IAmAPageSize', margins: 'terrible', pageRanges: { oops: 'im-not-the-right-key' }, headerTemplate: [1, 2, 3], footerTemplate: [4, 5, 6], preferCSSPageSize: 'no', generateTaggedPDF: 'wtf', generateDocumentOutline: [7, 8, 9] }; await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); // These will hard crash in Chromium unless we type-check for (const [key, value] of Object.entries(badTypes)) { const param = { [key]: value }; await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected(); } }); it('does not crash when called multiple times in parallel', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); const promises = []; for (let i = 0; i < 3; i++) { promises.push(w.webContents.printToPDF({})); } const results = await Promise.all(promises); for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); it('does not crash when called multiple times in sequence', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); const results = []; for (let i = 0; i < 3; i++) { const result = await w.webContents.printToPDF({}); results.push(result); } for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); it('can print a PDF with default settings', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); const data = await w.webContents.printToPDF({}); expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); }); type PageSizeString = Exclude<Required<Electron.PrintToPDFOptions>['pageSize'], Electron.Size>; it('with custom page sizes', async () => { const paperFormats: Record<PageSizeString, ElectronInternal.PageSize> = { Letter: { width: 8.5, height: 11 }, Legal: { width: 8.5, height: 14 }, Tabloid: { width: 11, height: 17 }, Ledger: { width: 17, height: 11 }, A0: { width: 33.1, height: 46.8 }, A1: { width: 23.4, height: 33.1 }, A2: { width: 16.54, height: 23.4 }, A3: { width: 11.7, height: 16.54 }, A4: { width: 8.27, height: 11.7 }, A5: { width: 5.83, height: 8.27 }, A6: { width: 4.13, height: 5.83 } }; await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); for (const format of Object.keys(paperFormats) as PageSizeString[]) { const data = await w.webContents.printToPDF({ pageSize: format }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); // page.view is [top, left, width, height]. const width = page.view[2] / 72; const height = page.view[3] / 72; const approxEq = (a: number, b: number, epsilon = 0.01) => Math.abs(a - b) <= epsilon; expect(approxEq(width, paperFormats[format].width)).to.be.true(); expect(approxEq(height, paperFormats[format].height)).to.be.true(); } }); it('with custom header and footer', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ displayHeaderFooter: true, headerTemplate: '<div>I\'m a PDF header</div>', footerTemplate: '<div>I\'m a PDF footer</div>' }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); const { items } = await page.getTextContent(); // Check that generated PDF contains a header. const containsText = (text: RegExp) => items.some(({ str }: { str: string }) => str.match(text)); expect(containsText(/I'm a PDF header/)).to.be.true(); expect(containsText(/I'm a PDF footer/)).to.be.true(); }); it('in landscape mode', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ landscape: true }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); // page.view is [top, left, width, height]. const width = page.view[2]; const height = page.view[3]; expect(width).to.be.greaterThan(height); }); it('with custom page ranges', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-large.html')); const data = await w.webContents.printToPDF({ pageRanges: '1-3', landscape: true }); const doc = await pdfjs.getDocument(data).promise; // Check that correct # of pages are rendered. expect(doc.numPages).to.equal(3); }); it('does not tag PDFs by default', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({}); const doc = await pdfjs.getDocument(data).promise; const markInfo = await doc.getMarkInfo(); expect(markInfo).to.be.null(); }); it('can generate tag data for PDFs', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ generateTaggedPDF: true }); const doc = await pdfjs.getDocument(data).promise; const markInfo = await doc.getMarkInfo(); expect(markInfo).to.deep.equal({ Marked: true, UserProperties: false, Suspects: false }); }); }); describe('PictureInPicture video', () => { afterEach(closeAllWindows); it('works as expected', async function () { const w = new BrowserWindow({ webPreferences: { sandbox: true } }); // TODO(codebytere): figure out why this workaround is needed and remove. // It is not germane to the actual test. await w.loadFile(path.join(fixturesPath, 'blank.html')); await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html')); await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')', true); const result = await w.webContents.executeJavaScript('runTest(true)', true); expect(result).to.be.true(); }); }); describe('Shared Workers', () => { afterEach(closeAllWindows); it('can get multiple shared workers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = once(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); expect(sharedWorkers).to.have.lengthOf(2); expect(sharedWorkers[0].url).to.contain('shared-worker'); expect(sharedWorkers[1].url).to.contain('shared-worker'); }); it('can inspect a specific shared worker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = once(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.inspectSharedWorkerById(sharedWorkers[0].id); await devtoolsOpened; const devtoolsClosed = once(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devtoolsClosed; }); }); describe('login event', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; let serverPort: number; let proxyServer: http.Server; let proxyServerPort: number; before(async () => { server = http.createServer((request, response) => { if (request.url === '/no-auth') { return response.end('ok'); } if (request.headers.authorization) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers.authorization); } response .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }) .end('401'); }); ({ port: serverPort, url: serverUrl } = await listen(server)); }); before(async () => { proxyServer = http.createServer((request, response) => { if (request.headers['proxy-authorization']) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers['proxy-authorization']); } response .writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }) .end(); }); proxyServerPort = (await listen(proxyServer)).port; }); afterEach(async () => { await session.defaultSession.clearAuthCache(); }); after(() => { server.close(); proxyServer.close(); }); it('is emitted when navigating', async () => { const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(serverUrl + '/'); expect(eventAuthInfo.isProxy).to.be.false(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(serverPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('is emitted when a proxy requests authorization', async () => { const customSession = session.fromPartition(`${Math.random()}`); await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' }); const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(`${serverUrl}/no-auth`); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`); expect(eventAuthInfo.isProxy).to.be.true(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(proxyServerPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('cancels authentication when callback is called with no arguments', async () => { const w = new BrowserWindow({ show: false }); w.webContents.on('login', (event, request, authInfo, cb) => { event.preventDefault(); cb(); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal('401'); }); }); describe('page-title-updated event', () => { afterEach(closeAllWindows); it('is emitted with a full title for pages with no navigation', async () => { const bw = new BrowserWindow({ show: false }); await bw.loadURL('about:blank'); bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null'); const [, child] = await once(app, 'web-contents-created') as [any, WebContents]; bw.webContents.executeJavaScript('child.document.title = "new title"'); const [, title] = await once(child, 'page-title-updated') as [any, string]; expect(title).to.equal('new title'); }); }); describe('context-menu event', () => { afterEach(closeAllWindows); it('emits when right-clicked in page', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const promise = once(w.webContents, 'context-menu') as Promise<[any, Electron.ContextMenuParams]>; // Simulate right-click to create context-menu event. const opts = { x: 0, y: 0, button: 'right' as const }; w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' }); w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' }); const [, params] = await promise; expect(params.pageURL).to.equal(w.webContents.getURL()); expect(params.frame).to.be.an('object'); expect(params.x).to.be.a('number'); expect(params.y).to.be.a('number'); }); }); describe('close() method', () => { afterEach(closeAllWindows); it('closes when close() is called', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('closes when close() is called after loading a page', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('can be GCed before loading a page', async () => { const v8Util = process._linkedBinding('electron_common_v8_util'); let registry: FinalizationRegistry<unknown> | null = null; const cleanedUp = new Promise<number>(resolve => { registry = new FinalizationRegistry(resolve as any); }); (() => { const w = (webContents as typeof ElectronInternal.WebContents).create(); registry!.register(w, 42); })(); const i = setInterval(() => v8Util.requestGarbageCollectionForTesting(), 100); defer(() => clearInterval(i)); expect(await cleanedUp).to.equal(42); }); it('causes its parent browserwindow to be closed', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const closed = once(w, 'closed'); w.webContents.close(); await closed; expect(w.isDestroyed()).to.be.true(); }); it('ignores beforeunload if waitForBeforeUnload not specified', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.on('will-prevent-unload', () => { throw new Error('unexpected will-prevent-unload'); }); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('runs beforeunload if waitForBeforeUnload is specified', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); const willPreventUnload = once(w, 'will-prevent-unload'); w.close({ waitForBeforeUnload: true }); await willPreventUnload; expect(w.isDestroyed()).to.be.false(); }); it('overriding beforeunload prevention results in webcontents close', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.once('will-prevent-unload', e => e.preventDefault()); const destroyed = once(w, 'destroyed'); w.close({ waitForBeforeUnload: true }); await destroyed; expect(w.isDestroyed()).to.be.true(); }); }); describe('content-bounds-updated event', () => { afterEach(closeAllWindows); it('emits when moveTo is called', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.moveTo(100, 100)', true); const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle]; const { width, height } = w.getBounds(); expect(rect).to.deep.equal({ x: 100, y: 100, width, height }); await new Promise(setImmediate); expect(w.getBounds().x).to.equal(100); expect(w.getBounds().y).to.equal(100); }); it('emits when resizeTo is called', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.resizeTo(100, 100)', true); const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle]; const { x, y } = w.getBounds(); expect(rect).to.deep.equal({ x, y, width: 100, height: 100 }); await new Promise(setImmediate); expect({ width: w.getBounds().width, height: w.getBounds().height }).to.deep.equal(process.platform === 'win32' ? { // The width is reported as being larger on Windows? I'm not sure why // this is. width: 136, height: 100 } : { width: 100, height: 100 }); }); it('does not change window bounds if cancelled', async () => { const w = new BrowserWindow({ show: false }); const { width, height } = w.getBounds(); w.loadURL('about:blank'); w.webContents.once('content-bounds-updated', e => e.preventDefault()); await w.webContents.executeJavaScript('window.resizeTo(100, 100)', true); await new Promise(setImmediate); expect(w.getBounds().width).to.equal(width); expect(w.getBounds().height).to.equal(height); }); }); });
closed
electron/electron
https://github.com/electron/electron
39,279
[Bug]: Filters for USB requestDevice
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The `navigator.usb.requestDevice` [API](https://developer.mozilla.org/en-US/docs/Web/API/USB/requestDevice) allows for a `filters` parameter. When used in a web browser, the provided list of devices will be filtered based on this value. In Electron, the developer needs to handle device selection with https://www.electronjs.org/docs/latest/tutorial/devices#webusb-api. I would expect the `details.deviceList` provided to the `select-usb-device` event to filter the devices. Similarly I would expect the `usb-device-added` and `usb-device-removed` events to respect the filter. ### Actual Behavior I am seeing all attached USB devices in `details.deviceList`. I do not see a way to access the filter in the `select-usb-device` event, but I may be missing it. Tested on Mac and Windows. ### Testcase Gist URL https://gist.github.com/aoneill01/07eeb6733fd75e24064e174c7c0c17de ### Additional Information _No response_
https://github.com/electron/electron/issues/39279
https://github.com/electron/electron/pull/41166
6df34436171f5b0fad1fd343de08621ce3a8b669
e4d5dc138fd909de288fde82ee5d03106fe092f2
2023-07-28T14:54:52Z
c++
2024-01-31T14:53:30Z
shell/browser/usb/usb_chooser_controller.cc
// Copyright (c) 2022 Microsoft, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/usb/usb_chooser_controller.h" #include <stddef.h> #include <utility> #include "base/functional/bind.h" #include "base/ranges/algorithm.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "gin/data_object_builder.h" #include "services/device/public/cpp/usb/usb_utils.h" #include "services/device/public/mojom/usb_enumeration_options.mojom.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/usb/usb_chooser_context_factory.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/usb_device_info_converter.h" #include "shell/common/node_includes.h" #include "shell/common/process_util.h" #include "ui/base/l10n/l10n_util.h" #include "url/gurl.h" using content::RenderFrameHost; using content::WebContents; namespace electron { UsbChooserController::UsbChooserController( RenderFrameHost* render_frame_host, blink::mojom::WebUsbRequestDeviceOptionsPtr options, blink::mojom::WebUsbService::GetPermissionCallback callback, content::WebContents* web_contents, base::WeakPtr<ElectronUsbDelegate> usb_delegate) : WebContentsObserver(web_contents), options_(std::move(options)), callback_(std::move(callback)), origin_(render_frame_host->GetMainFrame()->GetLastCommittedOrigin()), usb_delegate_(usb_delegate), render_frame_host_id_(render_frame_host->GetGlobalId()) { chooser_context_ = UsbChooserContextFactory::GetForBrowserContext( web_contents->GetBrowserContext()) ->AsWeakPtr(); DCHECK(chooser_context_); chooser_context_->GetDevices(base::BindOnce( &UsbChooserController::GotUsbDeviceList, weak_factory_.GetWeakPtr())); } UsbChooserController::~UsbChooserController() { RunCallback(/*device_info=*/nullptr); } api::Session* UsbChooserController::GetSession() { if (!web_contents()) { return nullptr; } return api::Session::FromBrowserContext(web_contents()->GetBrowserContext()); } void UsbChooserController::OnDeviceAdded( const device::mojom::UsbDeviceInfo& device_info) { if (DisplayDevice(device_info)) { api::Session* session = GetSession(); if (session) { session->Emit("usb-device-added", device_info.Clone(), web_contents()); } } } void UsbChooserController::OnDeviceRemoved( const device::mojom::UsbDeviceInfo& device_info) { api::Session* session = GetSession(); if (session) { session->Emit("usb-device-removed", device_info.Clone(), web_contents()); } } void UsbChooserController::OnDeviceChosen(gin::Arguments* args) { std::string device_id; if (!args->GetNext(&device_id) || device_id.empty()) { RunCallback(/*device_info=*/nullptr); } else { auto* device_info = chooser_context_->GetDeviceInfo(device_id); if (device_info) { RunCallback(device_info->Clone()); } else { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); node::Environment* env = node::Environment::GetCurrent(isolate); EmitWarning(env, "The device id " + device_id + " was not found.", "UnknownUsbDeviceId"); RunCallback(/*device_info=*/nullptr); } } } void UsbChooserController::OnBrowserContextShutdown() { observation_.Reset(); } // Get a list of devices that can be shown in the chooser bubble UI for // user to grant permission. void UsbChooserController::GotUsbDeviceList( std::vector<::device::mojom::UsbDeviceInfoPtr> devices) { // Listen to UsbChooserContext for OnDeviceAdded/Removed events after the // enumeration. if (chooser_context_) observation_.Observe(chooser_context_.get()); bool prevent_default = false; api::Session* session = GetSession(); if (session) { auto* rfh = content::RenderFrameHost::FromID(render_frame_host_id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> details = gin::DataObjectBuilder(isolate) .Set("deviceList", devices) .Set("frame", rfh) .Build(); prevent_default = session->Emit("select-usb-device", details, base::BindRepeating(&UsbChooserController::OnDeviceChosen, weak_factory_.GetWeakPtr())); } if (!prevent_default) { RunCallback(/*device_info=*/nullptr); } } bool UsbChooserController::DisplayDevice( const device::mojom::UsbDeviceInfo& device_info) const { if (!device::UsbDeviceFilterMatchesAny(options_->filters, device_info)) { return false; } if (base::ranges::any_of( options_->exclusion_filters, [&device_info](const auto& filter) { return device::UsbDeviceFilterMatches(*filter, device_info); })) { return false; } return true; } void UsbChooserController::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { if (usb_delegate_) { usb_delegate_->DeleteControllerForFrame(render_frame_host); } } void UsbChooserController::RunCallback( device::mojom::UsbDeviceInfoPtr device_info) { if (callback_) { if (!chooser_context_ || !device_info) { std::move(callback_).Run(nullptr); } else { chooser_context_->GrantDevicePermission(origin_, *device_info); std::move(callback_).Run(std::move(device_info)); } } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
41,193
[Bug]: Unfulfilled loadURL promise on invalid URL load.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 v30.0.0-nightly.20240130 ### What operating system are you using? Windows ### Operating System Version Windows 10 but not system specific bug. ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior webcontents.loadURL("invalidURL") promise is rejected. ### Actual Behavior webcontents.loadURL("invalidURL") promise is never fulfilled. ### Testcase Gist URL https://gist.github.com/38969978ec04e1f315312b2daa02146e ### Additional Information This is regression after #40640 (#40661). Invalid URLs navigation never happens and only did-failt-load event is emitted immediately at electron api level (see for example https://github.com/electron/electron/blob/main/shell/browser/api/electron_api_web_contents.cc#L2392 and https://github.com/electron/electron/blob/main/shell/browser/api/electron_api_web_contents.cc#L2447). Navigations are not started so will never finish.
https://github.com/electron/electron/issues/41193
https://github.com/electron/electron/pull/41194
dac29f99492fda71dc79e1ee8874bee36a3b2ae6
398ca2a0190d6c86d908a71c887260bf13ef5e2b
2024-01-31T12:19:14Z
c++
2024-02-05T07:36:51Z
lib/browser/api/web-contents.ts
import { app, ipcMain, session, webFrameMain, dialog } from 'electron/main'; import type { BrowserWindowConstructorOptions, LoadURLOptions, MessageBoxOptions, WebFrameMain } 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'; import { IpcMainImpl } from '@electron/internal/browser/ipc-main-impl'; import * as deprecate from '@electron/internal/common/deprecate'; // session is not used here, the purpose is to make sure session is initialized // before the webContents module. // eslint-disable-next-line no-unused-expressions session; const webFrameMainBinding = process._linkedBinding('electron_browser_web_frame_main'); let nextId = 0; const getNextId = function () { return ++nextId; }; type PostData = LoadURLOptions['postData'] // Stock page sizes const PDFPageSizes: Record<string, ElectronInternal.MediaSize> = { Letter: { custom_display_name: 'Letter', height_microns: 279400, name: 'NA_LETTER', width_microns: 215900 }, Legal: { custom_display_name: 'Legal', height_microns: 355600, name: 'NA_LEGAL', width_microns: 215900 }, Tabloid: { height_microns: 431800, name: 'NA_LEDGER', width_microns: 279400, custom_display_name: 'Tabloid' }, A0: { custom_display_name: 'A0', height_microns: 1189000, name: 'ISO_A0', width_microns: 841000 }, A1: { custom_display_name: 'A1', height_microns: 841000, name: 'ISO_A1', width_microns: 594000 }, A2: { custom_display_name: 'A2', height_microns: 594000, name: 'ISO_A2', width_microns: 420000 }, A3: { custom_display_name: 'A3', height_microns: 420000, name: 'ISO_A3', width_microns: 297000 }, A4: { custom_display_name: 'A4', height_microns: 297000, name: 'ISO_A4', is_default: 'true', width_microns: 210000 }, A5: { custom_display_name: 'A5', height_microns: 210000, name: 'ISO_A5', width_microns: 148000 }, A6: { custom_display_name: 'A6', height_microns: 148000, name: 'ISO_A6', width_microns: 105000 } } as const; const paperFormats: Record<string, ElectronInternal.PageSize> = { letter: { width: 8.5, height: 11 }, legal: { width: 8.5, height: 14 }, tabloid: { width: 11, height: 17 }, ledger: { width: 17, height: 11 }, a0: { width: 33.1, height: 46.8 }, a1: { width: 23.4, height: 33.1 }, a2: { width: 16.54, height: 23.4 }, a3: { width: 11.7, height: 16.54 }, a4: { width: 8.27, height: 11.7 }, a5: { width: 5.83, height: 8.27 }, a6: { width: 4.13, height: 5.83 } } 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); }; // 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; }; // 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); }; function checkType<T> (value: T, type: 'number' | 'boolean' | 'string' | 'object', name: string): T { // eslint-disable-next-line valid-typeof if (typeof value !== type) { throw new TypeError(`${name} must be a ${type}`); } return value; } function parsePageSize (pageSize: string | ElectronInternal.PageSize) { if (typeof pageSize === 'string') { const format = paperFormats[pageSize.toLowerCase()]; if (!format) { throw new Error(`Invalid pageSize ${pageSize}`); } return { paperWidth: format.width, paperHeight: format.height }; } else if (typeof pageSize === 'object') { if (typeof pageSize.width !== 'number' || typeof pageSize.height !== 'number') { throw new TypeError('width and height properties are required for pageSize'); } return { paperWidth: pageSize.width, paperHeight: pageSize.height }; } else { throw new TypeError('pageSize must be a string or an object'); } } // Translate the options of printToPDF. let pendingPromise: Promise<any> | undefined; WebContents.prototype.printToPDF = async function (options) { const margins = checkType(options.margins ?? {}, 'object', 'margins'); const pageSize = parsePageSize(options.pageSize ?? 'letter'); const { top, bottom, left, right } = margins; const validHeight = [top, bottom].every(u => u === undefined || u <= pageSize.paperHeight); const validWidth = [left, right].every(u => u === undefined || u <= pageSize.paperWidth); if (!validHeight || !validWidth) { throw new Error('margins must be less than or equal to pageSize'); } const printSettings = { requestID: getNextId(), landscape: checkType(options.landscape ?? false, 'boolean', 'landscape'), displayHeaderFooter: checkType(options.displayHeaderFooter ?? false, 'boolean', 'displayHeaderFooter'), headerTemplate: checkType(options.headerTemplate ?? '', 'string', 'headerTemplate'), footerTemplate: checkType(options.footerTemplate ?? '', 'string', 'footerTemplate'), printBackground: checkType(options.printBackground ?? false, 'boolean', 'printBackground'), scale: checkType(options.scale ?? 1.0, 'number', 'scale'), marginTop: checkType(margins.top ?? 0.4, 'number', 'margins.top'), marginBottom: checkType(margins.bottom ?? 0.4, 'number', 'margins.bottom'), marginLeft: checkType(margins.left ?? 0.4, 'number', 'margins.left'), marginRight: checkType(margins.right ?? 0.4, 'number', 'margins.right'), pageRanges: checkType(options.pageRanges ?? '', 'string', 'pageRanges'), preferCSSPageSize: checkType(options.preferCSSPageSize ?? false, 'boolean', 'preferCSSPageSize'), generateTaggedPDF: checkType(options.generateTaggedPDF ?? false, 'boolean', 'generateTaggedPDF'), generateDocumentOutline: checkType(options.generateDocumentOutline ?? false, 'boolean', 'generateDocumentOutline'), ...pageSize }; if (this._printToPDF) { if (pendingPromise) { pendingPromise = pendingPromise.then(() => this._printToPDF(printSettings)); } else { pendingPromise = this._printToPDF(printSettings); } return pendingPromise; } else { throw new Error('Printing feature is disabled'); } }; // TODO(codebytere): deduplicate argument sanitization by moving rest of // print param logic into new file shared between printToPDF and print WebContents.prototype.print = function (options: ElectronInternal.WebContentsPrintOptions, callback) { if (typeof options !== 'object') { throw new TypeError('webContents.print(): Invalid print settings specified.'); } const printSettings: Record<string, any> = { ...options }; const pageSize = options.pageSize ?? 'A4'; 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 RangeError('height and width properties must be minimum 352 microns.'); } printSettings.mediaSize = { name: 'CUSTOM', custom_display_name: 'Custom', height_microns: height, width_microns: width, imageable_area_left_microns: 0, imageable_area_bottom_microns: 0, imageable_area_right_microns: width, imageable_area_top_microns: height }; } else if (typeof pageSize === 'string' && PDFPageSizes[pageSize]) { const mediaSize = PDFPageSizes[pageSize]; printSettings.mediaSize = { ...mediaSize, imageable_area_left_microns: 0, imageable_area_bottom_microns: 0, imageable_area_right_microns: mediaSize.width_microns, imageable_area_top_microns: mediaSize.height_microns }; } else { throw new Error(`Unsupported pageSize: ${pageSize}`); } if (this._print) { if (callback) { this._print(printSettings, callback); } else { this._print(printSettings); } } else { console.error('Error: Printing feature is disabled.'); } }; 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 TypeError('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 })); }; type LoadError = { errorCode: number, errorDescription: string, url: string }; WebContents.prototype.loadURL = function (url, options) { const p = new Promise<void>((resolve, reject) => { const resolveAndCleanup = () => { removeListeners(); resolve(); }; let error: LoadError | undefined; const rejectAndCleanup = ({ errorCode, errorDescription, url }: LoadError) => { 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 = () => { if (error) { rejectAndCleanup(error); } else { resolveAndCleanup(); } }; const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => { if (!error && isMainFrame) { error = { errorCode, errorDescription, url: validatedURL }; } }; let navigationStarted = false; let browserInitiatedInPageNavigation = 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({ errorCode: -3, errorDescription: 'ERR_ABORTED', url }); } browserInitiatedInPageNavigation = navigationStarted && isSameDocument; 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. if (!error) { error = { errorCode: -2, errorDescription: 'ERR_FAILED', url: url }; } finishListener(); }; const finishListenerWhenUserInitiatedNavigation = () => { if (!browserInitiatedInPageNavigation) { finishListener(); } }; const removeListeners = () => { this.removeListener('did-finish-load', finishListener); this.removeListener('did-fail-load', failListener); this.removeListener('did-navigate-in-page', finishListenerWhenUserInitiatedNavigation); 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-navigate-in-page', finishListenerWhenUserInitiatedNavigation); 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 ?? {}); 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') { return { browserWindowConstructorOptions: typeof response.overrideBrowserWindowOptions === 'object' ? response.overrideBrowserWindowOptions : null, 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 addSenderToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent, sender: Electron.WebContents) => { event.sender = sender; 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._replyChannel.sendReply(value), get: () => {} }); }; const getWebFrameForEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => { if (!event.processId || !event.frameId) return null; return webFrameMainBinding.fromIdOrNull(event.processId, event.frameId); }; 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; const ipc = new IpcMainImpl(); Object.defineProperty(this, 'ipc', { get () { return ipc; }, enumerable: true }); // 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[]) { addSenderToEvent(event, this); if (internal) { ipcMainInternal.emit(channel, event, ...args); } else { addReplyToEvent(event); this.emit('ipc-message', event, channel, ...args); const maybeWebFrame = getWebFrameForEvent(event); maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, ...args); ipc.emit(channel, event, ...args); ipcMain.emit(channel, event, ...args); } }); this.on('-ipc-invoke' as any, async function (this: Electron.WebContents, event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) { addSenderToEvent(event, this); const replyWithResult = (result: any) => event._replyChannel.sendReply({ result }); const replyWithError = (error: Error) => { console.error(`Error occurred in handler for '${channel}':`, error); event._replyChannel.sendReply({ error: error.toString() }); }; const maybeWebFrame = getWebFrameForEvent(event); const targets: (ElectronInternal.IpcMainInternal| undefined)[] = internal ? [ipcMainInternal] : [maybeWebFrame?.ipc, ipc, ipcMain]; const target = targets.find(target => target && (target as any)._invokeHandlers.has(channel)); if (target) { const handler = (target as any)._invokeHandlers.get(channel); try { replyWithResult(await Promise.resolve(handler(event, ...args))); } catch (err) { replyWithError(err as Error); } } else { replyWithError(new Error(`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[]) { addSenderToEvent(event, this); addReturnValueToEvent(event); if (internal) { ipcMainInternal.emit(channel, event, ...args); } else { addReplyToEvent(event); const maybeWebFrame = getWebFrameForEvent(event); if (this.listenerCount('ipc-message-sync') === 0 && ipc.listenerCount(channel) === 0 && ipcMain.listenerCount(channel) === 0 && (!maybeWebFrame || maybeWebFrame.ipc.listenerCount(channel) === 0)) { console.warn(`WebContents #${this.id} called ipcRenderer.sendSync() with '${channel}' channel without listeners.`); } this.emit('ipc-message-sync', event, channel, ...args); maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, ...args); ipc.emit(channel, event, ...args); ipcMain.emit(channel, event, ...args); } }); this.on('-ipc-ports' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) { addSenderToEvent(event, this); event.ports = ports.map(p => new MessagePortMain(p)); const maybeWebFrame = getWebFrameForEvent(event); maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, message); ipc.emit(channel, event, message); ipcMain.emit(channel, event, message); }); 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.`); } }); this.on('-before-unload-fired' as any, function (this: Electron.WebContents, event: Electron.Event, proceed: boolean) { const type = this.getType(); // These are the "interactive" types, i.e. ones a user might be looking at. // All other types should ignore the "proceed" signal and unload // regardless. if (type === 'window' || type === 'offscreen' || type === 'browserView') { if (!proceed) { return event.preventDefault(); } } }); // 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: Electron.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 }; let result: ReturnType<typeof this._callWindowOpenHandler>; try { result = this._callWindowOpenHandler(event, details); } catch (err) { event.preventDefault(); throw err; } const options = result.browserWindowConstructorOptions; if (!event.defaultPrevented) { openGuestWindow({ embedder: this, 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: Electron.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 }; let result: ReturnType<typeof this._callWindowOpenHandler>; try { result = this._callWindowOpenHandler(event, details); } catch (err) { event.preventDefault(); throw err; } 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; const { webPreferences: parsedWebPreferences } = parseFeatures(rawFeatures); const webPreferences = makeWebPreferences({ embedder: this, insecureParsedWebPreferences: parsedWebPreferences, secureOverrideWebPreferences }); windowOpenOverriddenOptions = { ...windowOpenOverriddenOptions, webPreferences }; this._setNextChildWebPreferences(webPreferences); } }); // Create a new browser window for "window.open" this.on('-add-new-contents' as any, (event: Electron.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({ embedder: this, 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 originCounts = new Map<string, number>(); const openDialogs = new Set<AbortController>(); this.on('-run-dialog' as any, async (info: {frame: WebFrameMain, dialogType: 'prompt' | 'confirm' | 'alert', messageText: string, defaultPromptText: string}, callback: (success: boolean, user_input: string) => void) => { const originUrl = new URL(info.frame.url); const origin = originUrl.protocol === 'file:' ? originUrl.href : originUrl.origin; if ((originCounts.get(origin) ?? 0) < 0) return callback(false, ''); const prefs = this.getLastWebPreferences(); if (!prefs || prefs.disableDialogs) return callback(false, ''); // We don't support prompt() for some reason :) if (info.dialogType === 'prompt') return callback(false, ''); originCounts.set(origin, (originCounts.get(origin) ?? 0) + 1); // TODO: translate? const checkbox = originCounts.get(origin)! > 1 && prefs.safeDialogs ? prefs.safeDialogsMessage || 'Prevent this app from creating additional dialogs' : ''; const parent = this.getOwnerBrowserWindow(); const abortController = new AbortController(); const options: MessageBoxOptions = { message: info.messageText, checkboxLabel: checkbox, signal: abortController.signal, ...(info.dialogType === 'confirm') ? { buttons: ['OK', 'Cancel'], defaultId: 0, cancelId: 1 } : { buttons: ['OK'], defaultId: -1, // No default button cancelId: 0 } }; openDialogs.add(abortController); const promise = parent && !prefs.offscreen ? dialog.showMessageBox(parent, options) : dialog.showMessageBox(options); try { const result = await promise; if (abortController.signal.aborted || this.isDestroyed()) return; if (result.checkboxChecked) originCounts.set(origin, -1); return callback(result.response === 0, ''); } finally { openDialogs.delete(abortController); } }); this.on('-cancel-dialogs' as any, () => { for (const controller of openDialogs) { controller.abort(); } openDialogs.clear(); }); app.emit('web-contents-created', { sender: this, preventDefault () {}, get defaultPrevented () { return false; } }, 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 fromFrame (frame: Electron.WebFrameMain) { return binding.fromFrame(frame); } 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
41,193
[Bug]: Unfulfilled loadURL promise on invalid URL load.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 v30.0.0-nightly.20240130 ### What operating system are you using? Windows ### Operating System Version Windows 10 but not system specific bug. ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior webcontents.loadURL("invalidURL") promise is rejected. ### Actual Behavior webcontents.loadURL("invalidURL") promise is never fulfilled. ### Testcase Gist URL https://gist.github.com/38969978ec04e1f315312b2daa02146e ### Additional Information This is regression after #40640 (#40661). Invalid URLs navigation never happens and only did-failt-load event is emitted immediately at electron api level (see for example https://github.com/electron/electron/blob/main/shell/browser/api/electron_api_web_contents.cc#L2392 and https://github.com/electron/electron/blob/main/shell/browser/api/electron_api_web_contents.cc#L2447). Navigations are not started so will never finish.
https://github.com/electron/electron/issues/41193
https://github.com/electron/electron/pull/41194
dac29f99492fda71dc79e1ee8874bee36a3b2ae6
398ca2a0190d6c86d908a71c887260bf13ef5e2b
2024-01-31T12:19:14Z
c++
2024-02-05T07:36:51Z
spec/api-web-contents-spec.ts
import { expect } from 'chai'; import { AddressInfo } from 'node:net'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as http from 'node:http'; import { BrowserWindow, ipcMain, webContents, session, app, BrowserView, WebContents } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import { ifdescribe, defer, waitUntil, listen, ifit } from './lib/spec-helpers'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; const pdfjs = require('pdfjs-dist'); const fixturesPath = path.resolve(__dirname, 'fixtures'); const mainFixturesPath = path.resolve(__dirname, 'fixtures'); const features = process._linkedBinding('electron_common_features'); describe('webContents module', () => { describe('getAllWebContents() API', () => { afterEach(closeAllWindows); it('returns an array of web contents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html')); await once(w.webContents, 'did-attach-webview') as [any, WebContents]; w.webContents.openDevTools(); await once(w.webContents, 'devtools-opened'); const all = webContents.getAllWebContents().sort((a, b) => { return a.id - b.id; }); expect(all).to.have.length(3); expect(all[0].getType()).to.equal('window'); expect(all[all.length - 2].getType()).to.equal('webview'); expect(all[all.length - 1].getType()).to.equal('remote'); }); }); describe('fromId()', () => { it('returns undefined for an unknown id', () => { expect(webContents.fromId(12345)).to.be.undefined(); }); }); describe('fromFrame()', () => { it('returns WebContents for mainFrame', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); expect(webContents.fromFrame(contents.mainFrame)).to.equal(contents); }); it('returns undefined for disposed frame', async () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); const { mainFrame } = contents; contents.destroy(); await waitUntil(() => typeof webContents.fromFrame(mainFrame) === 'undefined'); }); it('throws when passing invalid argument', async () => { let errored = false; try { webContents.fromFrame({} as any); } catch { errored = true; } expect(errored).to.be.true(); }); }); describe('fromDevToolsTargetId()', () => { it('returns WebContents for attached DevTools target', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); try { await w.webContents.debugger.attach('1.3'); const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo'); expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents); } finally { await w.webContents.debugger.detach(); } }); it('returns undefined for an unknown id', () => { expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined(); }); }); describe('will-prevent-unload event', function () { afterEach(closeAllWindows); it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('does not emit if beforeunload returns undefined in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); view.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits if beforeunload returns false in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, 'will-prevent-unload'); }); it('emits if beforeunload returns false in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(view.webContents, 'will-prevent-unload'); }); it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', event => event.preventDefault()); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); const wait = once(w, 'closed'); w.close(); await wait; }); }); describe('webContents.send(channel, args...)', () => { afterEach(closeAllWindows); it('throws an error when the channel is missing', () => { const w = new BrowserWindow({ show: false }); expect(() => { (w.webContents.send as any)(); }).to.throw('Missing required channel argument'); expect(() => { w.webContents.send(null as any); }).to.throw('Missing required channel argument'); }); it('does not block node async APIs when sent before document is ready', (done) => { // Please reference https://github.com/electron/electron/issues/19368 if // this test fails. ipcMain.once('async-node-api-done', () => { done(); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, sandbox: false, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html')); setTimeout(50).then(() => { w.webContents.send('test'); }); }); }); ifdescribe(features.isPrintingEnabled())('webContents.print()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('throws when invalid settings are passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print(true); }).to.throw('webContents.print(): Invalid print settings specified.'); }); it('throws when an invalid pageSize is passed', () => { const badSize = 5; expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({ pageSize: badSize }); }).to.throw(`Unsupported pageSize: ${badSize}`); }); it('throws when an invalid callback is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({}, true); }).to.throw('webContents.print(): Invalid optional callback provided.'); }); it('fails when an invalid deviceName is passed', (done) => { w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => { expect(success).to.equal(false); expect(reason).to.match(/Invalid deviceName provided/); done(); }); }); it('throws when an invalid pageSize is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {}); }).to.throw('Unsupported pageSize: i-am-a-bad-pagesize'); }); it('throws when an invalid custom pageSize is passed', () => { expect(() => { w.webContents.print({ pageSize: { width: 100, height: 200 } }); }).to.throw('height and width properties must be minimum 352 microns.'); }); it('does not crash with custom margins', () => { expect(() => { w.webContents.print({ silent: true, margins: { marginType: 'custom', top: 1, bottom: 1, left: 1, right: 1 } }); }).to.not.throw(); }); }); describe('webContents.executeJavaScript', () => { describe('in about:blank', () => { const expected = 'hello, world!'; const expectedErrorMsg = 'woops!'; const code = `(() => "${expected}")()`; const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`; const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`; const errorTypes = new Set([ Error, ReferenceError, EvalError, RangeError, SyntaxError, TypeError, URIError ]); let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } }); await w.loadURL('about:blank'); }); after(closeAllWindows); it('resolves the returned promise with the result', async () => { const result = await w.webContents.executeJavaScript(code); expect(result).to.equal(expected); }); it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => { const result = await w.webContents.executeJavaScript(asyncCode); expect(result).to.equal(expected); }); it('rejects the returned promise if an async error is thrown', async () => { await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg); }); it('rejects the returned promise with an error if an Error.prototype is thrown', async () => { for (const error of errorTypes) { await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`)) .to.eventually.be.rejectedWith(error); } }); }); describe('on a real page', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('works after page load and during subframe load', async () => { await w.loadURL(serverUrl); // initiate a sub-frame load, then try and execute script during it await w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/slow' document.body.appendChild(iframe) null // don't return the iframe `); await w.webContents.executeJavaScript('console.log(\'hello\')'); }); it('executes after page load', async () => { const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()'); w.loadURL(serverUrl); const result = await executeJavaScript; expect(result).to.equal('test'); }); }); }); describe('webContents.executeJavaScriptInIsolatedWorld', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadURL('about:blank'); }); it('resolves the returned promise with the result', async () => { await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]); const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]); const mainWorldResult = await w.webContents.executeJavaScript('window.X'); expect(isolatedResult).to.equal(123); expect(mainWorldResult).to.equal(undefined); }); }); describe('loadURL() promise API', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('resolves when done loading', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('resolves when done loading a file URL', async () => { await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled(); }); it('resolves when navigating within the page', async () => { await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await setTimeout(); await expect(w.loadURL(w.getURL() + '#foo')).to.eventually.be.fulfilled(); }); it('resolves after browser initiated navigation', async () => { let finishedLoading = false; w.webContents.on('did-finish-load', function () { finishedLoading = true; }); await w.loadFile(path.join(fixturesPath, 'pages', 'navigate_in_page_and_wait.html')); expect(finishedLoading).to.be.true(); }); it('rejects when failing to load a file URL', async () => { await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FILE_NOT_FOUND'); }); // FIXME: Temporarily disable on WOA until // https://github.com/electron/electron/issues/20008 is resolved ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('rejects when loading fails due to DNS not resolved', async () => { await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected() .and.have.property('code', 'ERR_NAME_NOT_RESOLVED'); }); it('rejects when navigation is cancelled due to a bad scheme', async () => { await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FAILED'); }); it('does not crash when loading a new URL with emulation settings set', async () => { const setEmulation = async () => { if (w.webContents) { w.webContents.debugger.attach('1.3'); const deviceMetrics = { width: 700, height: 600, deviceScaleFactor: 2, mobile: true, dontSetVisibleSize: true }; await w.webContents.debugger.sendCommand( 'Emulation.setDeviceMetricsOverride', deviceMetrics ); } }; try { await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await setEmulation(); await w.loadURL('data:text/html,<h1>HELLO</h1>'); await setEmulation(); } catch (e) { expect((e as Error).message).to.match(/Debugger is already attached to the target/); } }); it('fails if loadURL is called inside a non-reentrant critical section', (done) => { w.webContents.once('did-fail-load', (_event, _errorCode, _errorDescription, validatedURL) => { expect(validatedURL).to.contain('blank.html'); done(); }); w.webContents.once('did-start-loading', () => { w.loadURL(`file://${fixturesPath}/pages/blank.html`); }); w.loadURL('data:text/html,<h1>HELLO</h1>'); }); it('sets appropriate error information on rejection', async () => { let err: any; try { await w.loadURL('file:non-existent'); } catch (e) { err = e; } expect(err).not.to.be.null(); expect(err.code).to.eql('ERR_FILE_NOT_FOUND'); expect(err.errno).to.eql(-6); expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent'); }); it('rejects if the load is aborted', async () => { const s = http.createServer(() => { /* never complete the request */ }); const { port } = await listen(s); const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/); // load a different file before the first load completes, causing the // first load to be aborted. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await p; s.close(); }); it("doesn't reject when a subframe fails to load", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="http://err.name.not.resolved"></iframe>'); resp = res; // don't end the response yet }); const { port } = await listen(s); const p = new Promise<void>(resolve => { w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.end(); await main; s.close(); }); it("doesn't resolve when a subframe loads", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="about:blank"></iframe>'); resp = res; // don't end the response yet }); const { port } = await listen(s); const p = new Promise<void>(resolve => { w.webContents.on('did-frame-finish-load', (event, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.destroy(); // cause the main request to fail await expect(main).to.eventually.be.rejected() .and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING s.close(); }); it('subsequent load failures reject each time', async () => { await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected(); await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected(); }); }); describe('getFocusedWebContents() API', () => { afterEach(closeAllWindows); // FIXME ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('returns the focused web contents', async () => { const w = new BrowserWindow({ show: true }); await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id); const devToolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools(); await devToolsOpened; expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.devToolsWebContents!.id); const devToolsClosed = once(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id); }); it('does not crash when called on a detached dev tools window', async () => { const w = new BrowserWindow({ show: true }); w.webContents.openDevTools({ mode: 'detach' }); w.webContents.inspectElement(100, 100); // For some reason we have to wait for two focused events...? await once(w.webContents, 'devtools-focused'); expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); // Work around https://github.com/electron/electron/issues/19985 await setTimeout(); const devToolsClosed = once(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); }); }); describe('setDevToolsWebContents() API', () => { afterEach(closeAllWindows); it('sets arbitrary webContents as devtools', async () => { const w = new BrowserWindow({ show: false }); const devtools = new BrowserWindow({ show: false }); const promise = once(devtools.webContents, 'dom-ready'); w.webContents.setDevToolsWebContents(devtools.webContents); w.webContents.openDevTools(); await promise; expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true(); const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name'); expect(result).to.equal('InspectorFrontendHostImpl'); devtools.destroy(); }); }); describe('isFocused() API', () => { it('returns false when the window is hidden', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(w.isVisible()).to.be.false(); expect(w.webContents.isFocused()).to.be.false(); }); }); describe('isCurrentlyAudible() API', () => { afterEach(closeAllWindows); it('returns whether audio is playing', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript(` window.context = new AudioContext // Start in suspended state, because of the // new web audio api policy. context.suspend() window.oscillator = context.createOscillator() oscillator.connect(context.destination) oscillator.start() `); let p = once(w.webContents, 'audio-state-changed'); w.webContents.executeJavaScript('context.resume()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.true(); p = once(w.webContents, 'audio-state-changed'); w.webContents.executeJavaScript('oscillator.stop()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.false(); }); }); describe('openDevTools() API', () => { afterEach(closeAllWindows); it('can show window with activation', async () => { const w = new BrowserWindow({ show: false }); const focused = once(w, 'focus'); w.show(); await focused; expect(w.isFocused()).to.be.true(); const blurred = once(w, 'blur'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await Promise.all([ once(w.webContents, 'devtools-opened'), once(w.webContents, 'devtools-focused') ]); await blurred; expect(w.isFocused()).to.be.false(); }); it('can show window without activation', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); }); it('can show a DevTools window with custom title', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false, title: 'myTitle' }); await devtoolsOpened; expect(w.webContents.getDevToolsTitle()).to.equal('myTitle'); }); it('can re-open devtools', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); const devtoolsClosed = once(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devtoolsClosed; expect(w.webContents.isDevToolsOpened()).to.be.false(); const devtoolsOpened2 = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await devtoolsOpened2; expect(w.webContents.isDevToolsOpened()).to.be.true(); }); }); describe('setDevToolsTitle() API', () => { afterEach(closeAllWindows); it('can set devtools title with function', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); w.webContents.setDevToolsTitle('newTitle'); expect(w.webContents.getDevToolsTitle()).to.equal('newTitle'); }); }); describe('before-input-event event', () => { afterEach(closeAllWindows); it('can prevent document keyboard events', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); const keyDown = new Promise(resolve => { ipcMain.once('keydown', (event, key) => resolve(key)); }); w.webContents.once('before-input-event', (event, input) => { if (input.key === 'a') event.preventDefault(); }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' }); expect(await keyDown).to.equal('b'); }); it('has the correct properties', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testBeforeInput = async (opts: any) => { const modifiers = []; if (opts.shift) modifiers.push('shift'); if (opts.control) modifiers.push('control'); if (opts.alt) modifiers.push('alt'); if (opts.meta) modifiers.push('meta'); if (opts.isAutoRepeat) modifiers.push('isAutoRepeat'); const p = once(w.webContents, 'before-input-event') as Promise<[any, Electron.Input]>; w.webContents.sendInputEvent({ type: opts.type, keyCode: opts.keyCode, modifiers: modifiers as any }); const [, input] = await p; expect(input.type).to.equal(opts.type); expect(input.key).to.equal(opts.key); expect(input.code).to.equal(opts.code); expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat); expect(input.shift).to.equal(opts.shift); expect(input.control).to.equal(opts.control); expect(input.alt).to.equal(opts.alt); expect(input.meta).to.equal(opts.meta); }; await testBeforeInput({ type: 'keyDown', key: 'A', code: 'KeyA', keyCode: 'a', shift: true, control: true, alt: true, meta: true, isAutoRepeat: true }); await testBeforeInput({ type: 'keyUp', key: '.', code: 'Period', keyCode: '.', shift: false, control: true, alt: true, meta: false, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: '!', code: 'Digit1', keyCode: '1', shift: true, control: false, alt: false, meta: true, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: 'Tab', code: 'Tab', keyCode: 'Tab', shift: false, control: true, alt: false, meta: false, isAutoRepeat: true }); }); }); // On Mac, zooming isn't done with the mouse wheel. ifdescribe(process.platform !== 'darwin')('zoom-changed', () => { afterEach(closeAllWindows); it('is emitted with the correct zoom-in info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: 1, wheelTicksX: 0, wheelTicksY: 1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string]; expect(zoomDirection).to.equal('in'); }; await testZoomChanged(); }); it('is emitted with the correct zoom-out info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: -1, wheelTicksX: 0, wheelTicksY: -1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string]; expect(zoomDirection).to.equal('out'); }; await testZoomChanged(); }); }); describe('sendInputEvent(event)', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); }); afterEach(closeAllWindows); it('can send keydown events', async () => { const keydown = once(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send keydown events with modifiers', async () => { const keydown = once(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); it('can send keydown events with special keys', async () => { const keydown = once(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Tab'); expect(code).to.equal('Tab'); expect(keyCode).to.equal(9); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.true(); }); it('can send char events', async () => { const keypress = once(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can correctly convert accelerators to key codes', async () => { const keyup = once(ipcMain, 'keyup'); w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' }); w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'keyUp' }); await keyup; const inputText = await w.webContents.executeJavaScript('document.getElementById("input").value'); expect(inputText).to.equal('+ + +'); }); it('can send char events with modifiers', async () => { const keypress = once(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); }); describe('insertCSS', () => { afterEach(closeAllWindows); it('supports inserting CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.webContents.insertCSS('body { background-repeat: round; }'); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('round'); }); it('supports removing inserted CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const key = await w.webContents.insertCSS('body { background-repeat: round; }'); await w.webContents.removeInsertedCSS(key); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('repeat'); }); }); describe('inspectElement()', () => { afterEach(closeAllWindows); it('supports inspecting an element in the devtools', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const event = once(w.webContents, 'devtools-opened'); w.webContents.inspectElement(10, 10); await event; }); }); describe('startDrag({file, icon})', () => { it('throws errors for a missing file or a missing/empty icon', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any); }).to.throw('Must specify either \'file\' or \'files\' option'); expect(() => { w.webContents.startDrag({ file: __filename } as any); }).to.throw('\'icon\' parameter is required'); expect(() => { w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') }); }).to.throw(/Failed to load image from path (.+)/); }); }); describe('focus APIs', () => { describe('focus()', () => { afterEach(closeAllWindows); it('does not blur the focused window when the web contents is hidden', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.show(); await w.loadURL('about:blank'); w.focus(); const child = new BrowserWindow({ show: false }); child.loadURL('about:blank'); child.webContents.focus(); const currentFocused = w.isFocused(); const childFocused = child.isFocused(); child.close(); expect(currentFocused).to.be.true(); expect(childFocused).to.be.false(); }); }); const moveFocusToDevTools = async (win: BrowserWindow) => { const devToolsOpened = once(win.webContents, 'devtools-opened'); win.webContents.openDevTools({ mode: 'right' }); await devToolsOpened; win.webContents.devToolsWebContents!.focus(); }; describe('focus event', () => { afterEach(closeAllWindows); it('is triggered when web contents is focused', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await moveFocusToDevTools(w); const focusPromise = once(w.webContents, 'focus'); w.webContents.focus(); await expect(focusPromise).to.eventually.be.fulfilled(); }); }); describe('blur event', () => { afterEach(closeAllWindows); it('is triggered when web contents is blurred', async () => { const w = new BrowserWindow({ show: true }); await w.loadURL('about:blank'); w.webContents.focus(); const blurPromise = once(w.webContents, 'blur'); await moveFocusToDevTools(w); await expect(blurPromise).to.eventually.be.fulfilled(); }); }); }); describe('getOSProcessId()', () => { afterEach(closeAllWindows); it('returns a valid process id', async () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getOSProcessId()).to.equal(0); await w.loadURL('about:blank'); expect(w.webContents.getOSProcessId()).to.be.above(0); }); }); describe('getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns a valid stream id', () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty(); }); }); describe('userAgent APIs', () => { it('is not empty by default', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); expect(userAgent).to.be.a('string').that.is.not.empty(); }); it('can set the user agent (functions)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); w.webContents.setUserAgent('my-user-agent'); expect(w.webContents.getUserAgent()).to.equal('my-user-agent'); w.webContents.setUserAgent(userAgent); expect(w.webContents.getUserAgent()).to.equal(userAgent); }); it('can set the user agent (properties)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.userAgent; w.webContents.userAgent = 'my-user-agent'; expect(w.webContents.userAgent).to.equal('my-user-agent'); w.webContents.userAgent = userAgent; expect(w.webContents.userAgent).to.equal(userAgent); }); }); describe('audioMuted APIs', () => { it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.setAudioMuted(true); expect(w.webContents.isAudioMuted()).to.be.true(); w.webContents.setAudioMuted(false); expect(w.webContents.isAudioMuted()).to.be.false(); }); it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.audioMuted = true; expect(w.webContents.audioMuted).to.be.true(); w.webContents.audioMuted = false; expect(w.webContents.audioMuted).to.be.false(); }); }); describe('zoom api', () => { const hostZoomMap: Record<string, number> = { host1: 0.3, host2: 0.7, host3: 0.2 }; before(() => { const protocol = session.defaultSession.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { const response = `<script> const {ipcRenderer} = require('electron') ipcRenderer.send('set-zoom', window.location.hostname) ipcRenderer.on(window.location.hostname + '-zoom-set', () => { ipcRenderer.send(window.location.hostname + '-zoom-level') }) </script>`; callback({ data: response, mimeType: 'text/html' }); }); }); after(() => { const protocol = session.defaultSession.protocol; protocol.unregisterProtocol(standardScheme); }); afterEach(closeAllWindows); it('throws on an invalid zoomFactor', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { w.webContents.setZoomFactor(0.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); expect(() => { w.webContents.setZoomFactor(-2.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); }); it('can set the correct zoom level (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.getZoomLevel(); expect(zoomLevel).to.eql(0.0); w.webContents.setZoomLevel(0.5); const newZoomLevel = w.webContents.getZoomLevel(); expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.setZoomLevel(0); } }); it('can set the correct zoom level (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.eql(0.0); w.webContents.zoomLevel = 0.5; const newZoomLevel = w.webContents.zoomLevel; expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.zoomLevel = 0; } }); it('can set the correct zoom factor (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.getZoomFactor(); expect(zoomFactor).to.eql(1.0); w.webContents.setZoomFactor(0.5); const newZoomFactor = w.webContents.getZoomFactor(); expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.setZoomFactor(1.0); } }); it('can set the correct zoom factor (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.zoomFactor; expect(zoomFactor).to.eql(1.0); w.webContents.zoomFactor = 0.5; const newZoomFactor = w.webContents.zoomFactor; expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.zoomFactor = 1.0; } }); it('can persist zoom level across navigation', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let finalNavigation = false; ipcMain.on('set-zoom', (e, host) => { const zoomLevel = hostZoomMap[host]; if (!finalNavigation) w.webContents.zoomLevel = zoomLevel; e.sender.send(`${host}-zoom-set`); }); ipcMain.on('host1-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host1; expect(zoomLevel).to.equal(expectedZoomLevel); if (finalNavigation) { done(); } else { w.loadURL(`${standardScheme}://host2`); } } catch (e) { done(e); } }); ipcMain.once('host2-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host2; expect(zoomLevel).to.equal(expectedZoomLevel); finalNavigation = true; w.webContents.goBack(); } catch (e) { done(e); } }); w.loadURL(`${standardScheme}://host1`); }); it('can propagate zoom level across same session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false }); defer(() => { w2.setClosable(true); w2.close(); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel1).to.equal(zoomLevel2); }); it('cannot propagate zoom level across different session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false, webPreferences: { partition: 'temp' } }); const protocol = w2.webContents.session.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { callback('hello'); }); defer(() => { w2.setClosable(true); w2.close(); protocol.unregisterProtocol(standardScheme); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); it('can persist when it contains iframe', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { setTimeout(200).then(() => { res.end(); }); }); listen(server).then(({ url }) => { const content = `<iframe src=${url}></iframe>`; w.webContents.on('did-frame-finish-load', (e, isMainFrame) => { if (!isMainFrame) { try { const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(2.0); w.webContents.zoomLevel = 0; done(); } catch (e) { done(e); } finally { server.close(); } } }); w.webContents.on('dom-ready', () => { w.webContents.zoomLevel = 2.0; }); w.loadURL(`data:text/html,${content}`); }); }); it('cannot propagate when used with webframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const w2 = new BrowserWindow({ show: false }); const temporaryZoomSet = once(ipcMain, 'temporary-zoom-set'); w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html')); await temporaryZoomSet; const finalZoomLevel = w.webContents.getZoomLevel(); await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html')); const zoomLevel1 = w.webContents.zoomLevel; const zoomLevel2 = w2.webContents.zoomLevel; w2.setClosable(true); w2.close(); expect(zoomLevel1).to.equal(finalZoomLevel); expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); describe('with unique domains', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before(async () => { server = http.createServer((req, res) => { setTimeout().then(() => res.end('hey')); }); serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); after(() => { server.close(); }); it('cannot persist zoom level after navigation with webFrame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const source = ` const {ipcRenderer, webFrame} = require('electron') webFrame.setZoomLevel(0.6) ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel()) `; const zoomLevelPromise = once(ipcMain, 'zoom-level-set'); await w.loadURL(serverUrl); await w.webContents.executeJavaScript(source); let [, zoomLevel] = await zoomLevelPromise; expect(zoomLevel).to.equal(0.6); const loadPromise = once(w.webContents, 'did-finish-load'); await w.loadURL(crossSiteUrl); await loadPromise; zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(0); }); }); }); describe('webrtc ip policy api', () => { afterEach(closeAllWindows); it('can set and get webrtc ip policies', () => { const w = new BrowserWindow({ show: false }); const policies = [ 'default', 'default_public_interface_only', 'default_public_and_private_interfaces', 'disable_non_proxied_udp' ] as const; for (const policy of policies) { w.webContents.setWebRTCIPHandlingPolicy(policy); expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy); } }); }); describe('webrtc udp port range policy api', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('check default webrtc udp port range is { min: 0, max: 0 }', () => { const settings = w.webContents.getWebRTCUDPPortRange(); expect(settings).to.deep.equal({ min: 0, max: 0 }); }); it('can set and get webrtc udp port range policy with correct arguments', () => { w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 }); const settings = w.webContents.getWebRTCUDPPortRange(); expect(settings).to.deep.equal({ min: 1, max: 65535 }); }); it('can not set webrtc udp port range policy with invalid arguments', () => { expect(() => { w.webContents.setWebRTCUDPPortRange({ min: 0, max: 65535 }); }).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]"); expect(() => { w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65536 }); }).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]"); expect(() => { w.webContents.setWebRTCUDPPortRange({ min: 60000, max: 56789 }); }).to.throw("'max' must be greater than or equal to 'min'"); }); it('can reset webrtc udp port range policy to default with { min: 0, max: 0 }', () => { w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 }); const settings = w.webContents.getWebRTCUDPPortRange(); expect(settings).to.deep.equal({ min: 1, max: 65535 }); w.webContents.setWebRTCUDPPortRange({ min: 0, max: 0 }); const defaultSetting = w.webContents.getWebRTCUDPPortRange(); expect(defaultSetting).to.deep.equal({ min: 0, max: 0 }); }); }); describe('opener api', () => { afterEach(closeAllWindows); it('can get opener with window.open()', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>; w.webContents.executeJavaScript('window.open("about:blank")', true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame); }); it('has no opener when using "noopener"', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>; w.webContents.executeJavaScript('window.open("about:blank", undefined, "noopener")', true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.be.null(); }); it('can get opener with a[target=_blank][rel=opener]', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>; w.webContents.executeJavaScript(`(function() { const a = document.createElement('a'); a.target = '_blank'; a.rel = 'opener'; a.href = 'about:blank'; a.click(); }())`, true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame); }); it('has no opener with a[target=_blank][rel=noopener]', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>; w.webContents.executeJavaScript(`(function() { const a = document.createElement('a'); a.target = '_blank'; a.rel = 'noopener'; a.href = 'about:blank'; a.click(); }())`, true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.be.null(); }); }); describe('render view deleted events', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before(async () => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${crossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else if (req.url === '/first-window-open') { res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`); } else if (req.url === '/second-window-open') { res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>'); } else { res.end(); } }; setTimeout().then(respond); }); serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); after(() => { server.close(); }); afterEach(closeAllWindows); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); w.webContents.on('did-finish-load', () => { w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted'); }); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const parentWindow = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; let childWindow: BrowserWindow | null = null; const destroyed = once(parentWindow.webContents, 'destroyed'); const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; const childWindowCreated = new Promise<void>((resolve) => { app.once('browser-window-created', (event, window) => { childWindow = window; window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); resolve(); }); }); parentWindow.loadURL(`${serverUrl}/first-window-open`); await childWindowCreated; childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); parentWindow.close(); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed'); }); it('emits current-render-view-deleted if the current RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; w.webContents.on('current-render-view-deleted' as any, () => { currentRenderViewDeletedEmitted = true; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted'); }); it('emits render-view-deleted if any RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let rvhDeletedCount = 0; w.webContents.on('render-view-deleted' as any, () => { rvhDeletedCount++; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; const expectedRenderViewDeletedEventCount = 1; expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times'); }); }); describe('setIgnoreMenuShortcuts(ignore)', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.setIgnoreMenuShortcuts(true); w.webContents.setIgnoreMenuShortcuts(false); }).to.not.throw(); }); }); const crashPrefs = [ { nodeIntegration: true }, { sandbox: true } ]; const nicePrefs = (o: any) => { let s = ''; for (const key of Object.keys(o)) { s += `${key}=${o[key]}, `; } return `(${s.slice(0, s.length - 2)})`; }; for (const prefs of crashPrefs) { describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('isCrashed() is false by default', () => { expect(w.webContents.isCrashed()).to.equal(false); }); it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => { expect(w.webContents.isCrashed()).to.equal(false); const crashEvent = once(w.webContents, 'render-process-gone') as Promise<[any, Electron.RenderProcessGoneDetails]>; w.webContents.forcefullyCrashRenderer(); const [, details] = await crashEvent; expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed'); expect(w.webContents.isCrashed()).to.equal(true); }); it('a crashed process is recoverable with reload()', async () => { expect(w.webContents.isCrashed()).to.equal(false); w.webContents.forcefullyCrashRenderer(); w.webContents.reload(); expect(w.webContents.isCrashed()).to.equal(false); }); }); } // Destroying webContents in its event listener is going to crash when // Electron is built in Debug mode. describe('destroy()', () => { let server: http.Server; let serverUrl: string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/200': response.end(); break; default: done(new Error('unsupported endpoint')); } }); listen(server).then(({ url }) => { serverUrl = url; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', url: '/200' }, { name: 'dom-ready', url: '/200' }, { name: 'did-stop-loading', url: '/200' }, { name: 'did-finish-load', url: '/200' }, // FIXME: Multiple Emit calls inside an observer assume that object // will be alive till end of the observer. Synchronous `destroy` api // violates this contract and crashes. { name: 'did-frame-finish-load', url: '/200' }, { name: 'did-fail-load', url: '/net-error' } ]; for (const e of events) { it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () { // This test is flaky on Windows CI and we don't know why, but the // purpose of this test is to make sure Electron does not crash so it // is fine to retry this test for a few times. this.retries(3); const contents = (webContents as typeof ElectronInternal.WebContents).create(); const originalEmit = contents.emit.bind(contents); contents.emit = (...args) => { return originalEmit(...args); }; contents.once(e.name as any, () => contents.destroy()); const destroyed = once(contents, 'destroyed'); contents.loadURL(serverUrl + e.url); await destroyed; }); } }); describe('did-change-theme-color event', () => { afterEach(closeAllWindows); it('is triggered with correct theme color', (done) => { const w = new BrowserWindow({ show: true }); let count = 0; w.webContents.on('did-change-theme-color', (e, color) => { try { if (count === 0) { count += 1; expect(color).to.equal('#FFEEDD'); w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); } else if (count === 1) { expect(color).to.be.null(); done(); } } catch (e) { done(e); } }); w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html')); }); }); describe('console-message event', () => { afterEach(closeAllWindows); it('is triggered with correct log message', (done) => { const w = new BrowserWindow({ show: true }); w.webContents.on('console-message', (e, level, message) => { // Don't just assert as Chromium might emit other logs that we should ignore. if (message === 'a') { done(); } }); w.loadFile(path.join(fixturesPath, 'pages', 'a.html')); }); }); describe('ipc-message event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends an asynchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); w.webContents.executeJavaScript(` require('electron').ipcRenderer.send('message', 'Hello World!') `); const [, channel, message] = await once(w.webContents, 'ipc-message'); expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); }); }); describe('ipc-message-sync event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends a synchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); const promise: Promise<[string, string]> = new Promise(resolve => { w.webContents.once('ipc-message-sync', (event, channel, arg) => { event.returnValue = 'foobar'; resolve([channel, arg]); }); }); const result = await w.webContents.executeJavaScript(` require('electron').ipcRenderer.sendSync('message', 'Hello World!') `); const [channel, message] = await promise; expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); expect(result).to.equal('foobar'); }); }); describe('referrer', () => { afterEach(closeAllWindows); it('propagates referrer information to new target=_blank windows', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } finally { server.close(); } } res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>'); }); listen(server).then(({ url }) => { w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url + '/'); expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin'); return { action: 'allow' }; }); w.webContents.executeJavaScript('a.click()'); }); w.loadURL(url); }); }); it('propagates referrer information to windows opened with window.open', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } } res.end(''); }); listen(server).then(({ url }) => { w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url + '/'); expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin'); return { action: 'allow' }; }); w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")'); }); w.loadURL(url); }); }); }); describe('webframe messages in sandboxed contents', () => { afterEach(closeAllWindows); it('responds to executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const result = await w.webContents.executeJavaScript('37 + 5'); expect(result).to.equal(42); }); }); describe('preload-error event', () => { afterEach(closeAllWindows); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('is triggered when unhandled exception is thrown', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>; w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('Hello World!'); }); it('is triggered on syntax errors', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>; w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('foobar is not defined'); }); it('is triggered when preload script loading fails', async () => { const preload = path.join(fixturesPath, 'module', 'preload-invalid.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>; w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.contain('preload-invalid.js'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('takeHeapSnapshot()', () => { afterEach(closeAllWindows); it('works with sandboxed renderers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); const cleanup = () => { try { fs.unlinkSync(filePath); } catch { // ignore error } }; try { await w.webContents.takeHeapSnapshot(filePath); const stats = fs.statSync(filePath); expect(stats.size).not.to.be.equal(0); } finally { cleanup(); } }); it('fails with invalid file path', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const badPath = path.join('i', 'am', 'a', 'super', 'bad', 'path'); const promise = w.webContents.takeHeapSnapshot(badPath); return expect(promise).to.be.eventually.rejectedWith(Error, `Failed to take heap snapshot with invalid file path ${badPath}`); }); it('fails with invalid render process', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); w.webContents.destroy(); const promise = w.webContents.takeHeapSnapshot(filePath); return expect(promise).to.be.eventually.rejectedWith(Error, 'Failed to take heap snapshot with nonexistent render frame'); }); }); describe('setBackgroundThrottling()', () => { afterEach(closeAllWindows); it('does not crash when allowing', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(true); }); it('does not crash when called via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); w.setBackgroundThrottling(true); }); it('does not crash when disallowing', () => { const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } }); w.webContents.setBackgroundThrottling(false); }); }); describe('getBackgroundThrottling()', () => { afterEach(closeAllWindows); it('works via getter', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); expect(w.webContents.getBackgroundThrottling()).to.equal(false); w.webContents.setBackgroundThrottling(true); expect(w.webContents.getBackgroundThrottling()).to.equal(true); }); it('works via property', () => { const w = new BrowserWindow({ show: false }); w.webContents.backgroundThrottling = false; expect(w.webContents.backgroundThrottling).to.equal(false); w.webContents.backgroundThrottling = true; expect(w.webContents.backgroundThrottling).to.equal(true); }); it('works via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); w.setBackgroundThrottling(false); expect(w.getBackgroundThrottling()).to.equal(false); w.setBackgroundThrottling(true); expect(w.getBackgroundThrottling()).to.equal(true); }); }); ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = await w.webContents.getPrintersAsync(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('printToPDF()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); afterEach(closeAllWindows); it('rejects on incorrectly typed parameters', async () => { const badTypes = { landscape: [], displayHeaderFooter: '123', printBackground: 2, scale: 'not-a-number', pageSize: 'IAmAPageSize', margins: 'terrible', pageRanges: { oops: 'im-not-the-right-key' }, headerTemplate: [1, 2, 3], footerTemplate: [4, 5, 6], preferCSSPageSize: 'no', generateTaggedPDF: 'wtf', generateDocumentOutline: [7, 8, 9] }; await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); // These will hard crash in Chromium unless we type-check for (const [key, value] of Object.entries(badTypes)) { const param = { [key]: value }; await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected(); } }); it('rejects when margins exceed physical page size', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); await expect(w.webContents.printToPDF({ pageSize: 'Letter', margins: { top: 100, bottom: 100, left: 5, right: 5 } })).to.eventually.be.rejectedWith('margins must be less than or equal to pageSize'); }); it('does not crash when called multiple times in parallel', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); const promises = []; for (let i = 0; i < 3; i++) { promises.push(w.webContents.printToPDF({})); } const results = await Promise.all(promises); for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); it('does not crash when called multiple times in sequence', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); const results = []; for (let i = 0; i < 3; i++) { const result = await w.webContents.printToPDF({}); results.push(result); } for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); it('can print a PDF with default settings', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); const data = await w.webContents.printToPDF({}); expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); }); type PageSizeString = Exclude<Required<Electron.PrintToPDFOptions>['pageSize'], Electron.Size>; it('with custom page sizes', async () => { const paperFormats: Record<PageSizeString, ElectronInternal.PageSize> = { Letter: { width: 8.5, height: 11 }, Legal: { width: 8.5, height: 14 }, Tabloid: { width: 11, height: 17 }, Ledger: { width: 17, height: 11 }, A0: { width: 33.1, height: 46.8 }, A1: { width: 23.4, height: 33.1 }, A2: { width: 16.54, height: 23.4 }, A3: { width: 11.7, height: 16.54 }, A4: { width: 8.27, height: 11.7 }, A5: { width: 5.83, height: 8.27 }, A6: { width: 4.13, height: 5.83 } }; await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); for (const format of Object.keys(paperFormats) as PageSizeString[]) { const data = await w.webContents.printToPDF({ pageSize: format }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); // page.view is [top, left, width, height]. const width = page.view[2] / 72; const height = page.view[3] / 72; const approxEq = (a: number, b: number, epsilon = 0.01) => Math.abs(a - b) <= epsilon; expect(approxEq(width, paperFormats[format].width)).to.be.true(); expect(approxEq(height, paperFormats[format].height)).to.be.true(); } }); it('with custom header and footer', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ displayHeaderFooter: true, headerTemplate: '<div>I\'m a PDF header</div>', footerTemplate: '<div>I\'m a PDF footer</div>' }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); const { items } = await page.getTextContent(); // Check that generated PDF contains a header. const containsText = (text: RegExp) => items.some(({ str }: { str: string }) => str.match(text)); expect(containsText(/I'm a PDF header/)).to.be.true(); expect(containsText(/I'm a PDF footer/)).to.be.true(); }); it('in landscape mode', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ landscape: true }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); // page.view is [top, left, width, height]. const width = page.view[2]; const height = page.view[3]; expect(width).to.be.greaterThan(height); }); it('with custom page ranges', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-large.html')); const data = await w.webContents.printToPDF({ pageRanges: '1-3', landscape: true }); const doc = await pdfjs.getDocument(data).promise; // Check that correct # of pages are rendered. expect(doc.numPages).to.equal(3); }); it('does not tag PDFs by default', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({}); const doc = await pdfjs.getDocument(data).promise; const markInfo = await doc.getMarkInfo(); expect(markInfo).to.be.null(); }); it('can generate tag data for PDFs', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ generateTaggedPDF: true }); const doc = await pdfjs.getDocument(data).promise; const markInfo = await doc.getMarkInfo(); expect(markInfo).to.deep.equal({ Marked: true, UserProperties: false, Suspects: false }); }); }); describe('PictureInPicture video', () => { afterEach(closeAllWindows); it('works as expected', async function () { const w = new BrowserWindow({ webPreferences: { sandbox: true } }); // TODO(codebytere): figure out why this workaround is needed and remove. // It is not germane to the actual test. await w.loadFile(path.join(fixturesPath, 'blank.html')); await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html')); await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')', true); const result = await w.webContents.executeJavaScript('runTest(true)', true); expect(result).to.be.true(); }); }); describe('Shared Workers', () => { afterEach(closeAllWindows); it('can get multiple shared workers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = once(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); expect(sharedWorkers).to.have.lengthOf(2); expect(sharedWorkers[0].url).to.contain('shared-worker'); expect(sharedWorkers[1].url).to.contain('shared-worker'); }); it('can inspect a specific shared worker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = once(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.inspectSharedWorkerById(sharedWorkers[0].id); await devtoolsOpened; const devtoolsClosed = once(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devtoolsClosed; }); }); describe('login event', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; let serverPort: number; let proxyServer: http.Server; let proxyServerPort: number; before(async () => { server = http.createServer((request, response) => { if (request.url === '/no-auth') { return response.end('ok'); } if (request.headers.authorization) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers.authorization); } response .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }) .end('401'); }); ({ port: serverPort, url: serverUrl } = await listen(server)); }); before(async () => { proxyServer = http.createServer((request, response) => { if (request.headers['proxy-authorization']) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers['proxy-authorization']); } response .writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }) .end(); }); proxyServerPort = (await listen(proxyServer)).port; }); afterEach(async () => { await session.defaultSession.clearAuthCache(); }); after(() => { server.close(); proxyServer.close(); }); it('is emitted when navigating', async () => { const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(serverUrl + '/'); expect(eventAuthInfo.isProxy).to.be.false(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(serverPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('is emitted when a proxy requests authorization', async () => { const customSession = session.fromPartition(`${Math.random()}`); await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' }); const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(`${serverUrl}/no-auth`); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`); expect(eventAuthInfo.isProxy).to.be.true(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(proxyServerPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('cancels authentication when callback is called with no arguments', async () => { const w = new BrowserWindow({ show: false }); w.webContents.on('login', (event, request, authInfo, cb) => { event.preventDefault(); cb(); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal('401'); }); }); describe('page-title-updated event', () => { afterEach(closeAllWindows); it('is emitted with a full title for pages with no navigation', async () => { const bw = new BrowserWindow({ show: false }); await bw.loadURL('about:blank'); bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null'); const [, child] = await once(app, 'web-contents-created') as [any, WebContents]; bw.webContents.executeJavaScript('child.document.title = "new title"'); const [, title] = await once(child, 'page-title-updated') as [any, string]; expect(title).to.equal('new title'); }); }); describe('context-menu event', () => { afterEach(closeAllWindows); it('emits when right-clicked in page', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const promise = once(w.webContents, 'context-menu') as Promise<[any, Electron.ContextMenuParams]>; // Simulate right-click to create context-menu event. const opts = { x: 0, y: 0, button: 'right' as const }; w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' }); w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' }); const [, params] = await promise; expect(params.pageURL).to.equal(w.webContents.getURL()); expect(params.frame).to.be.an('object'); expect(params.x).to.be.a('number'); expect(params.y).to.be.a('number'); }); }); describe('close() method', () => { afterEach(closeAllWindows); it('closes when close() is called', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('closes when close() is called after loading a page', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('can be GCed before loading a page', async () => { const v8Util = process._linkedBinding('electron_common_v8_util'); let registry: FinalizationRegistry<unknown> | null = null; const cleanedUp = new Promise<number>(resolve => { registry = new FinalizationRegistry(resolve as any); }); (() => { const w = (webContents as typeof ElectronInternal.WebContents).create(); registry!.register(w, 42); })(); const i = setInterval(() => v8Util.requestGarbageCollectionForTesting(), 100); defer(() => clearInterval(i)); expect(await cleanedUp).to.equal(42); }); it('causes its parent browserwindow to be closed', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const closed = once(w, 'closed'); w.webContents.close(); await closed; expect(w.isDestroyed()).to.be.true(); }); it('ignores beforeunload if waitForBeforeUnload not specified', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.on('will-prevent-unload', () => { throw new Error('unexpected will-prevent-unload'); }); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('runs beforeunload if waitForBeforeUnload is specified', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); const willPreventUnload = once(w, 'will-prevent-unload'); w.close({ waitForBeforeUnload: true }); await willPreventUnload; expect(w.isDestroyed()).to.be.false(); }); it('overriding beforeunload prevention results in webcontents close', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.once('will-prevent-unload', e => e.preventDefault()); const destroyed = once(w, 'destroyed'); w.close({ waitForBeforeUnload: true }); await destroyed; expect(w.isDestroyed()).to.be.true(); }); }); describe('content-bounds-updated event', () => { afterEach(closeAllWindows); it('emits when moveTo is called', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.moveTo(100, 100)', true); const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle]; const { width, height } = w.getBounds(); expect(rect).to.deep.equal({ x: 100, y: 100, width, height }); await new Promise(setImmediate); expect(w.getBounds().x).to.equal(100); expect(w.getBounds().y).to.equal(100); }); it('emits when resizeTo is called', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.resizeTo(100, 100)', true); const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle]; const { x, y } = w.getBounds(); expect(rect).to.deep.equal({ x, y, width: 100, height: 100 }); await new Promise(setImmediate); expect({ width: w.getBounds().width, height: w.getBounds().height }).to.deep.equal(process.platform === 'win32' ? { // The width is reported as being larger on Windows? I'm not sure why // this is. width: 136, height: 100 } : { width: 100, height: 100 }); }); it('does not change window bounds if cancelled', async () => { const w = new BrowserWindow({ show: false }); const { width, height } = w.getBounds(); w.loadURL('about:blank'); w.webContents.once('content-bounds-updated', e => e.preventDefault()); await w.webContents.executeJavaScript('window.resizeTo(100, 100)', true); await new Promise(setImmediate); expect(w.getBounds().width).to.equal(width); expect(w.getBounds().height).to.equal(height); }); }); });
closed
electron/electron
https://github.com/electron/electron
41,008
[Bug]: `original-fs` does not provide unmodified methods
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 28.1.3 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior `original-fs` should provide unmodified methods from Node.js' `fs` module ### Actual Behavior `original-fs` seems to be using our ASAR patches that are meant to be applied only when importing the plain `fs` module in Electron ### Testcase Gist URL https://gist.github.com/3f029d290d598c9e1d1322c25c48c575 ### Additional Information The Fiddle above is just a slight variation of the repro provided by @tangjfn in #40943 / #40960 (thanks for the test case!), where you can enter a path to a folder containing an `.asar` file and attempt to remove it using `fs.promises.rm` or `fs.promises.rmdir`. They both fail with `ENOTEMPTY: directory not empty`: ![image](https://github.com/electron/electron/assets/19478575/e7555a0f-7fa2-43b6-ac43-d00b94f191e1)
https://github.com/electron/electron/issues/41008
https://github.com/electron/electron/pull/41209
fb888a6989dacfd6be3fe1a2b1cfffd0de81246a
5dfa9e33172d994c2f2a98a00312134cbc703d6b
2024-01-16T15:52:39Z
c++
2024-02-05T08:51:04Z
patches/node/build_add_gn_build_files.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Jeremy Apthorp <[email protected]> Date: Tue, 26 Feb 2019 17:07:45 -0800 Subject: build: add GN build files This adds GN build files for Node, so we don't have to build with GYP. Note that there always GN files in upstream Node in 20/21 branches, however those files were cherry-picked from main branch and do not really in 20/21. We have to wait until 22 is released to be able to build with upstream GN files. diff --git a/BUILD.gn b/BUILD.gn index 1ed186b597eece7c34cb69c8e1e20870555a040d..541e7d2b8ee05677b64a3ea39c1422560fd5df75 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -1,14 +1,404 @@ -############################################################################## -# # -# DO NOT EDIT THIS FILE! # -# # -############################################################################## +import("//v8/gni/v8.gni") +import("//electron/js2c_toolchain.gni") +import("electron_node.gni") -# This file is used by GN for building, which is NOT the build system used for -# building official binaries. -# Please modify the gyp files if you are making changes to build system. +declare_args() { + # Enable the V8 inspector protocol for use with node. + node_enable_inspector = true -import("unofficial.gni") + # Build node with SSL support. + # The variable is called "openssl" for parity with node's GYP build. + node_use_openssl = true -node_gn_build("node") { + # Use the specified path to system CA (PEM format) in addition to + # the BoringSSL supplied CA store or compiled-in Mozilla CA copy. + node_openssl_system_ca_path = "" + + # Initialize v8 platform during node.js startup. + # NB. this must be turned off in Electron, because Electron initializes the + # v8 platform itself. + node_use_v8_platform = false + + # Build with DTrace support. + node_use_dtrace = false + + # Build with ETW support. + node_use_etw = false + + # Build JavaScript in lib/ with DCHECK macros. + node_debug_lib = false + + # Custom build tag. + node_tag = "" + + # V8 options to pass, see `node --v8-options` for examples + node_v8_options = "" + + # Provide a custom URL prefix for the `process.release` properties + # `sourceUrl` and `headersUrl`. When compiling a release build, this will + # default to https://nodejs.org/download/release/') + node_release_urlbase = "" + + # Allows downstream packagers (eg. Linux distributions) to build Electron against system shared libraries. + use_system_cares = false + use_system_nghttp2 = false + use_system_llhttp = false + use_system_histogram = false +} + +if (is_linux) { + import("//build/config/linux/pkg_config.gni") + if (use_system_cares) { + pkg_config("cares") { + packages = [ "libcares" ] + } + } + if (use_system_nghttp2) { + pkg_config("nghttp2") { + packages = [ "libnghttp2" ] + } + } +} + +assert(!node_use_dtrace, "node_use_dtrace not supported in GN") +assert(!node_use_etw, "node_use_etw not supported in GN") + +assert(!node_enable_inspector || node_use_openssl, + "node_enable_inspector requires node_use_openssl") + +config("node_internals") { + defines = [ "NODE_WANT_INTERNALS=1" ] +} + +node_files = read_file("filenames.json", "json") +library_files = node_files.library_files +fs_files = node_files.fs_files +original_fs_files = [] +foreach(file, fs_files) { + original_fs_files += [string_replace(string_replace(file, "internal/fs/", "internal/original-fs/"), "lib/fs.js", "lib/original-fs.js")] +} + +copy("node_js2c_inputs") { + sources = library_files + outputs = [ + "$target_gen_dir/js2c_inputs/{{source_target_relative}}", + ] +} + +action("node_js2c_original_fs") { + script = "tools/generate_original_fs.py" + inputs = fs_files + outputs = [] + foreach(file, fs_files + original_fs_files) { + outputs += ["$target_gen_dir/js2c_inputs/$file"] + } + + args = [rebase_path("$target_gen_dir/js2c_inputs")] + fs_files +} + +action("node_js2c_exec") { + deps = [ + "//electron:generate_config_gypi", + ":node_js2c_original_fs", + ":node_js2c_inputs", + ":node_js2c($electron_js2c_toolchain)" + ] + config_gypi = [ "$root_gen_dir/config.gypi" ] + inputs = library_files + get_target_outputs(":node_js2c_original_fs") + config_gypi + outputs = [ + "$target_gen_dir/node_javascript.cc", + ] + + script = "//electron/build/run-in-dir.py" + out_dir = get_label_info(":anything($electron_js2c_toolchain)", "root_out_dir") + args = [ rebase_path("$target_gen_dir/js2c_inputs"), rebase_path("$out_dir/node_js2c") ] + + rebase_path(outputs) + library_files + fs_files + original_fs_files + rebase_path(config_gypi) +} + +config("node_features") { + defines = [] + if (node_enable_inspector) { + defines += [ "HAVE_INSPECTOR=1" ] + } else { + defines += [ "HAVE_INSPECTOR=0" ] + } + if (node_use_openssl) { + defines += [ "HAVE_OPENSSL=1" ] + } else { + defines += [ "HAVE_OPENSSL=0" ] + } + if (v8_enable_i18n_support) { + defines += [ "NODE_HAVE_I18N_SUPPORT=1" ] + } else { + defines += [ "NODE_HAVE_I18N_SUPPORT=0" ] + } + if (node_use_v8_platform) { + defines += [ "NODE_USE_V8_PLATFORM=1" ] + } else { + defines += [ "NODE_USE_V8_PLATFORM=0" ] + } +} + +config("node_lib_config") { + include_dirs = [ "src" ] + + cflags = [ + "-Wno-shadow", + # FIXME(deepak1556): include paths should be corrected, + # refer https://docs.google.com/presentation/d/1oxNHaVjA9Gn_rTzX6HIpJHP7nXRua_0URXxxJ3oYRq0/edit#slide=id.g71ecd450e_2_702 + "-Wno-microsoft-include", + ] + + configs = [ ":node_features" ] + + if (is_debug) { + defines = [ "DEBUG" ] + } +} + +config("node_internal_config") { + visibility = [ + ":*", + "src/inspector:*", + ] + defines = [ + "NODE_WANT_INTERNALS=1", + "NODE_IMPLEMENTATION", + ] + if (node_module_version != "") { + defines += [ "NODE_EMBEDDER_MODULE_VERSION=" + node_module_version ] + } + if (is_component_build) { + defines += [ + "NODE_SHARED_MODE", + ] + } + + if (target_cpu == "x86") { + node_arch = "ia32" + } else { + node_arch = target_cpu + } + defines += [ "NODE_ARCH=\"$node_arch\"" ] + + if (target_os == "win") { + node_platform = "win32" + } else if (target_os == "mac") { + node_platform = "darwin" + } else { + node_platform = target_os + } + defines += [ "NODE_PLATFORM=\"$node_platform\"" ] + + if (is_win) { + defines += [ + "NOMINMAX", + "_UNICODE=1", + ] + } else { + defines += [ "__POSIX__" ] + } + + if (node_tag != "") { + defines += [ "NODE_TAG=\"$node_tag\"" ] + } + if (node_v8_options != "") { + defines += [ "NODE_V8_OPTIONS=\"$node_v8_options\"" ] + } + if (node_release_urlbase != "") { + defines += [ "NODE_RELEASE_URLBASE=\"$node_release_urlbase\"" ] + } + + if (node_use_openssl) { + defines += [ + "NODE_OPENSSL_SYSTEM_CERT_PATH=\"$node_openssl_system_ca_path\"", + "EVP_CTRL_CCM_SET_TAG=EVP_CTRL_GCM_SET_TAG", + ] + } +} + +executable("overlapped-checker") { + sources = [] + if (is_win) { + sources += [ "test/overlapped-checker/main_win.c" ] + } else { + sources += [ "test/overlapped-checker/main_unix.c" ] + } +} + +if (current_toolchain == electron_js2c_toolchain) { + executable("node_js2c") { + defines = [] + sources = [ + "tools/js2c.cc", + "tools/executable_wrapper.h" + ] + include_dirs = [ "tools" ] + deps = [ + "deps/simdutf($electron_js2c_toolchain)", + "deps/uv($electron_js2c_toolchain)", + "//v8" + ] + + if (!is_win) { + defines += [ "NODE_JS2C_USE_STRING_LITERALS" ] + } + if (is_debug) { + cflags_cc = [ "-g", "-O0" ] + defines += [ "DEBUG" ] + } + } +} + +component("node_lib") { + deps = [ + ":node_js2c_exec", + "deps/googletest:gtest", + "deps/ada", + "deps/base64", + "deps/simdutf", + "deps/uvwasi", + "//third_party/zlib", + "//third_party/brotli:dec", + "//third_party/brotli:enc", + "//v8:v8_libplatform", + ] + if (use_system_cares) { + configs += [ ":cares" ] + } else { + deps += [ "deps/cares" ] + } + if (use_system_nghttp2) { + configs += [ ":nghttp2" ] + } else { + deps += [ "deps/nghttp2" ] + } + public_deps = [ + "deps/uv", + "//electron:electron_js2c", + "//v8", + ] + configs += [ ":node_internal_config" ] + public_configs = [ ":node_lib_config" ] + include_dirs = [ + "src", + "deps/postject" + ] + libs = [] + if (use_system_llhttp) { + libs += [ "llhttp" ] + } else { + deps += [ "deps/llhttp" ] + } + if (use_system_histogram) { + libs += [ "hdr_histogram" ] + include_dirs += [ "/usr/include/hdr" ] + } else { + deps += [ "deps/histogram" ] + } + frameworks = [] + cflags_cc = [ + "-Wno-deprecated-declarations", + "-Wno-implicit-fallthrough", + "-Wno-return-type", + "-Wno-sometimes-uninitialized", + "-Wno-string-plus-int", + "-Wno-unused-function", + "-Wno-unused-label", + "-Wno-unused-private-field", + "-Wno-unused-variable", + ] + + if (v8_enable_i18n_support) { + deps += [ "//third_party/icu" ] + } + + sources = node_files.node_sources + sources += [ + "$root_gen_dir/electron_natives.cc", + "$target_gen_dir/node_javascript.cc", + "src/node_snapshot_stub.cc", + ] + + if (is_win) { + libs += [ "psapi.lib" ] + } + if (is_mac) { + frameworks += [ "CoreFoundation.framework" ] + } + + if (node_enable_inspector) { + sources += [ + "src/inspector_agent.cc", + "src/inspector_agent.h", + "src/inspector_io.cc", + "src/inspector_io.h", + "src/inspector_js_api.cc", + "src/inspector_profiler.cc", + "src/inspector_socket.cc", + "src/inspector_socket.h", + "src/inspector_socket_server.cc", + "src/inspector_socket_server.h", + ] + deps += [ "src/inspector" ] + } + + if (node_use_openssl) { + deps += [ "//third_party/boringssl" ] + sources += [ + "src/crypto/crypto_aes.cc", + "src/crypto/crypto_aes.h", + "src/crypto/crypto_bio.cc", + "src/crypto/crypto_bio.h", + "src/crypto/crypto_cipher.cc", + "src/crypto/crypto_cipher.h", + "src/crypto/crypto_clienthello-inl.h", + "src/crypto/crypto_clienthello.cc", + "src/crypto/crypto_clienthello.h", + "src/crypto/crypto_common.cc", + "src/crypto/crypto_common.h", + "src/crypto/crypto_context.cc", + "src/crypto/crypto_context.h", + "src/crypto/crypto_dh.cc", + "src/crypto/crypto_dh.h", + "src/crypto/crypto_dsa.cc", + "src/crypto/crypto_dsa.h", + "src/crypto/crypto_ec.cc", + "src/crypto/crypto_ec.h", + "src/crypto/crypto_groups.h", + "src/crypto/crypto_hash.cc", + "src/crypto/crypto_hash.h", + "src/crypto/crypto_hkdf.cc", + "src/crypto/crypto_hkdf.h", + "src/crypto/crypto_hmac.cc", + "src/crypto/crypto_hmac.h", + "src/crypto/crypto_keygen.cc", + "src/crypto/crypto_keygen.h", + "src/crypto/crypto_keys.cc", + "src/crypto/crypto_keys.h", + "src/crypto/crypto_pbkdf2.cc", + "src/crypto/crypto_pbkdf2.h", + "src/crypto/crypto_random.cc", + "src/crypto/crypto_random.h", + "src/crypto/crypto_rsa.cc", + "src/crypto/crypto_rsa.h", + "src/crypto/crypto_scrypt.cc", + "src/crypto/crypto_scrypt.h", + "src/crypto/crypto_sig.cc", + "src/crypto/crypto_sig.h", + "src/crypto/crypto_spkac.cc", + "src/crypto/crypto_spkac.h", + "src/crypto/crypto_timing.cc", + "src/crypto/crypto_timing.h", + "src/crypto/crypto_tls.cc", + "src/crypto/crypto_tls.h", + "src/crypto/crypto_util.cc", + "src/crypto/crypto_util.h", + "src/crypto/crypto_x509.cc", + "src/crypto/crypto_x509.h", + "src/node_crypto.cc", + "src/node_crypto.h", + ] + cflags_cc += [ "-Wno-sign-compare" ] + } } diff --git a/deps/ada/BUILD.gn b/deps/ada/BUILD.gn index e92ac3a3beac143dced2efb05304ed8ba832b067..1ce69e9deba1a9b191e8d95f4c82e0ec1f7b50ca 100644 --- a/deps/ada/BUILD.gn +++ b/deps/ada/BUILD.gn @@ -1,14 +1,12 @@ -############################################################################## -# # -# DO NOT EDIT THIS FILE! # -# # -############################################################################## +import("//v8/gni/v8.gni") -# This file is used by GN for building, which is NOT the build system used for -# building official binaries. -# Please modify the gyp files if you are making changes to build system. +config("ada_config") { + include_dirs = [ "." ] +} -import("unofficial.gni") +static_library("ada") { + include_dirs = [ "." ] + sources = [ "ada.cpp" ] -ada_gn_build("ada") { + public_configs = [ ":ada_config" ] } diff --git a/deps/base64/unofficial.gni b/deps/base64/unofficial.gni index 269c62d976d6adea6d020568094e23e9b0a9dc7c..14ffff0b4badb7ad71f2b6df43ad2eb300fc55ed 100644 --- a/deps/base64/unofficial.gni +++ b/deps/base64/unofficial.gni @@ -18,6 +18,10 @@ template("base64_gn_build") { } } + # FIXME(zcbenz): ASM on win/x86 compiles perfectly in upstream Node, figure + # out why it does not work in Electron's build configs. + support_x86_asm = target_cpu == "x64" || (target_cpu == "x86" && !is_win) + config("base64_internal_config") { include_dirs = [ "base64/lib" ] if (is_component_build) { @@ -25,7 +29,7 @@ template("base64_gn_build") { } else { defines = [] } - if (target_cpu == "x86" || target_cpu == "x64") { + if (support_x86_asm) { defines += [ "HAVE_SSSE3=1", "HAVE_SSE41=1", @@ -75,7 +79,7 @@ template("base64_gn_build") { source_set("base64_ssse3") { configs += [ ":base64_internal_config" ] sources = [ "base64/lib/arch/ssse3/codec.c" ] - if (target_cpu == "x86" || target_cpu == "x64") { + if (support_x86_asm) { if (is_clang || !is_win) { cflags_c = [ "-mssse3" ] } @@ -85,7 +89,7 @@ template("base64_gn_build") { source_set("base64_sse41") { configs += [ ":base64_internal_config" ] sources = [ "base64/lib/arch/sse41/codec.c" ] - if (target_cpu == "x86" || target_cpu == "x64") { + if (support_x86_asm) { if (is_clang || !is_win) { cflags_c = [ "-msse4.1" ] } @@ -95,7 +99,7 @@ template("base64_gn_build") { source_set("base64_sse42") { configs += [ ":base64_internal_config" ] sources = [ "base64/lib/arch/sse42/codec.c" ] - if (target_cpu == "x86" || target_cpu == "x64") { + if (support_x86_asm) { if (is_clang || !is_win) { cflags_c = [ "-msse4.2" ] } @@ -105,7 +109,7 @@ template("base64_gn_build") { source_set("base64_avx") { configs += [ ":base64_internal_config" ] sources = [ "base64/lib/arch/avx/codec.c" ] - if (target_cpu == "x86" || target_cpu == "x64") { + if (support_x86_asm) { if (is_clang || !is_win) { cflags_c = [ "-mavx" ] } else if (is_win) { @@ -117,7 +121,7 @@ template("base64_gn_build") { source_set("base64_avx2") { configs += [ ":base64_internal_config" ] sources = [ "base64/lib/arch/avx2/codec.c" ] - if (target_cpu == "x86" || target_cpu == "x64") { + if (support_x86_asm) { if (is_clang || !is_win) { cflags_c = [ "-mavx2" ] } else if (is_win) { @@ -129,7 +133,7 @@ template("base64_gn_build") { source_set("base64_avx512") { configs += [ ":base64_internal_config" ] sources = [ "base64/lib/arch/avx512/codec.c" ] - if (target_cpu == "x86" || target_cpu == "x64") { + if (support_x86_asm) { if (is_clang || !is_win) { cflags_c = [ "-mavx512vl", diff --git a/deps/cares/BUILD.gn b/deps/cares/BUILD.gn index ac19ac73ed1e24c61cb679f3851685b79cfc8b39..fb1b3138cdb674205afa0ffe078270585843eca3 100644 --- a/deps/cares/BUILD.gn +++ b/deps/cares/BUILD.gn @@ -1,14 +1,143 @@ -############################################################################## -# # -# DO NOT EDIT THIS FILE! # -# # -############################################################################## +config("cares_config") { + include_dirs = [ "include", "src/lib" ] +} +static_library("cares") { + defines = [ "CARES_STATICLIB" ] + include_dirs = [ "include" ] + public_configs = [ ":cares_config" ] + + libs = [] + cflags_c = [ + "-Wno-logical-not-parentheses", + "-Wno-implicit-fallthrough", + "-Wno-sign-compare", + ] + + sources = [ + "include/ares.h", + "include/ares_dns.h", + "include/ares_nameser.h", + "include/ares_rules.h", + "include/ares_version.h", + "src/lib/ares__addrinfo2hostent.c", + "src/lib/ares__addrinfo_localhost.c", + "src/lib/ares_android.c", + "src/lib/ares__buf.c", + "src/lib/ares__buf.h", + "src/lib/ares__close_sockets.c", + "src/lib/ares__htable.c", + "src/lib/ares__htable.h", + "src/lib/ares__htable_asvp.c", + "src/lib/ares__htable_asvp.h", + "src/lib/ares__htable_stvp.c", + "src/lib/ares__htable_stvp.h", + "src/lib/ares__llist.c", + "src/lib/ares__llist.h", + "src/lib/ares__get_hostent.c", + "src/lib/ares__parse_into_addrinfo.c", + "src/lib/ares__read_line.c", + "src/lib/ares__readaddrinfo.c", + "src/lib/ares__slist.c", + "src/lib/ares__slist.h", + "src/lib/ares__sortaddrinfo.c", + "src/lib/ares__timeval.c", + "src/lib/ares_cancel.c", + "src/lib/ares_create_query.c", + "src/lib/ares_data.c", + "src/lib/ares_data.h", + "src/lib/ares_destroy.c", + "src/lib/ares_expand_name.c", + "src/lib/ares_expand_string.c", + "src/lib/ares_fds.c", + "src/lib/ares_free_hostent.c", + "src/lib/ares_free_string.c", + "src/lib/ares_freeaddrinfo.c", + "src/lib/ares_getaddrinfo.c", + "src/lib/ares_getenv.h", + "src/lib/ares_gethostbyaddr.c", + "src/lib/ares_gethostbyname.c", + "src/lib/ares_getnameinfo.c", + "src/lib/ares_getsock.c", + "src/lib/ares_inet_net_pton.h", + "src/lib/ares_init.c", + "src/lib/ares_ipv6.h", + "src/lib/ares_library_init.c", + "src/lib/ares_library_init.h", + "src/lib/ares_mkquery.c", + "src/lib/ares_nameser.h", + "src/lib/ares_nowarn.c", + "src/lib/ares_nowarn.h", + "src/lib/ares_options.c", + "src/lib/ares_parse_aaaa_reply.c", + "src/lib/ares_parse_a_reply.c", + "src/lib/ares_parse_caa_reply.c", + "src/lib/ares_parse_mx_reply.c", + "src/lib/ares_parse_naptr_reply.c", + "src/lib/ares_parse_ns_reply.c", + "src/lib/ares_parse_ptr_reply.c", + "src/lib/ares_parse_soa_reply.c", + "src/lib/ares_parse_srv_reply.c", + "src/lib/ares_parse_txt_reply.c", + "src/lib/ares_parse_uri_reply.c", + "src/lib/ares_platform.h", + "src/lib/ares_private.h", + "src/lib/ares_process.c", + "src/lib/ares_query.c", + "src/lib/ares_rand.c", + "src/lib/ares_search.c", + "src/lib/ares_send.c", + "src/lib/ares_setup.h", + "src/lib/ares_strcasecmp.c", + "src/lib/ares_strcasecmp.h", + "src/lib/ares_strdup.c", + "src/lib/ares_strdup.h", + "src/lib/ares_strerror.c", + "src/lib/ares_strsplit.c", + "src/lib/ares_timeout.c", + "src/lib/ares_version.c", + "src/lib/bitncmp.c", + "src/lib/bitncmp.h", + "src/lib/inet_net_pton.c", + "src/lib/inet_ntop.c", + "src/lib/setup_once.h", + "src/tools/ares_getopt.c", + "src/tools/ares_getopt.h", + ] + + if (!is_win) { + defines += [ + "_DARWIN_USE_64_BIT_INODE=1", + "_LARGEFILE_SOURCE", + "_FILE_OFFSET_BITS=64", + "_GNU_SOURCE", + ] + } -# This file is used by GN for building, which is NOT the build system used for -# building official binaries. -# Please modify the gyp files if you are making changes to build system. + if (is_win) { + defines += [ "CARES_PULL_WS2TCPIP_H=1" ] + include_dirs += [ "config/win32" ] + sources += [ + "src/lib/ares_getenv.c", + "src/lib/ares_iphlpapi.h", + "src/lib/ares_platform.c", + "src/lib/config-win32.h", + "src/lib/windows_port.c", + ] + libs += [ + "ws2_32.lib", + "iphlpapi.lib", + ] + } else { + defines += [ "HAVE_CONFIG_H" ] + } -import("unofficial.gni") + if (is_linux) { + include_dirs += [ "config/linux" ] + sources += [ "config/linux/ares_config.h" ] + } -cares_gn_build("cares") { + if (is_mac) { + include_dirs += [ "config/darwin" ] + sources += [ "config/darwin/ares_config.h" ] + } } diff --git a/deps/googletest/BUILD.gn b/deps/googletest/BUILD.gn index de13f3f653b5d53610f4611001c10dce332293c2..0daf8c006cef89e76d7eccec3e924bd2718021c9 100644 --- a/deps/googletest/BUILD.gn +++ b/deps/googletest/BUILD.gn @@ -1,14 +1,64 @@ -############################################################################## -# # -# DO NOT EDIT THIS FILE! # -# # -############################################################################## +config("gtest_config") { + include_dirs = [ "include" ] + defines = [ "UNIT_TEST" ] +} + +static_library("gtest") { + include_dirs = [ + "include", + "." # src + ] + + public_configs = [ ":gtest_config" ] -# This file is used by GN for building, which is NOT the build system used for -# building official binaries. -# Please modify the gyp files if you are making changes to build system. + cflags_cc = [ + "-Wno-c++98-compat-extra-semi", + "-Wno-unused-const-variable", + "-Wno-unreachable-code-return", + ] -import("unofficial.gni") + defines = [ + "GTEST_HAS_POSIX_RE=0", + "GTEST_LANG_CXX11=1", + ] + + sources = [ + "include/gtest/gtest_pred_impl.h", + "include/gtest/gtest_prod.h", + "include/gtest/gtest-death-test.h", + "include/gtest/gtest-matchers.h", + "include/gtest/gtest-message.h", + "include/gtest/gtest-param-test.h", + "include/gtest/gtest-printers.h", + "include/gtest/gtest-spi.h", + "include/gtest/gtest-test-part.h", + "include/gtest/gtest-typed-test.h", + "include/gtest/gtest.h", + "include/gtest/internal/gtest-death-test-internal.h", + "include/gtest/internal/gtest-filepath.h", + "include/gtest/internal/gtest-internal.h", + "include/gtest/internal/gtest-param-util.h", + "include/gtest/internal/gtest-port-arch.h", + "include/gtest/internal/gtest-port.h", + "include/gtest/internal/gtest-string.h", + "include/gtest/internal/gtest-type-util.h", + "include/gtest/internal/custom/gtest-port.h", + "include/gtest/internal/custom/gtest-printers.h", + "include/gtest/internal/custom/gtest.h", + "src/gtest-all.cc", + "src/gtest-death-test.cc", + "src/gtest-filepath.cc", + "src/gtest-internal-inl.h", + "src/gtest-matchers.cc", + "src/gtest-port.cc", + "src/gtest-printers.cc", + "src/gtest-test-part.cc", + "src/gtest-typed-test.cc", + "src/gtest.cc", + ] +} -googletest_gn_build("googletest") { +static_library("gtest_main") { + deps = [ ":gtest" ] + sources = [ "src/gtest_main.cc" ] } diff --git a/deps/histogram/BUILD.gn b/deps/histogram/BUILD.gn index e2f3ee37137a6b7d45cbe79f8b9ba7f693ffc4d3..85467b372f01cf602af45fa2f0d599acabfc2310 100644 --- a/deps/histogram/BUILD.gn +++ b/deps/histogram/BUILD.gn @@ -1,14 +1,19 @@ -############################################################################## -# # -# DO NOT EDIT THIS FILE! # -# # -############################################################################## +config("histogram_config") { + include_dirs = [ "include" ] -# This file is used by GN for building, which is NOT the build system used for -# building official binaries. -# Please modify the gyp files if you are making changes to build system. + cflags = [ + "-Wno-implicit-function-declaration", + "-Wno-incompatible-pointer-types", + "-Wno-unused-function", + "-Wno-atomic-alignment", + ] +} -import("unofficial.gni") +static_library("histogram") { + public_configs = [ ":histogram_config" ] -histogram_gn_build("histogram") { + sources = [ + "src/hdr_histogram.c", + "src/hdr_histogram.h", + ] } diff --git a/deps/llhttp/BUILD.gn b/deps/llhttp/BUILD.gn index 64a2a4799d5530276f46aa1faa63ece063390ada..fb000f8ee7647c375bc190d1729d67bb7770d109 100644 --- a/deps/llhttp/BUILD.gn +++ b/deps/llhttp/BUILD.gn @@ -1,14 +1,15 @@ -############################################################################## -# # -# DO NOT EDIT THIS FILE! # -# # -############################################################################## - -# This file is used by GN for building, which is NOT the build system used for -# building official binaries. -# Please modify the gyp files if you are making changes to build system. - -import("unofficial.gni") +config("llhttp_config") { + include_dirs = [ "include" ] + cflags = [ "-Wno-unreachable-code" ] +} -llhttp_gn_build("llhttp") { +static_library("llhttp") { + include_dirs = [ "include" ] + public_configs = [ ":llhttp_config" ] + cflags_c = [ "-Wno-implicit-fallthrough" ] + sources = [ + "src/api.c", + "src/http.c", + "src/llhttp.c", + ] } diff --git a/deps/nghttp2/BUILD.gn b/deps/nghttp2/BUILD.gn index 274352b0e2449f8db49d9a49c6b92a69f97e8363..7d2ca477db2415f43ababa270d8aefa3124b2765 100644 --- a/deps/nghttp2/BUILD.gn +++ b/deps/nghttp2/BUILD.gn @@ -1,14 +1,51 @@ -############################################################################## -# # -# DO NOT EDIT THIS FILE! # -# # -############################################################################## - -# This file is used by GN for building, which is NOT the build system used for -# building official binaries. -# Please modify the gyp files if you are making changes to build system. +config("nghttp2_config") { + defines = [ "NGHTTP2_STATICLIB" ] + include_dirs = [ "lib/includes" ] +} +static_library("nghttp2") { + public_configs = [ ":nghttp2_config" ] + defines = [ + "_U_", + "BUILDING_NGHTTP2", + "NGHTTP2_STATICLIB", + "HAVE_CONFIG_H", + ] + include_dirs = [ "lib/includes" ] -import("unofficial.gni") + cflags_c = [ + "-Wno-implicit-function-declaration", + "-Wno-implicit-fallthrough", + "-Wno-string-plus-int", + "-Wno-unreachable-code-return", + "-Wno-unused-but-set-variable", + ] -nghttp2_gn_build("nghttp2") { + sources = [ + "lib/nghttp2_buf.c", + "lib/nghttp2_callbacks.c", + "lib/nghttp2_debug.c", + "lib/nghttp2_extpri.c", + "lib/nghttp2_frame.c", + "lib/nghttp2_hd.c", + "lib/nghttp2_hd_huffman.c", + "lib/nghttp2_hd_huffman_data.c", + "lib/nghttp2_helper.c", + "lib/nghttp2_http.c", + "lib/nghttp2_map.c", + "lib/nghttp2_mem.c", + "lib/nghttp2_npn.c", + "lib/nghttp2_option.c", + "lib/nghttp2_outbound_item.c", + "lib/nghttp2_pq.c", + "lib/nghttp2_priority_spec.c", + "lib/nghttp2_queue.c", + "lib/nghttp2_ratelim.c", + "lib/nghttp2_rcbuf.c", + "lib/nghttp2_session.c", + "lib/nghttp2_stream.c", + "lib/nghttp2_submit.c", + "lib/nghttp2_time.c", + "lib/nghttp2_version.c", + "lib/sfparse.c" + ] } diff --git a/deps/simdjson/BUILD.gn b/deps/simdjson/BUILD.gn index d0580ccf354d2000fb0075fd3bb4579f93477927..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 100644 --- a/deps/simdjson/BUILD.gn +++ b/deps/simdjson/BUILD.gn @@ -1,14 +0,0 @@ -############################################################################## -# # -# DO NOT EDIT THIS FILE! # -# # -############################################################################## - -# This file is used by GN for building, which is NOT the build system used for -# building official binaries. -# Please modify the gyp files if you are making changes to build system. - -import("unofficial.gni") - -simdjson_gn_build("simdjson") { -} diff --git a/deps/simdutf/BUILD.gn b/deps/simdutf/BUILD.gn index 119d49456911e99944294bd00b3f182a8f0e35b5..ce38c3633a228306622a7237067393d25332c59c 100644 --- a/deps/simdutf/BUILD.gn +++ b/deps/simdutf/BUILD.gn @@ -1,14 +1,21 @@ -############################################################################## -# # -# DO NOT EDIT THIS FILE! # -# # -############################################################################## +config("simdutf_config") { + include_dirs = [ "." ] +} -# This file is used by GN for building, which is NOT the build system used for -# building official binaries. -# Please modify the gyp files if you are making changes to build system. +static_library("simdutf") { + include_dirs = [ "." ] + sources = [ + "simdutf.cpp", + ] -import("unofficial.gni") + public_configs = [ ":simdutf_config" ] -simdutf_gn_build("simdutf") { + cflags_cc = [ + "-Wno-ambiguous-reversed-operator", + "-Wno-c++98-compat-extra-semi", + "-Wno-unreachable-code", + "-Wno-unreachable-code-break", + "-Wno-unused-const-variable", + "-Wno-unused-function", + ] } diff --git a/deps/uv/BUILD.gn b/deps/uv/BUILD.gn index 8e6ac27048b5965e20f35c7a63e469beb6fa5970..7518168141db7958550c7f5dc1ed17ccdbbe4a60 100644 --- a/deps/uv/BUILD.gn +++ b/deps/uv/BUILD.gn @@ -1,14 +1,194 @@ -############################################################################## -# # -# DO NOT EDIT THIS FILE! # -# # -############################################################################## +config("libuv_config") { + include_dirs = [ "include" ] -# This file is used by GN for building, which is NOT the build system used for -# building official binaries. -# Please modify the gyp files if you are making changes to build system. + defines = [] -import("unofficial.gni") + if (is_linux) { + defines += [ "_POSIX_C_SOURCE=200112" ] + } + if (!is_win) { + defines += [ + "_LARGEFILE_SOURCE", + "_FILE_OFFSET_BITS=64", + ] + } + if (is_mac) { + defines += [ "_DARWIN_USE_64_BIT_INODE=1" ] + } +} + +static_library("uv") { + include_dirs = [ + "include", + "src", + ] + + public_configs = [ ":libuv_config" ] + + ldflags = [] + + defines = [] + + # This only has an effect on Windows, where it will cause libuv's symbols to be exported in node.lib + defines += [ "BUILDING_UV_SHARED=1" ] + + cflags_c = [ + "-Wno-incompatible-pointer-types", + "-Wno-bitwise-op-parentheses", + "-Wno-implicit-fallthrough", + "-Wno-implicit-function-declaration", + "-Wno-missing-braces", + "-Wno-sign-compare", + "-Wno-sometimes-uninitialized", + "-Wno-string-conversion", + "-Wno-switch", + "-Wno-unused-function", + "-Wno-unused-result", + "-Wno-unused-variable", + "-Wno-unreachable-code", + "-Wno-unreachable-code-return", + "-Wno-unused-but-set-variable", + "-Wno-shadow", + ] + + libs = [] + + sources = [ + "include/uv.h", + "include/uv/tree.h", + "include/uv/errno.h", + "include/uv/threadpool.h", + "include/uv/version.h", + "src/fs-poll.c", + "src/heap-inl.h", + "src/idna.c", + "src/idna.h", + "src/inet.c", + "src/queue.h", + "src/random.c", + "src/strscpy.c", + "src/strscpy.h", + "src/strtok.c", + "src/strtok.h", + "src/thread-common.c", + "src/threadpool.c", + "src/timer.c", + "src/uv-data-getter-setters.c", + "src/uv-common.c", + "src/uv-common.h", + "src/version.c", + ] + + if (is_win) { + defines += [ "_GNU_SOURCE" ] + sources += [ + "include/uv/win.h", + "src/win/async.c", + "src/win/atomicops-inl.h", + "src/win/core.c", + "src/win/detect-wakeup.c", + "src/win/dl.c", + "src/win/error.c", + "src/win/fs.c", + "src/win/fs-event.c", + "src/win/getaddrinfo.c", + "src/win/getnameinfo.c", + "src/win/handle.c", + "src/win/handle-inl.h", + "src/win/internal.h", + "src/win/loop-watcher.c", + "src/win/pipe.c", + "src/win/thread.c", + "src/win/poll.c", + "src/win/process.c", + "src/win/process-stdio.c", + "src/win/req-inl.h", + "src/win/signal.c", + "src/win/snprintf.c", + "src/win/stream.c", + "src/win/stream-inl.h", + "src/win/tcp.c", + "src/win/tty.c", + "src/win/udp.c", + "src/win/util.c", + "src/win/winapi.c", + "src/win/winapi.h", + "src/win/winsock.c", + "src/win/winsock.h", + ] -uv_gn_build("uv") { + libs += [ + "advapi32.lib", + "iphlpapi.lib", + "psapi.lib", + "shell32.lib", + "user32.lib", + "userenv.lib", + "ws2_32.lib", + ] + } else { + sources += [ + "include/uv/unix.h", + "include/uv/linux.h", + "include/uv/sunos.h", + "include/uv/darwin.h", + "include/uv/bsd.h", + "include/uv/aix.h", + "src/unix/async.c", + "src/unix/core.c", + "src/unix/dl.c", + "src/unix/fs.c", + "src/unix/getaddrinfo.c", + "src/unix/getnameinfo.c", + "src/unix/internal.h", + "src/unix/loop.c", + "src/unix/loop-watcher.c", + "src/unix/pipe.c", + "src/unix/poll.c", + "src/unix/process.c", + "src/unix/random-devurandom.c", + "src/unix/signal.c", + "src/unix/stream.c", + "src/unix/tcp.c", + "src/unix/thread.c", + "src/unix/tty.c", + "src/unix/udp.c", + ] + libs += [ "m" ] + ldflags += [ "-pthread" ] + } + if (is_mac || is_linux) { + sources += [ "src/unix/proctitle.c" ] + } + if (is_mac) { + sources += [ + "src/unix/darwin-proctitle.c", + "src/unix/darwin.c", + "src/unix/fsevents.c", + "src/unix/random-getentropy.c", + ] + defines += [ + "_DARWIN_USE_64_BIT_INODE=1", + "_DARWIN_UNLIMITED_SELECT=1", + ] + } + if (is_linux) { + defines += [ "_GNU_SOURCE" ] + sources += [ + "src/unix/linux.c", + "src/unix/procfs-exepath.c", + "src/unix/random-getrandom.c", + "src/unix/random-sysctl-linux.c", + ] + libs += [ + "dl", + "rt", + ] + } + if (is_mac) { # is_bsd + sources += [ + "src/unix/bsd-ifaddrs.c", + "src/unix/kqueue.c", + ] + } } diff --git a/deps/uvwasi/BUILD.gn b/deps/uvwasi/BUILD.gn index 4f8fb081df805a786e523e5f0ffbb0096fdeca99..d9fcf8dc972b1caa2b7a130b1144c685316035cd 100644 --- a/deps/uvwasi/BUILD.gn +++ b/deps/uvwasi/BUILD.gn @@ -1,14 +1,39 @@ -############################################################################## -# # -# DO NOT EDIT THIS FILE! # -# # -############################################################################## +config("uvwasi_config") { + include_dirs = [ "include" ] +} + +static_library("uvwasi") { + include_dirs = [ + "include", + "src", + ] + + defines = [] + if (is_linux) { + defines += [ + "_GNU_SOURCE", + "_POSIX_C_SOURCE=200112" + ] + } + + deps = [ "../../deps/uv" ] -# This file is used by GN for building, which is NOT the build system used for -# building official binaries. -# Please modify the gyp files if you are making changes to build system. + public_configs = [ ":uvwasi_config" ] -import("unofficial.gni") + cflags_c = [] + if (!is_win) { + cflags_c += [ "-fvisibility=hidden" ] + } -uvwasi_gn_build("uvwasi") { + sources = [ + "src/clocks.c", + "src/fd_table.c", + "src/path_resolver.c", + "src/poll_oneoff.c", + "src/sync_helpers.c", + "src/uv_mapping.c", + "src/uvwasi.c", + "src/wasi_rights.c", + "src/wasi_serdes.c" + ] } diff --git a/electron_node.gni b/electron_node.gni new file mode 100644 index 0000000000000000000000000000000000000000..af9cbada10203b387fb9732b346583b1c4349223 --- /dev/null +++ b/electron_node.gni @@ -0,0 +1,4 @@ +declare_args() { + # Allows embedders to override the NODE_MODULE_VERSION define + node_module_version = "" +} diff --git a/filenames.json b/filenames.json new file mode 100644 index 0000000000000000000000000000000000000000..4404338bb5d576b341cae3bf79c84334fb05654f --- /dev/null +++ b/filenames.json @@ -0,0 +1,733 @@ +// This file is automatically generated by generate_gn_filenames_json.py +// DO NOT EDIT +{ + "fs_files": [ + "lib/internal/fs/cp/cp-sync.js", + "lib/internal/fs/cp/cp.js", + "lib/internal/fs/dir.js", + "lib/internal/fs/promises.js", + "lib/internal/fs/read/context.js", + "lib/internal/fs/recursive_watch.js", + "lib/internal/fs/rimraf.js", + "lib/internal/fs/streams.js", + "lib/internal/fs/sync_write_stream.js", + "lib/internal/fs/utils.js", + "lib/internal/fs/watchers.js", + "lib/fs.js" + ], + "headers": [ + { + "dest_dir": "include/node/", + "files": [ + "src/js_native_api.h", + "src/js_native_api_types.h", + "src/node.h", + "src/node_api.h", + "src/node_api_types.h", + "src/node_buffer.h", + "src/node_object_wrap.h" + ] + }, + { + "dest_dir": "include/node//", + "files": [ + "//v8/include/v8-array-buffer.h", + "//v8/include/v8-callbacks.h", + "//v8/include/v8-container.h", + "//v8/include/v8-context.h", + "//v8/include/v8-cppgc.h", + "//v8/include/v8-data.h", + "//v8/include/v8-date.h", + "//v8/include/v8-debug.h", + "//v8/include/v8-embedder-heap.h", + "//v8/include/v8-embedder-state-scope.h", + "//v8/include/v8-exception.h", + "//v8/include/v8-extension.h", + "//v8/include/v8-external.h", + "//v8/include/v8-forward.h", + "//v8/include/v8-function-callback.h", + "//v8/include/v8-function.h", + "//v8/include/v8-handle-base.h", + "//v8/include/v8-initialization.h", + "//v8/include/v8-internal.h", + "//v8/include/v8-isolate.h", + "//v8/include/v8-json.h", + "//v8/include/v8-local-handle.h", + "//v8/include/v8-locker.h", + "//v8/include/v8-maybe.h", + "//v8/include/v8-memory-span.h", + "//v8/include/v8-message.h", + "//v8/include/v8-microtask-queue.h", + "//v8/include/v8-microtask.h", + "//v8/include/v8-object.h", + "//v8/include/v8-persistent-handle.h", + "//v8/include/v8-platform.h", + "//v8/include/v8-primitive-object.h", + "//v8/include/v8-primitive.h", + "//v8/include/v8-profiler.h", + "//v8/include/v8-promise.h", + "//v8/include/v8-proxy.h", + "//v8/include/v8-regexp.h", + "//v8/include/v8-script.h", + "//v8/include/v8-snapshot.h", + "//v8/include/v8-source-location.h", + "//v8/include/v8-statistics.h", + "//v8/include/v8-template.h", + "//v8/include/v8-traced-handle.h", + "//v8/include/v8-typed-array.h", + "//v8/include/v8-unwinder.h", + "//v8/include/v8-value-serializer.h", + "//v8/include/v8-value.h", + "//v8/include/v8-version.h", + "//v8/include/v8-wasm.h", + "//v8/include/v8-weak-callback-info.h", + "//v8/include/v8.h", + "//v8/include/v8config.h" + ] + }, + { + "dest_dir": "include/node//libplatform/", + "files": [ + "//v8/include/libplatform/libplatform-export.h", + "//v8/include/libplatform/libplatform.h", + "//v8/include/libplatform/v8-tracing.h" + ] + }, + { + "dest_dir": "include/node//cppgc/", + "files": [ + "//v8/include/cppgc/allocation.h", + "//v8/include/cppgc/common.h", + "//v8/include/cppgc/cross-thread-persistent.h", + "//v8/include/cppgc/custom-space.h", + "//v8/include/cppgc/default-platform.h", + "//v8/include/cppgc/ephemeron-pair.h", + "//v8/include/cppgc/explicit-management.h", + "//v8/include/cppgc/garbage-collected.h", + "//v8/include/cppgc/heap-consistency.h", + "//v8/include/cppgc/heap-handle.h", + "//v8/include/cppgc/heap-state.h", + "//v8/include/cppgc/heap-statistics.h", + "//v8/include/cppgc/heap.h", + "//v8/include/cppgc/liveness-broker.h", + "//v8/include/cppgc/macros.h", + "//v8/include/cppgc/member.h", + "//v8/include/cppgc/name-provider.h", + "//v8/include/cppgc/object-size-trait.h", + "//v8/include/cppgc/persistent.h", + "//v8/include/cppgc/platform.h", + "//v8/include/cppgc/prefinalizer.h", + "//v8/include/cppgc/process-heap-statistics.h", + "//v8/include/cppgc/sentinel-pointer.h", + "//v8/include/cppgc/source-location.h", + "//v8/include/cppgc/testing.h", + "//v8/include/cppgc/trace-trait.h", + "//v8/include/cppgc/type-traits.h", + "//v8/include/cppgc/visitor.h" + ] + }, + { + "dest_dir": "include/node//cppgc/internal/", + "files": [ + "//v8/include/cppgc/internal/api-constants.h", + "//v8/include/cppgc/internal/atomic-entry-flag.h", + "//v8/include/cppgc/internal/base-page-handle.h", + "//v8/include/cppgc/internal/caged-heap-local-data.h", + "//v8/include/cppgc/internal/caged-heap.h", + "//v8/include/cppgc/internal/compiler-specific.h", + "//v8/include/cppgc/internal/finalizer-trait.h", + "//v8/include/cppgc/internal/gc-info.h", + "//v8/include/cppgc/internal/logging.h", + "//v8/include/cppgc/internal/member-storage.h", + "//v8/include/cppgc/internal/name-trait.h", + "//v8/include/cppgc/internal/persistent-node.h", + "//v8/include/cppgc/internal/pointer-policies.h", + "//v8/include/cppgc/internal/write-barrier.h" + ] + }, + { + "dest_dir": "include/node//", + "files": [ + "deps/uv/include/uv.h" + ] + }, + { + "dest_dir": "include/node//uv/", + "files": [ + "deps/uv/include/uv/aix.h", + "deps/uv/include/uv/bsd.h", + "deps/uv/include/uv/darwin.h", + "deps/uv/include/uv/errno.h", + "deps/uv/include/uv/linux.h", + "deps/uv/include/uv/os390.h", + "deps/uv/include/uv/posix.h", + "deps/uv/include/uv/sunos.h", + "deps/uv/include/uv/threadpool.h", + "deps/uv/include/uv/tree.h", + "deps/uv/include/uv/unix.h", + "deps/uv/include/uv/version.h", + "deps/uv/include/uv/win.h" + ] + } + ], + "library_files": [ + "lib/_http_agent.js", + "lib/_http_client.js", + "lib/_http_common.js", + "lib/_http_incoming.js", + "lib/_http_outgoing.js", + "lib/_http_server.js", + "lib/_stream_duplex.js", + "lib/_stream_passthrough.js", + "lib/_stream_readable.js", + "lib/_stream_transform.js", + "lib/_stream_wrap.js", + "lib/_stream_writable.js", + "lib/_tls_common.js", + "lib/_tls_wrap.js", + "lib/assert.js", + "lib/assert/strict.js", + "lib/async_hooks.js", + "lib/buffer.js", + "lib/child_process.js", + "lib/cluster.js", + "lib/console.js", + "lib/constants.js", + "lib/crypto.js", + "lib/dgram.js", + "lib/diagnostics_channel.js", + "lib/dns.js", + "lib/dns/promises.js", + "lib/domain.js", + "lib/events.js", + "lib/fs/promises.js", + "lib/http.js", + "lib/http2.js", + "lib/https.js", + "lib/inspector.js", + "lib/inspector/promises.js", + "lib/internal/abort_controller.js", + "lib/internal/assert.js", + "lib/internal/assert/assertion_error.js", + "lib/internal/assert/calltracker.js", + "lib/internal/async_hooks.js", + "lib/internal/blob.js", + "lib/internal/blocklist.js", + "lib/internal/bootstrap/node.js", + "lib/internal/bootstrap/realm.js", + "lib/internal/bootstrap/shadow_realm.js", + "lib/internal/bootstrap/switches/does_not_own_process_state.js", + "lib/internal/bootstrap/switches/does_own_process_state.js", + "lib/internal/bootstrap/switches/is_main_thread.js", + "lib/internal/bootstrap/switches/is_not_main_thread.js", + "lib/internal/bootstrap/web/exposed-wildcard.js", + "lib/internal/bootstrap/web/exposed-window-or-worker.js", + "lib/internal/buffer.js", + "lib/internal/child_process.js", + "lib/internal/child_process/serialization.js", + "lib/internal/cli_table.js", + "lib/internal/cluster/child.js", + "lib/internal/cluster/primary.js", + "lib/internal/cluster/round_robin_handle.js", + "lib/internal/cluster/shared_handle.js", + "lib/internal/cluster/utils.js", + "lib/internal/cluster/worker.js", + "lib/internal/console/constructor.js", + "lib/internal/console/global.js", + "lib/internal/constants.js", + "lib/internal/crypto/aes.js", + "lib/internal/crypto/certificate.js", + "lib/internal/crypto/cfrg.js", + "lib/internal/crypto/cipher.js", + "lib/internal/crypto/diffiehellman.js", + "lib/internal/crypto/ec.js", + "lib/internal/crypto/hash.js", + "lib/internal/crypto/hashnames.js", + "lib/internal/crypto/hkdf.js", + "lib/internal/crypto/keygen.js", + "lib/internal/crypto/keys.js", + "lib/internal/crypto/mac.js", + "lib/internal/crypto/pbkdf2.js", + "lib/internal/crypto/random.js", + "lib/internal/crypto/rsa.js", + "lib/internal/crypto/scrypt.js", + "lib/internal/crypto/sig.js", + "lib/internal/crypto/util.js", + "lib/internal/crypto/webcrypto.js", + "lib/internal/crypto/webidl.js", + "lib/internal/crypto/x509.js", + "lib/internal/debugger/inspect.js", + "lib/internal/debugger/inspect_client.js", + "lib/internal/debugger/inspect_repl.js", + "lib/internal/dgram.js", + "lib/internal/dns/callback_resolver.js", + "lib/internal/dns/promises.js", + "lib/internal/dns/utils.js", + "lib/internal/encoding.js", + "lib/internal/error_serdes.js", + "lib/internal/errors.js", + "lib/internal/event_target.js", + "lib/internal/events/symbols.js", + "lib/internal/file.js", + "lib/internal/fixed_queue.js", + "lib/internal/freelist.js", + "lib/internal/freeze_intrinsics.js", + "lib/internal/heap_utils.js", + "lib/internal/histogram.js", + "lib/internal/http.js", + "lib/internal/http2/compat.js", + "lib/internal/http2/core.js", + "lib/internal/http2/util.js", + "lib/internal/idna.js", + "lib/internal/inspector_async_hook.js", + "lib/internal/js_stream_socket.js", + "lib/internal/legacy/processbinding.js", + "lib/internal/linkedlist.js", + "lib/internal/main/check_syntax.js", + "lib/internal/main/embedding.js", + "lib/internal/main/eval_stdin.js", + "lib/internal/main/eval_string.js", + "lib/internal/main/inspect.js", + "lib/internal/main/mksnapshot.js", + "lib/internal/main/print_help.js", + "lib/internal/main/prof_process.js", + "lib/internal/main/repl.js", + "lib/internal/main/run_main_module.js", + "lib/internal/main/test_runner.js", + "lib/internal/main/watch_mode.js", + "lib/internal/main/worker_thread.js", + "lib/internal/mime.js", + "lib/internal/modules/cjs/loader.js", + "lib/internal/modules/esm/assert.js", + "lib/internal/modules/esm/create_dynamic_module.js", + "lib/internal/modules/esm/fetch_module.js", + "lib/internal/modules/esm/formats.js", + "lib/internal/modules/esm/get_format.js", + "lib/internal/modules/esm/handle_process_exit.js", + "lib/internal/modules/esm/hooks.js", + "lib/internal/modules/esm/initialize_import_meta.js", + "lib/internal/modules/esm/load.js", + "lib/internal/modules/esm/loader.js", + "lib/internal/modules/esm/module_job.js", + "lib/internal/modules/esm/module_map.js", + "lib/internal/modules/esm/package_config.js", + "lib/internal/modules/esm/resolve.js", + "lib/internal/modules/esm/shared_constants.js", + "lib/internal/modules/esm/translators.js", + "lib/internal/modules/esm/utils.js", + "lib/internal/modules/esm/worker.js", + "lib/internal/modules/helpers.js", + "lib/internal/modules/package_json_reader.js", + "lib/internal/modules/run_main.js", + "lib/internal/navigator.js", + "lib/internal/net.js", + "lib/internal/options.js", + "lib/internal/per_context/domexception.js", + "lib/internal/per_context/messageport.js", + "lib/internal/per_context/primordials.js", + "lib/internal/perf/event_loop_delay.js", + "lib/internal/perf/event_loop_utilization.js", + "lib/internal/perf/nodetiming.js", + "lib/internal/perf/observe.js", + "lib/internal/perf/performance.js", + "lib/internal/perf/performance_entry.js", + "lib/internal/perf/resource_timing.js", + "lib/internal/perf/timerify.js", + "lib/internal/perf/usertiming.js", + "lib/internal/perf/utils.js", + "lib/internal/policy/manifest.js", + "lib/internal/policy/sri.js", + "lib/internal/priority_queue.js", + "lib/internal/process/esm_loader.js", + "lib/internal/process/execution.js", + "lib/internal/process/per_thread.js", + "lib/internal/process/permission.js", + "lib/internal/process/policy.js", + "lib/internal/process/pre_execution.js", + "lib/internal/process/promises.js", + "lib/internal/process/report.js", + "lib/internal/process/signal.js", + "lib/internal/process/task_queues.js", + "lib/internal/process/warning.js", + "lib/internal/process/worker_thread_only.js", + "lib/internal/promise_hooks.js", + "lib/internal/querystring.js", + "lib/internal/readline/callbacks.js", + "lib/internal/readline/emitKeypressEvents.js", + "lib/internal/readline/interface.js", + "lib/internal/readline/promises.js", + "lib/internal/readline/utils.js", + "lib/internal/repl.js", + "lib/internal/repl/await.js", + "lib/internal/repl/history.js", + "lib/internal/repl/utils.js", + "lib/internal/socket_list.js", + "lib/internal/socketaddress.js", + "lib/internal/source_map/prepare_stack_trace.js", + "lib/internal/source_map/source_map.js", + "lib/internal/source_map/source_map_cache.js", + "lib/internal/stream_base_commons.js", + "lib/internal/streams/add-abort-signal.js", + "lib/internal/streams/compose.js", + "lib/internal/streams/destroy.js", + "lib/internal/streams/duplex.js", + "lib/internal/streams/duplexify.js", + "lib/internal/streams/end-of-stream.js", + "lib/internal/streams/from.js", + "lib/internal/streams/lazy_transform.js", + "lib/internal/streams/legacy.js", + "lib/internal/streams/operators.js", + "lib/internal/streams/passthrough.js", + "lib/internal/streams/pipeline.js", + "lib/internal/streams/readable.js", + "lib/internal/streams/state.js", + "lib/internal/streams/transform.js", + "lib/internal/streams/utils.js", + "lib/internal/streams/writable.js", + "lib/internal/test/binding.js", + "lib/internal/test/transfer.js", + "lib/internal/test_runner/coverage.js", + "lib/internal/test_runner/harness.js", + "lib/internal/test_runner/mock/mock.js", + "lib/internal/test_runner/mock/mock_timers.js", + "lib/internal/test_runner/reporter/dot.js", + "lib/internal/test_runner/reporter/junit.js", + "lib/internal/test_runner/reporter/lcov.js", + "lib/internal/test_runner/reporter/spec.js", + "lib/internal/test_runner/reporter/tap.js", + "lib/internal/test_runner/reporter/v8-serializer.js", + "lib/internal/test_runner/runner.js", + "lib/internal/test_runner/test.js", + "lib/internal/test_runner/tests_stream.js", + "lib/internal/test_runner/utils.js", + "lib/internal/timers.js", + "lib/internal/tls/secure-context.js", + "lib/internal/tls/secure-pair.js", + "lib/internal/trace_events_async_hooks.js", + "lib/internal/tty.js", + "lib/internal/url.js", + "lib/internal/util.js", + "lib/internal/util/colors.js", + "lib/internal/util/comparisons.js", + "lib/internal/util/debuglog.js", + "lib/internal/util/embedding.js", + "lib/internal/util/inspect.js", + "lib/internal/util/inspector.js", + "lib/internal/util/iterable_weak_map.js", + "lib/internal/util/parse_args/parse_args.js", + "lib/internal/util/parse_args/utils.js", + "lib/internal/util/types.js", + "lib/internal/v8/startup_snapshot.js", + "lib/internal/v8_prof_polyfill.js", + "lib/internal/v8_prof_processor.js", + "lib/internal/validators.js", + "lib/internal/vm.js", + "lib/internal/vm/module.js", + "lib/internal/wasm_web_api.js", + "lib/internal/watch_mode/files_watcher.js", + "lib/internal/watchdog.js", + "lib/internal/webidl.js", + "lib/internal/webstreams/adapters.js", + "lib/internal/webstreams/compression.js", + "lib/internal/webstreams/encoding.js", + "lib/internal/webstreams/queuingstrategies.js", + "lib/internal/webstreams/readablestream.js", + "lib/internal/webstreams/transfer.js", + "lib/internal/webstreams/transformstream.js", + "lib/internal/webstreams/util.js", + "lib/internal/webstreams/writablestream.js", + "lib/internal/worker.js", + "lib/internal/worker/io.js", + "lib/internal/worker/js_transferable.js", + "lib/module.js", + "lib/net.js", + "lib/os.js", + "lib/path.js", + "lib/path/posix.js", + "lib/path/win32.js", + "lib/perf_hooks.js", + "lib/process.js", + "lib/punycode.js", + "lib/querystring.js", + "lib/readline.js", + "lib/readline/promises.js", + "lib/repl.js", + "lib/stream.js", + "lib/stream/consumers.js", + "lib/stream/promises.js", + "lib/stream/web.js", + "lib/string_decoder.js", + "lib/sys.js", + "lib/test.js", + "lib/test/reporters.js", + "lib/timers.js", + "lib/timers/promises.js", + "lib/tls.js", + "lib/trace_events.js", + "lib/tty.js", + "lib/url.js", + "lib/util.js", + "lib/util/types.js", + "lib/v8.js", + "lib/vm.js", + "lib/wasi.js", + "lib/worker_threads.js", + "lib/zlib.js", + "deps/v8/tools/splaytree.mjs", + "deps/v8/tools/codemap.mjs", + "deps/v8/tools/consarray.mjs", + "deps/v8/tools/csvparser.mjs", + "deps/v8/tools/profile.mjs", + "deps/v8/tools/profile_view.mjs", + "deps/v8/tools/logreader.mjs", + "deps/v8/tools/arguments.mjs", + "deps/v8/tools/tickprocessor.mjs", + "deps/v8/tools/sourcemap.mjs", + "deps/v8/tools/tickprocessor-driver.mjs", + "deps/acorn/acorn/dist/acorn.js", + "deps/acorn/acorn-walk/dist/walk.js", + "deps/minimatch/index.js", + "deps/cjs-module-lexer/lexer.js", + "deps/cjs-module-lexer/dist/lexer.js", + "deps/undici/undici.js" + ], + "node_sources": [ + "src/api/async_resource.cc", + "src/api/callback.cc", + "src/api/embed_helpers.cc", + "src/api/encoding.cc", + "src/api/environment.cc", + "src/api/exceptions.cc", + "src/api/hooks.cc", + "src/api/utils.cc", + "src/async_wrap.cc", + "src/base_object.cc", + "src/cares_wrap.cc", + "src/cleanup_queue.cc", + "src/connect_wrap.cc", + "src/connection_wrap.cc", + "src/dataqueue/queue.cc", + "src/debug_utils.cc", + "src/encoding_binding.cc", + "src/env.cc", + "src/fs_event_wrap.cc", + "src/handle_wrap.cc", + "src/heap_utils.cc", + "src/histogram.cc", + "src/js_native_api.h", + "src/js_native_api_types.h", + "src/js_native_api_v8.cc", + "src/js_native_api_v8.h", + "src/js_native_api_v8_internals.h", + "src/js_stream.cc", + "src/json_utils.cc", + "src/js_udp_wrap.cc", + "src/json_parser.h", + "src/json_parser.cc", + "src/module_wrap.cc", + "src/node.cc", + "src/node_api.cc", + "src/node_binding.cc", + "src/node_blob.cc", + "src/node_buffer.cc", + "src/node_builtins.cc", + "src/node_config.cc", + "src/node_constants.cc", + "src/node_contextify.cc", + "src/node_credentials.cc", + "src/node_dir.cc", + "src/node_dotenv.cc", + "src/node_env_var.cc", + "src/node_errors.cc", + "src/node_external_reference.cc", + "src/node_file.cc", + "src/node_http_parser.cc", + "src/node_http2.cc", + "src/node_i18n.cc", + "src/node_main_instance.cc", + "src/node_messaging.cc", + "src/node_metadata.cc", + "src/node_options.cc", + "src/node_os.cc", + "src/node_perf.cc", + "src/node_platform.cc", + "src/node_postmortem_metadata.cc", + "src/node_process_events.cc", + "src/node_process_methods.cc", + "src/node_process_object.cc", + "src/node_realm.cc", + "src/node_report.cc", + "src/node_report_module.cc", + "src/node_report_utils.cc", + "src/node_sea.cc", + "src/node_serdes.cc", + "src/node_shadow_realm.cc", + "src/node_snapshotable.cc", + "src/node_sockaddr.cc", + "src/node_stat_watcher.cc", + "src/node_symbols.cc", + "src/node_task_queue.cc", + "src/node_trace_events.cc", + "src/node_types.cc", + "src/node_url.cc", + "src/node_util.cc", + "src/node_v8.cc", + "src/node_wasi.cc", + "src/node_wasm_web_api.cc", + "src/node_watchdog.cc", + "src/node_worker.cc", + "src/node_zlib.cc", + "src/permission/child_process_permission.cc", + "src/permission/fs_permission.cc", + "src/permission/inspector_permission.cc", + "src/permission/permission.cc", + "src/permission/worker_permission.cc", + "src/pipe_wrap.cc", + "src/process_wrap.cc", + "src/signal_wrap.cc", + "src/spawn_sync.cc", + "src/stream_base.cc", + "src/stream_pipe.cc", + "src/stream_wrap.cc", + "src/string_bytes.cc", + "src/string_decoder.cc", + "src/tcp_wrap.cc", + "src/timers.cc", + "src/timer_wrap.cc", + "src/tracing/agent.cc", + "src/tracing/node_trace_buffer.cc", + "src/tracing/node_trace_writer.cc", + "src/tracing/trace_event.cc", + "src/tracing/traced_value.cc", + "src/tty_wrap.cc", + "src/udp_wrap.cc", + "src/util.cc", + "src/uv.cc", + "src/aliased_buffer.h", + "src/aliased_buffer-inl.h", + "src/aliased_struct.h", + "src/aliased_struct-inl.h", + "src/async_wrap.h", + "src/async_wrap-inl.h", + "src/base_object.h", + "src/base_object-inl.h", + "src/base_object_types.h", + "src/base64.h", + "src/base64-inl.h", + "src/blob_serializer_deserializer.h", + "src/blob_serializer_deserializer-inl.h", + "src/callback_queue.h", + "src/callback_queue-inl.h", + "src/cleanup_queue.h", + "src/cleanup_queue-inl.h", + "src/connect_wrap.h", + "src/connection_wrap.h", + "src/dataqueue/queue.h", + "src/debug_utils.h", + "src/debug_utils-inl.h", + "src/encoding_binding.h", + "src/env_properties.h", + "src/env.h", + "src/env-inl.h", + "src/handle_wrap.h", + "src/histogram.h", + "src/histogram-inl.h", + "src/js_stream.h", + "src/json_utils.h", + "src/large_pages/node_large_page.cc", + "src/large_pages/node_large_page.h", + "src/memory_tracker.h", + "src/memory_tracker-inl.h", + "src/module_wrap.h", + "src/node.h", + "src/node_api.h", + "src/node_api_types.h", + "src/node_binding.h", + "src/node_blob.h", + "src/node_buffer.h", + "src/node_builtins.h", + "src/node_constants.h", + "src/node_context_data.h", + "src/node_contextify.h", + "src/node_dir.h", + "src/node_dotenv.h", + "src/node_errors.h", + "src/node_exit_code.h", + "src/node_external_reference.h", + "src/node_file.h", + "src/node_file-inl.h", + "src/node_http_common.h", + "src/node_http_common-inl.h", + "src/node_http2.h", + "src/node_http2_state.h", + "src/node_i18n.h", + "src/node_internals.h", + "src/node_main_instance.h", + "src/node_mem.h", + "src/node_mem-inl.h", + "src/node_messaging.h", + "src/node_metadata.h", + "src/node_mutex.h", + "src/node_object_wrap.h", + "src/node_options.h", + "src/node_options-inl.h", + "src/node_perf.h", + "src/node_perf_common.h", + "src/node_platform.h", + "src/node_process.h", + "src/node_process-inl.h", + "src/node_realm.h", + "src/node_realm-inl.h", + "src/node_report.h", + "src/node_revert.h", + "src/node_root_certs.h", + "src/node_sea.h", + "src/node_shadow_realm.h", + "src/node_snapshotable.h", + "src/node_snapshot_builder.h", + "src/node_sockaddr.h", + "src/node_sockaddr-inl.h", + "src/node_stat_watcher.h", + "src/node_union_bytes.h", + "src/node_url.h", + "src/node_version.h", + "src/node_v8.h", + "src/node_v8_platform-inl.h", + "src/node_wasi.h", + "src/node_watchdog.h", + "src/node_worker.h", + "src/permission/child_process_permission.h", + "src/permission/fs_permission.h", + "src/permission/inspector_permission.h", + "src/permission/permission.h", + "src/permission/worker_permission.h", + "src/pipe_wrap.h", + "src/req_wrap.h", + "src/req_wrap-inl.h", + "src/spawn_sync.h", + "src/stream_base.h", + "src/stream_base-inl.h", + "src/stream_pipe.h", + "src/stream_wrap.h", + "src/string_bytes.h", + "src/string_decoder.h", + "src/string_decoder-inl.h", + "src/string_search.h", + "src/tcp_wrap.h", + "src/timers.h", + "src/tracing/agent.h", + "src/tracing/node_trace_buffer.h", + "src/tracing/node_trace_writer.h", + "src/tracing/trace_event.h", + "src/tracing/trace_event_common.h", + "src/tracing/traced_value.h", + "src/timer_wrap.h", + "src/timer_wrap-inl.h", + "src/tty_wrap.h", + "src/udp_wrap.h", + "src/util.h", + "src/util-inl.h", + "//v8/include/v8.h", + "deps/postject/postject-api.h" + ] +} diff --git a/src/inspector/BUILD.gn b/src/inspector/BUILD.gn index 909fd14345fcd988c381e640280f4b33f2e0c351..cb0e4558436ab7a109cadf439d49413b0f569a5a 100644 --- a/src/inspector/BUILD.gn +++ b/src/inspector/BUILD.gn @@ -1,14 +1,203 @@ -############################################################################## -# # -# DO NOT EDIT THIS FILE! # -# # -############################################################################## +import("//v8/gni/v8.gni") -# This file is used by GN for building, which is NOT the build system used for -# building official binaries. -# Please modify the gyp files if you are making changes to build system. +inspector_protocol_dir = "../../tools/inspector_protocol" -import("unofficial.gni") +_protocol_generated = [ + "protocol/Forward.h", + "protocol/Protocol.cpp", + "protocol/Protocol.h", + "protocol/NodeWorker.cpp", + "protocol/NodeWorker.h", + "protocol/NodeTracing.cpp", + "protocol/NodeTracing.h", + "protocol/NodeRuntime.cpp", + "protocol/NodeRuntime.h", +] -inspector_gn_build("inspector") { +# These are from node_protocol_config.json +# These convoluted path hacks are to work around the fact that node.js is very +# confused about what paths are in its includes, without changing node at all. +# Hopefully, keying everything in this file off the paths that are in +# node_protocol_config.json will mean that the paths stay in sync. +inspector_protocol_package = "src/node/inspector/protocol" +inspector_protocol_output = "node/inspector/protocol" + +config("inspector_config") { + include_dirs = [ + "$target_gen_dir", + "$target_gen_dir/src", + ] + + configs = [ "../..:node_features" ] +} + +source_set("inspector") { + sources = [ + "main_thread_interface.cc", + "main_thread_interface.h", + "node_string.cc", + "node_string.h", + "runtime_agent.cc", + "runtime_agent.h", + "tracing_agent.cc", + "tracing_agent.h", + "worker_agent.cc", + "worker_agent.h", + "worker_inspector.cc", + "worker_inspector.h", + ] + sources += rebase_path(_protocol_generated, + ".", + "$target_gen_dir/$inspector_protocol_package/..") + include_dirs = [ + "//v8/include", + "..", + ] + deps = [ + ":protocol_generated_sources", + ":v8_inspector_compress_protocol_json", + "../../deps/uv", + "../../deps/simdutf", + "//third_party/icu:icuuc", + ] + configs += [ + "../..:node_internal_config", + "../..:node_lib_config", + ] + public_configs = [ ":inspector_config" ] +} + +# This based on the template from //v8/../inspector_protocol.gni +action("protocol_generated_sources") { + # This is to ensure that the output directory exists--the code generator + # doesn't create it. + write_file("$target_gen_dir/$inspector_protocol_package/.dummy", "") + script = "$inspector_protocol_dir/code_generator.py" + + inputs = [ + "$target_gen_dir/node_protocol_config.json", + "$target_gen_dir/src/node_protocol.json", + "$inspector_protocol_dir/lib/base_string_adapter_cc.template", + "$inspector_protocol_dir/lib/base_string_adapter_h.template", + "$inspector_protocol_dir/lib/Allocator_h.template", + "$inspector_protocol_dir/lib/Array_h.template", + "$inspector_protocol_dir/lib/DispatcherBase_cpp.template", + "$inspector_protocol_dir/lib/DispatcherBase_h.template", + "$inspector_protocol_dir/lib/ErrorSupport_cpp.template", + "$inspector_protocol_dir/lib/ErrorSupport_h.template", + "$inspector_protocol_dir/lib/Forward_h.template", + "$inspector_protocol_dir/lib/FrontendChannel_h.template", + "$inspector_protocol_dir/lib/Maybe_h.template", + "$inspector_protocol_dir/lib/Object_cpp.template", + "$inspector_protocol_dir/lib/Object_h.template", + "$inspector_protocol_dir/lib/Parser_cpp.template", + "$inspector_protocol_dir/lib/Parser_h.template", + "$inspector_protocol_dir/lib/Protocol_cpp.template", + "$inspector_protocol_dir/lib/ValueConversions_h.template", + "$inspector_protocol_dir/lib/Values_cpp.template", + "$inspector_protocol_dir/lib/Values_h.template", + "$inspector_protocol_dir/templates/Exported_h.template", + "$inspector_protocol_dir/templates/Imported_h.template", + "$inspector_protocol_dir/templates/TypeBuilder_cpp.template", + "$inspector_protocol_dir/templates/TypeBuilder_h.template", + ] + + deps = [ + ":node_protocol_config", + ":node_protocol_json", + ] + + args = [ + "--jinja_dir", + rebase_path("//third_party/", root_build_dir), # jinja is in chromium's third_party + "--output_base", + rebase_path("$target_gen_dir/src", root_build_dir), + "--config", + rebase_path("$target_gen_dir/node_protocol_config.json", root_build_dir), + ] + + outputs = + get_path_info(rebase_path(rebase_path(_protocol_generated, + ".", + "$inspector_protocol_output/.."), + ".", + "$target_gen_dir/src"), + "abspath") +} + +template("generate_protocol_json") { + copy_target_name = target_name + "_copy" + copy(copy_target_name) { + sources = invoker.sources + outputs = [ + "$target_gen_dir/{{source_file_part}}", + ] + } + copied_pdl = get_target_outputs(":$copy_target_name") + action(target_name) { + deps = [ + ":$copy_target_name", + ] + sources = copied_pdl + outputs = invoker.outputs + script = "$inspector_protocol_dir/convert_protocol_to_json.py" + args = rebase_path(sources + outputs, root_build_dir) + } +} + +copy("node_protocol_config") { + sources = [ + "node_protocol_config.json", + ] + outputs = [ + "$target_gen_dir/{{source_file_part}}", + ] +} + +generate_protocol_json("node_protocol_json") { + sources = [ + "node_protocol.pdl", + ] + outputs = [ + "$target_gen_dir/src/node_protocol.json", + ] +} + +generate_protocol_json("v8_protocol_json") { + sources = [ + "//v8/include/js_protocol.pdl", + ] + outputs = [ + "$target_gen_dir/js_protocol.json", + ] +} + +action("concatenate_protocols") { + deps = [ + ":node_protocol_json", + ":v8_protocol_json", + ] + inputs = [ + "$target_gen_dir/js_protocol.json", + "$target_gen_dir/src/node_protocol.json", + ] + outputs = [ + "$target_gen_dir/concatenated_protocol.json", + ] + script = "//v8/third_party/inspector_protocol/concatenate_protocols.py" + args = rebase_path(inputs + outputs, root_build_dir) +} + +action("v8_inspector_compress_protocol_json") { + deps = [ + ":concatenate_protocols", + ] + inputs = [ + "$target_gen_dir/concatenated_protocol.json", + ] + outputs = [ + "$target_gen_dir/v8_inspector_protocol_json.h", + ] + script = "../../tools/compress_json.py" + args = rebase_path(inputs + outputs, root_build_dir) } diff --git a/src/node_builtins.cc b/src/node_builtins.cc index bafd8d4b8581f0aee6cb1f30b810c8dfc46c2ce9..453d874efff767a95ef25fad7005ac11717f0c67 100644 --- a/src/node_builtins.cc +++ b/src/node_builtins.cc @@ -739,6 +739,7 @@ void BuiltinLoader::RegisterExternalReferences( registry->Register(GetNatives); RegisterExternalReferencesForInternalizedBuiltinCode(registry); + EmbedderRegisterExternalReferencesForInternalizedBuiltinCode(registry); } } // namespace builtins diff --git a/src/node_builtins.h b/src/node_builtins.h index 9f2fbc1e53937448aa27c1f5fe110eabc7edc0df..ea77c7598153bb8a9ba20c89a4ece2c1580b9a25 100644 --- a/src/node_builtins.h +++ b/src/node_builtins.h @@ -74,6 +74,8 @@ using BuiltinCodeCacheMap = // Generated by tools/js2c.py as node_javascript.cc void RegisterExternalReferencesForInternalizedBuiltinCode( ExternalReferenceRegistry* registry); +void EmbedderRegisterExternalReferencesForInternalizedBuiltinCode( + ExternalReferenceRegistry* registry); // Handles compilation and caching of built-in JavaScript modules and // bootstrap scripts, whose source are bundled into the binary as static data. diff --git a/tools/generate_gn_filenames_json.py b/tools/generate_gn_filenames_json.py new file mode 100755 index 0000000000000000000000000000000000000000..7848ddb1841b6d4f36e9376c73564eb4ff6d7c08 --- /dev/null +++ b/tools/generate_gn_filenames_json.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +import json +import os +import sys + +import install + +from utils import SearchFiles + +def LoadPythonDictionary(path): + file_string = open(path).read() + try: + file_data = eval(file_string, {'__builtins__': None}, None) + except SyntaxError as e: + e.filename = path + raise + except Exception as e: + raise Exception("Unexpected error while reading %s: %s" % (path, str(e))) + + assert isinstance(file_data, dict), "%s does not eval to a dictionary" % path + + return file_data + + +FILENAMES_JSON_HEADER = ''' +// This file is automatically generated by generate_gn_filenames_json.py +// DO NOT EDIT +'''.lstrip() + + +if __name__ == '__main__': + node_root_dir = os.path.dirname(os.path.dirname(__file__)) + node_gyp_path = os.path.join(node_root_dir, 'node.gyp') + out = {} + node_gyp = LoadPythonDictionary(node_gyp_path) + node_lib_target = next( + t for t in node_gyp['targets'] + if t['target_name'] == '<(node_lib_target_name)') + node_source_blocklist = { + '<@(library_files)', + '<@(deps_files)', + '<@(node_sources)', + 'common.gypi', + '<(SHARED_INTERMEDIATE_DIR)/node_javascript.cc', + } + + def filter_v8_files(files): + if any(f.startswith('deps/v8/') for f in files): + files = [f.replace('deps/v8/', '../../v8/', 1) if f.endswith('js') else f.replace('deps/v8/', '//v8/') for f in files] + + if any(f == '<@(node_builtin_shareable_builtins)' for f in files): + files.remove('<@(node_builtin_shareable_builtins)') + shared_builtins = ['deps/cjs-module-lexer/lexer.js', 'deps/cjs-module-lexer/dist/lexer.js', 'deps/undici/undici.js'] + files.extend(shared_builtins) + + return files + + def filter_fs_files(files): + return [f for f in files if f.startswith('lib/internal/fs/')] + ['lib/fs.js'] + + lib_files = SearchFiles('lib', 'js') + out['library_files'] = filter_v8_files(lib_files) + out['library_files'] += filter_v8_files(node_gyp['variables']['deps_files']) + out['node_sources'] = node_gyp['variables']['node_sources'] + + out['fs_files'] = filter_fs_files(out['library_files']) + # fs files are handled separately + out['library_files'] = [f for f in out['library_files'] if f not in out['fs_files']] + + blocklisted_sources = [ + f for f in node_lib_target['sources'] + if f not in node_source_blocklist] + out['node_sources'] += filter_v8_files(blocklisted_sources) + + out['headers'] = [] + def add_headers(files, dest_dir): + if 'src/node.h' in files: + files = [f for f in files if f.endswith('.h') and f != 'src/node_version.h'] + elif any(f.startswith('../../v8/') for f in files): + files = [f.replace('../../v8/', '//v8/', 1) for f in files] + if files: + hs = {'files': sorted(files), 'dest_dir': dest_dir} + out['headers'].append(hs) + + install.variables = {'node_shared_libuv': 'false'} + install.headers(add_headers) + with open(os.path.join(node_root_dir, 'filenames.json'), 'w') as f: + f.write(FILENAMES_JSON_HEADER) + f.write(json.dumps(out, sort_keys=True, indent=2, separators=(',', ': '))) + f.write('\n') diff --git a/tools/generate_original_fs.py b/tools/generate_original_fs.py new file mode 100644 index 0000000000000000000000000000000000000000..98d569e6ba6d85a29a215a8f9ce3c1f6a9bd655e --- /dev/null +++ b/tools/generate_original_fs.py @@ -0,0 +1,18 @@ +import os +import sys + +node_root_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) +out_dir = sys.argv[1] +fs_files = sys.argv[2:] + +for fs_file in fs_files: + with open(os.path.join(node_root_dir, fs_file), 'r') as f: + contents = f.read() + original_fs_file = fs_file.replace('internal/fs/', 'internal/original-fs/').replace('lib/fs.js', 'lib/original-fs.js') + + with open(os.path.join(out_dir, fs_file), 'w') as original_f: + original_f.write(contents) + + with open(os.path.join(out_dir, original_fs_file), 'w') as transformed_f: + transformed_contents = contents.replace('internal/fs/', 'internal/original-fs/') + transformed_f.write(transformed_contents) diff --git a/tools/install.py b/tools/install.py index 11616e1bcac5308020eb68fdb811bfb86cb14dd5..74b01f8352021f1105c080dbbf8bb29121a13501 100755 --- a/tools/install.py +++ b/tools/install.py @@ -199,105 +199,108 @@ def headers(action): v8_headers = [ # The internal cppgc headers are depended on by the public # ones, so they need to be included as well. - 'deps/v8/include/cppgc/internal/api-constants.h', - 'deps/v8/include/cppgc/internal/atomic-entry-flag.h', - 'deps/v8/include/cppgc/internal/base-page-handle.h', - 'deps/v8/include/cppgc/internal/caged-heap-local-data.h', - 'deps/v8/include/cppgc/internal/caged-heap.h', - 'deps/v8/include/cppgc/internal/compiler-specific.h', - 'deps/v8/include/cppgc/internal/finalizer-trait.h', - 'deps/v8/include/cppgc/internal/gc-info.h', - 'deps/v8/include/cppgc/internal/logging.h', - 'deps/v8/include/cppgc/internal/member-storage.h', - 'deps/v8/include/cppgc/internal/name-trait.h', - 'deps/v8/include/cppgc/internal/persistent-node.h', - 'deps/v8/include/cppgc/internal/pointer-policies.h', - 'deps/v8/include/cppgc/internal/write-barrier.h', + '../../v8/include/cppgc/internal/api-constants.h', + '../../v8/include/cppgc/internal/atomic-entry-flag.h', + '../../v8/include/cppgc/internal/base-page-handle.h', + '../../v8/include/cppgc/internal/caged-heap-local-data.h', + '../../v8/include/cppgc/internal/caged-heap.h', + '../../v8/include/cppgc/internal/compiler-specific.h', + '../../v8/include/cppgc/internal/finalizer-trait.h', + '../../v8/include/cppgc/internal/gc-info.h', + '../../v8/include/cppgc/internal/logging.h', + '../../v8/include/cppgc/internal/member-storage.h', + '../../v8/include/cppgc/internal/name-trait.h', + '../../v8/include/cppgc/internal/persistent-node.h', + '../../v8/include/cppgc/internal/pointer-policies.h', + '../../v8/include/cppgc/internal/write-barrier.h', # cppgc headers - 'deps/v8/include/cppgc/allocation.h', - 'deps/v8/include/cppgc/common.h', - 'deps/v8/include/cppgc/cross-thread-persistent.h', - 'deps/v8/include/cppgc/custom-space.h', - 'deps/v8/include/cppgc/default-platform.h', - 'deps/v8/include/cppgc/ephemeron-pair.h', - 'deps/v8/include/cppgc/explicit-management.h', - 'deps/v8/include/cppgc/garbage-collected.h', - 'deps/v8/include/cppgc/heap-consistency.h', - 'deps/v8/include/cppgc/heap-handle.h', - 'deps/v8/include/cppgc/heap-state.h', - 'deps/v8/include/cppgc/heap-statistics.h', - 'deps/v8/include/cppgc/heap.h', - 'deps/v8/include/cppgc/liveness-broker.h', - 'deps/v8/include/cppgc/macros.h', - 'deps/v8/include/cppgc/member.h', - 'deps/v8/include/cppgc/name-provider.h', - 'deps/v8/include/cppgc/object-size-trait.h', - 'deps/v8/include/cppgc/persistent.h', - 'deps/v8/include/cppgc/platform.h', - 'deps/v8/include/cppgc/prefinalizer.h', - 'deps/v8/include/cppgc/process-heap-statistics.h', - 'deps/v8/include/cppgc/sentinel-pointer.h', - 'deps/v8/include/cppgc/source-location.h', - 'deps/v8/include/cppgc/testing.h', - 'deps/v8/include/cppgc/trace-trait.h', - 'deps/v8/include/cppgc/type-traits.h', - 'deps/v8/include/cppgc/visitor.h', + '../../v8/include/cppgc/allocation.h', + '../../v8/include/cppgc/common.h', + '../../v8/include/cppgc/cross-thread-persistent.h', + '../../v8/include/cppgc/custom-space.h', + '../../v8/include/cppgc/default-platform.h', + '../../v8/include/cppgc/ephemeron-pair.h', + '../../v8/include/cppgc/explicit-management.h', + '../../v8/include/cppgc/garbage-collected.h', + '../../v8/include/cppgc/heap-consistency.h', + '../../v8/include/cppgc/heap-handle.h', + '../../v8/include/cppgc/heap-state.h', + '../../v8/include/cppgc/heap-statistics.h', + '../../v8/include/cppgc/heap.h', + '../../v8/include/cppgc/liveness-broker.h', + '../../v8/include/cppgc/macros.h', + '../../v8/include/cppgc/member.h', + '../../v8/include/cppgc/name-provider.h', + '../../v8/include/cppgc/object-size-trait.h', + '../../v8/include/cppgc/persistent.h', + '../../v8/include/cppgc/platform.h', + '../../v8/include/cppgc/prefinalizer.h', + '../../v8/include/cppgc/process-heap-statistics.h', + '../../v8/include/cppgc/sentinel-pointer.h', + '../../v8/include/cppgc/source-location.h', + '../../v8/include/cppgc/testing.h', + '../../v8/include/cppgc/trace-trait.h', + '../../v8/include/cppgc/type-traits.h', + '../../v8/include/cppgc/visitor.h', # libplatform headers - 'deps/v8/include/libplatform/libplatform-export.h', - 'deps/v8/include/libplatform/libplatform.h', - 'deps/v8/include/libplatform/v8-tracing.h', + '../../v8/include/libplatform/libplatform-export.h', + '../../v8/include/libplatform/libplatform.h', + '../../v8/include/libplatform/v8-tracing.h', # v8 headers - 'deps/v8/include/v8-array-buffer.h', - 'deps/v8/include/v8-callbacks.h', - 'deps/v8/include/v8-container.h', - 'deps/v8/include/v8-context.h', - 'deps/v8/include/v8-cppgc.h', - 'deps/v8/include/v8-data.h', - 'deps/v8/include/v8-date.h', - 'deps/v8/include/v8-debug.h', - 'deps/v8/include/v8-embedder-heap.h', - 'deps/v8/include/v8-embedder-state-scope.h', - 'deps/v8/include/v8-exception.h', - 'deps/v8/include/v8-extension.h', - 'deps/v8/include/v8-external.h', - 'deps/v8/include/v8-forward.h', - 'deps/v8/include/v8-function-callback.h', - 'deps/v8/include/v8-function.h', - 'deps/v8/include/v8-initialization.h', - 'deps/v8/include/v8-internal.h', - 'deps/v8/include/v8-isolate.h', - 'deps/v8/include/v8-json.h', - 'deps/v8/include/v8-local-handle.h', - 'deps/v8/include/v8-locker.h', - 'deps/v8/include/v8-maybe.h', - 'deps/v8/include/v8-memory-span.h', - 'deps/v8/include/v8-message.h', - 'deps/v8/include/v8-microtask-queue.h', - 'deps/v8/include/v8-microtask.h', - 'deps/v8/include/v8-object.h', - 'deps/v8/include/v8-persistent-handle.h', - 'deps/v8/include/v8-platform.h', - 'deps/v8/include/v8-primitive-object.h', - 'deps/v8/include/v8-primitive.h', - 'deps/v8/include/v8-profiler.h', - 'deps/v8/include/v8-promise.h', - 'deps/v8/include/v8-proxy.h', - 'deps/v8/include/v8-regexp.h', - 'deps/v8/include/v8-script.h', - 'deps/v8/include/v8-snapshot.h', - 'deps/v8/include/v8-statistics.h', - 'deps/v8/include/v8-template.h', - 'deps/v8/include/v8-traced-handle.h', - 'deps/v8/include/v8-typed-array.h', - 'deps/v8/include/v8-unwinder.h', - 'deps/v8/include/v8-value-serializer.h', - 'deps/v8/include/v8-value.h', - 'deps/v8/include/v8-version.h', - 'deps/v8/include/v8-wasm.h', - 'deps/v8/include/v8-weak-callback-info.h', - 'deps/v8/include/v8.h', - 'deps/v8/include/v8config.h', + '../../v8/include/v8-array-buffer.h', + '../../v8/include/v8-callbacks.h', + '../../v8/include/v8-container.h', + '../../v8/include/v8-context.h', + '../../v8/include/v8-cppgc.h', + '../../v8/include/v8-data.h', + '../../v8/include/v8-date.h', + '../../v8/include/v8-debug.h', + '../../v8/include/v8-embedder-heap.h', + '../../v8/include/v8-embedder-state-scope.h', + '../../v8/include/v8-exception.h', + '../../v8/include/v8-extension.h', + '../../v8/include/v8-external.h', + '../../v8/include/v8-forward.h', + '../../v8/include/v8-function-callback.h', + '../../v8/include/v8-function.h', + '../../v8/include/v8-handle-base.h', + '../../v8/include/v8-initialization.h', + '../../v8/include/v8-internal.h', + '../../v8/include/v8-isolate.h', + '../../v8/include/v8-json.h', + '../../v8/include/v8-local-handle.h', + '../../v8/include/v8-locker.h', + '../../v8/include/v8-maybe.h', + '../../v8/include/v8-memory-span.h', + '../../v8/include/v8-message.h', + '../../v8/include/v8-microtask-queue.h', + '../../v8/include/v8-microtask.h', + '../../v8/include/v8-object.h', + '../../v8/include/v8-persistent-handle.h', + '../../v8/include/v8-platform.h', + '../../v8/include/v8-primitive-object.h', + '../../v8/include/v8-primitive.h', + '../../v8/include/v8-profiler.h', + '../../v8/include/v8-promise.h', + '../../v8/include/v8-proxy.h', + '../../v8/include/v8-regexp.h', + '../../v8/include/v8-script.h', + '../../v8/include/v8-snapshot.h', + '../../v8/include/v8-source-location.h', + '../../v8/include/v8-statistics.h', + '../../v8/include/v8-template.h', + '../../v8/include/v8-traced-handle.h', + '../../v8/include/v8-typed-array.h', + '../../v8/include/v8-unwinder.h', + '../../v8/include/v8-value-serializer.h', + '../../v8/include/v8-value.h', + '../../v8/include/v8-version.h', + '../../v8/include/v8-wasm.h', + '../../v8/include/v8-weak-callback-info.h', + '../../v8/include/v8.h', + '../../v8/include/v8config.h', ] + v8_headers = [h.replace('deps/', '../../') for h in v8_headers] files_arg = [name for name in files_arg if name in v8_headers] action(files_arg, dest) @@ -324,7 +327,7 @@ def headers(action): if sys.platform.startswith('aix') or sys.platform == "os400": action(['out/Release/node.exp'], 'include/node/') - subdir_files('deps/v8/include', 'include/node/', wanted_v8_headers) + subdir_files('../../v8/include', 'include/node/', wanted_v8_headers) if 'false' == variables.get('node_shared_libuv'): subdir_files('deps/uv/include', 'include/node/', action) diff --git a/tools/js2c.cc b/tools/js2c.cc old mode 100644 new mode 100755 index 904fb6fa44d4f56fb67476e937edcbb797d78fe7..129cd4b2c12b58464fbab8355afa0c26721d1413 --- a/tools/js2c.cc +++ b/tools/js2c.cc @@ -29,6 +29,7 @@ namespace js2c { int Main(int argc, char* argv[]); static bool is_verbose = false; +static bool only_js = false; void Debug(const char* format, ...) { va_list arguments; @@ -195,6 +196,7 @@ const char* kTemplate = R"( #include "node_builtins.h" #include "node_external_reference.h" #include "node_internals.h" +#include "node_threadsafe_cow-inl.h" namespace node { @@ -210,7 +212,11 @@ const ThreadsafeCopyOnWrite<BuiltinSourceMap> global_source_map { } // anonymous namespace void BuiltinLoader::LoadJavaScriptSource() { - source_ = global_source_map; + BuiltinSourceMap map = *source_.read(); + BuiltinSourceMap new_map = *global_source_map.read(); + + map.merge(new_map); + source_ = ThreadsafeCopyOnWrite<BuiltinSourceMap>(map); } void RegisterExternalReferencesForInternalizedBuiltinCode( @@ -227,6 +233,45 @@ UnionBytes BuiltinLoader::GetConfig() { } // namespace node )"; +const char* kEmbedderTemplate = R"( +#include "env-inl.h" +#include "node_builtins.h" +#include "node_external_reference.h" +#include "node_internals.h" +#include "node_threadsafe_cow-inl.h" + +namespace node { + +namespace builtins { + +%.*s +namespace { +const ThreadsafeCopyOnWrite<BuiltinSourceMap> global_source_map { + BuiltinSourceMap { +%.*s + } // BuiltinSourceMap + +}; // ThreadsafeCopyOnWrite +} // anonymous namespace + +void BuiltinLoader::LoadEmbedderJavaScriptSource() { + BuiltinSourceMap map = *source_.read(); + BuiltinSourceMap new_map = *global_source_map.read(); + + map.merge(new_map); + source_ = ThreadsafeCopyOnWrite<BuiltinSourceMap>(map); +} + +void EmbedderRegisterExternalReferencesForInternalizedBuiltinCode( + ExternalReferenceRegistry* registry) { +%.*s +} + +} // namespace builtins + +} // namespace node +)"; + Fragment Format(const Fragments& definitions, const Fragments& initializers, const Fragments& registrations) { @@ -236,13 +281,12 @@ Fragment Format(const Fragments& definitions, size_t init_size = init_buf.size(); std::vector<char> reg_buf = Join(registrations, "\n"); size_t reg_size = reg_buf.size(); - - size_t result_size = - def_size + init_size + reg_size + strlen(kTemplate) + 100; + size_t result_size = def_size + init_size + reg_size + + strlen(only_js ? kEmbedderTemplate: kTemplate) + 300; std::vector<char> result(result_size, 0); int r = snprintf(result.data(), result_size, - kTemplate, + only_js ? kEmbedderTemplate: kTemplate, static_cast<int>(def_buf.size()), def_buf.data(), static_cast<int>(init_buf.size()), @@ -711,12 +755,15 @@ int JS2C(const FileList& js_files, } } + if (!only_js) { assert(FilenameIsConfigGypi(config)); // "config.gypi" -> config_raw. int r = AddGypi("config", config, &definitions); if (r != 0) { return r; } + } + Fragment out = Format(definitions, initializers, registrations); return WriteIfChanged(out, dest); } @@ -742,6 +789,8 @@ int Main(int argc, char* argv[]) { std::string arg(argv[i]); if (arg == "--verbose") { is_verbose = true; + } else if (arg == "--only-js") { + only_js = true; } else if (arg == "--root") { if (i == argc - 1) { fprintf(stderr, "--root must be followed by a path\n"); @@ -790,6 +839,14 @@ int Main(int argc, char* argv[]) { } } + if (only_js) { + auto js_it = file_map.find(".js"); + + assert(file_map.size() == 1); + assert(js_it != file_map.end()); + + return JS2C(js_it->second, FileList(), std::string(), output); + } else { // Should have exactly 3 types: `.js`, `.mjs` and `.gypi`. assert(file_map.size() == 3); auto gypi_it = file_map.find(".gypi"); @@ -809,6 +866,7 @@ int Main(int argc, char* argv[]) { std::sort(mjs_it->second.begin(), mjs_it->second.end()); return JS2C(js_it->second, mjs_it->second, gypi_it->second[0], output); + } } } // namespace js2c } // namespace node @@ -817,4 +875,4 @@ NODE_MAIN(int argc, node::argv_type raw_argv[]) { char** argv; node::FixupMain(argc, raw_argv, &argv); return node::js2c::Main(argc, argv); -} +} \ No newline at end of file
closed
electron/electron
https://github.com/electron/electron
41,008
[Bug]: `original-fs` does not provide unmodified methods
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 28.1.3 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior `original-fs` should provide unmodified methods from Node.js' `fs` module ### Actual Behavior `original-fs` seems to be using our ASAR patches that are meant to be applied only when importing the plain `fs` module in Electron ### Testcase Gist URL https://gist.github.com/3f029d290d598c9e1d1322c25c48c575 ### Additional Information The Fiddle above is just a slight variation of the repro provided by @tangjfn in #40943 / #40960 (thanks for the test case!), where you can enter a path to a folder containing an `.asar` file and attempt to remove it using `fs.promises.rm` or `fs.promises.rmdir`. They both fail with `ENOTEMPTY: directory not empty`: ![image](https://github.com/electron/electron/assets/19478575/e7555a0f-7fa2-43b6-ac43-d00b94f191e1)
https://github.com/electron/electron/issues/41008
https://github.com/electron/electron/pull/41209
fb888a6989dacfd6be3fe1a2b1cfffd0de81246a
5dfa9e33172d994c2f2a98a00312134cbc703d6b
2024-01-16T15:52:39Z
c++
2024-02-05T08:51:04Z
spec/asar-spec.ts
import { expect } from 'chai'; import * as path from 'node:path'; import * as url from 'node:url'; import { Worker } from 'node:worker_threads'; import { BrowserWindow, ipcMain } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import { getRemoteContext, ifdescribe, ifit, itremote, useRemoteContext } from './lib/spec-helpers'; import * as importedFs from 'node:fs'; import { once } from 'node:events'; describe('asar package', () => { const fixtures = path.join(__dirname, 'fixtures'); const asarDir = path.join(fixtures, 'test.asar'); afterEach(closeAllWindows); describe('asar protocol', () => { it('sets __dirname correctly', async function () { after(function () { ipcMain.removeAllListeners('dirname'); }); const w = new BrowserWindow({ show: false, width: 400, height: 400, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const p = path.resolve(asarDir, 'web.asar', 'index.html'); const dirnameEvent = once(ipcMain, 'dirname'); w.loadFile(p); const [, dirname] = await dirnameEvent; expect(dirname).to.equal(path.dirname(p)); }); it('loads script tag in html', async function () { after(function () { ipcMain.removeAllListeners('ping'); }); const w = new BrowserWindow({ show: false, width: 400, height: 400, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const p = path.resolve(asarDir, 'script.asar', 'index.html'); const ping = once(ipcMain, 'ping'); w.loadFile(p); const [, message] = await ping; expect(message).to.equal('pong'); }); it('loads video tag in html', async function () { this.timeout(60000); after(function () { ipcMain.removeAllListeners('asar-video'); }); const w = new BrowserWindow({ show: false, width: 400, height: 400, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const p = path.resolve(asarDir, 'video.asar', 'index.html'); w.loadFile(p); const [, message, error] = await once(ipcMain, 'asar-video'); if (message === 'ended') { expect(error).to.be.null(); } else if (message === 'error') { throw new Error(error); } }); }); describe('worker', () => { it('Worker can load asar file', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'workers', 'load_worker.html')); const workerUrl = url.format({ pathname: path.resolve(fixtures, 'workers', 'workers.asar', 'worker.js').replaceAll('\\', '/'), protocol: 'file', slashes: true }); const result = await w.webContents.executeJavaScript(`loadWorker('${workerUrl}')`); expect(result).to.equal('success'); }); it('SharedWorker can load asar file', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'workers', 'load_shared_worker.html')); const workerUrl = url.format({ pathname: path.resolve(fixtures, 'workers', 'workers.asar', 'shared_worker.js').replaceAll('\\', '/'), protocol: 'file', slashes: true }); const result = await w.webContents.executeJavaScript(`loadSharedWorker('${workerUrl}')`); expect(result).to.equal('success'); }); }); describe('worker threads', function () { // DISABLED-FIXME(#38192): only disabled for ASan. ifit(!process.env.IS_ASAN)('should start worker thread from asar file', function (callback) { const p = path.join(asarDir, 'worker_threads.asar', 'worker.js'); const w = new Worker(p); w.on('error', (err) => callback(err)); w.on('message', (message) => { expect(message).to.equal('ping'); w.terminate(); callback(null); }); }); }); }); // eslint-disable-next-line @typescript-eslint/no-unused-vars async function expectToThrowErrorWithCode (_func: Function, _code: string) { /* dummy for typescript */ } // eslint-disable-next-line @typescript-eslint/no-unused-vars function promisify (_f: Function): any { /* dummy for typescript */ } describe('asar package', function () { const fixtures = path.join(__dirname, 'fixtures'); const asarDir = path.join(fixtures, 'test.asar'); const fs = require('node:fs') as typeof importedFs; // dummy, to fool typescript useRemoteContext({ url: url.pathToFileURL(path.join(fixtures, 'pages', 'blank.html')), setup: ` async function expectToThrowErrorWithCode (func, code) { let error; try { await func(); } catch (e) { error = e; } const chai = require('chai') chai.expect(error).to.have.property('code').which.equals(code); } fs = require('node:fs') path = require('node:path') asarDir = ${JSON.stringify(asarDir)} // This is used instead of util.promisify for some tests to dodge the // util.promisify.custom behavior. promisify = (f) => { return (...args) => new Promise((resolve, reject) => { f(...args, (err, result) => { if (err) reject(err) else resolve(result) }) }) } null ` }); describe('node api', function () { itremote('supports paths specified as a Buffer', function () { const file = Buffer.from(path.join(asarDir, 'a.asar', 'file1')); expect(fs.existsSync(file)).to.be.true(); }); describe('fs.readFileSync', function () { itremote('does not leak fd', function () { let readCalls = 1; while (readCalls <= 10000) { fs.readFileSync(path.join(process.resourcesPath, 'default_app.asar', 'main.js')); readCalls++; } }); itremote('reads a normal file', function () { const file1 = path.join(asarDir, 'a.asar', 'file1'); expect(fs.readFileSync(file1).toString().trim()).to.equal('file1'); const file2 = path.join(asarDir, 'a.asar', 'file2'); expect(fs.readFileSync(file2).toString().trim()).to.equal('file2'); const file3 = path.join(asarDir, 'a.asar', 'file3'); expect(fs.readFileSync(file3).toString().trim()).to.equal('file3'); }); itremote('reads from a empty file', function () { const file = path.join(asarDir, 'empty.asar', 'file1'); const buffer = fs.readFileSync(file); expect(buffer).to.be.empty(); expect(buffer.toString()).to.equal(''); }); itremote('reads a linked file', function () { const p = path.join(asarDir, 'a.asar', 'link1'); expect(fs.readFileSync(p).toString().trim()).to.equal('file1'); }); itremote('reads a file from linked directory', function () { const p1 = path.join(asarDir, 'a.asar', 'link2', 'file1'); expect(fs.readFileSync(p1).toString().trim()).to.equal('file1'); const p2 = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1'); expect(fs.readFileSync(p2).toString().trim()).to.equal('file1'); }); itremote('throws ENOENT error when can not find file', function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); expect(() => { fs.readFileSync(p); }).to.throw(/ENOENT/); }); itremote('passes ENOENT error to callback when can not find file', function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); let async = false; fs.readFile(p, function (error) { expect(async).to.be.true(); expect(error).to.match(/ENOENT/); }); async = true; }); itremote('reads a normal file with unpacked files', function () { const p = path.join(asarDir, 'unpack.asar', 'a.txt'); expect(fs.readFileSync(p).toString().trim()).to.equal('a'); }); itremote('reads a file in filesystem', function () { const p = path.resolve(asarDir, 'file'); expect(fs.readFileSync(p).toString().trim()).to.equal('file'); }); }); describe('fs.readFile', function () { itremote('reads a normal file', async function () { const p = path.join(asarDir, 'a.asar', 'file1'); const content = await new Promise((resolve, reject) => fs.readFile(p, (err, content) => { if (err) return reject(err); resolve(content); })); expect(String(content).trim()).to.equal('file1'); }); itremote('reads from a empty file', async function () { const p = path.join(asarDir, 'empty.asar', 'file1'); const content = await new Promise((resolve, reject) => fs.readFile(p, (err, content) => { if (err) return reject(err); resolve(content); })); expect(String(content)).to.equal(''); }); itremote('reads from a empty file with encoding', async function () { const p = path.join(asarDir, 'empty.asar', 'file1'); const content = await new Promise((resolve, reject) => fs.readFile(p, (err, content) => { if (err) return reject(err); resolve(content); })); expect(String(content)).to.equal(''); }); itremote('reads a linked file', async function () { const p = path.join(asarDir, 'a.asar', 'link1'); const content = await new Promise((resolve, reject) => fs.readFile(p, (err, content) => { if (err) return reject(err); resolve(content); })); expect(String(content).trim()).to.equal('file1'); }); itremote('reads a file from linked directory', async function () { const p = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1'); const content = await new Promise((resolve, reject) => fs.readFile(p, (err, content) => { if (err) return reject(err); resolve(content); })); expect(String(content).trim()).to.equal('file1'); }); itremote('throws ENOENT error when can not find file', async function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); const err = await new Promise<any>((resolve) => fs.readFile(p, resolve)); expect(err.code).to.equal('ENOENT'); }); }); describe('fs.promises.readFile', function () { itremote('reads a normal file', async function () { const p = path.join(asarDir, 'a.asar', 'file1'); const content = await fs.promises.readFile(p); expect(String(content).trim()).to.equal('file1'); }); itremote('reads from a empty file', async function () { const p = path.join(asarDir, 'empty.asar', 'file1'); const content = await fs.promises.readFile(p); expect(String(content)).to.equal(''); }); itremote('reads from a empty file with encoding', async function () { const p = path.join(asarDir, 'empty.asar', 'file1'); const content = await fs.promises.readFile(p, 'utf8'); expect(content).to.equal(''); }); itremote('reads a linked file', async function () { const p = path.join(asarDir, 'a.asar', 'link1'); const content = await fs.promises.readFile(p); expect(String(content).trim()).to.equal('file1'); }); itremote('reads a file from linked directory', async function () { const p = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1'); const content = await fs.promises.readFile(p); expect(String(content).trim()).to.equal('file1'); }); itremote('throws ENOENT error when can not find file', async function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); await expectToThrowErrorWithCode(() => fs.promises.readFile(p), 'ENOENT'); }); }); describe('fs.copyFile', function () { itremote('copies a normal file', async function () { const p = path.join(asarDir, 'a.asar', 'file1'); const temp = require('temp').track(); const dest = temp.path(); await new Promise<void>((resolve, reject) => { fs.copyFile(p, dest, (err) => { if (err) reject(err); else resolve(); }); }); expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true(); }); itremote('copies a unpacked file', async function () { const p = path.join(asarDir, 'unpack.asar', 'a.txt'); const temp = require('temp').track(); const dest = temp.path(); await new Promise<void>((resolve, reject) => { fs.copyFile(p, dest, (err) => { if (err) reject(err); else resolve(); }); }); expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true(); }); }); describe('fs.promises.copyFile', function () { itremote('copies a normal file', async function () { const p = path.join(asarDir, 'a.asar', 'file1'); const temp = require('temp').track(); const dest = temp.path(); await fs.promises.copyFile(p, dest); expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true(); }); itremote('copies a unpacked file', async function () { const p = path.join(asarDir, 'unpack.asar', 'a.txt'); const temp = require('temp').track(); const dest = temp.path(); await fs.promises.copyFile(p, dest); expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true(); }); }); describe('fs.copyFileSync', function () { itremote('copies a normal file', function () { const p = path.join(asarDir, 'a.asar', 'file1'); const temp = require('temp').track(); const dest = temp.path(); fs.copyFileSync(p, dest); expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true(); }); itremote('copies a unpacked file', function () { const p = path.join(asarDir, 'unpack.asar', 'a.txt'); const temp = require('temp').track(); const dest = temp.path(); fs.copyFileSync(p, dest); expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true(); }); }); describe('fs.lstatSync', function () { itremote('handles path with trailing slash correctly', function () { const p = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1'); fs.lstatSync(p); fs.lstatSync(p + '/'); }); itremote('returns information of root', function () { const p = path.join(asarDir, 'a.asar'); const stats = fs.lstatSync(p); expect(stats.isFile()).to.be.false(); expect(stats.isDirectory()).to.be.true(); expect(stats.isSymbolicLink()).to.be.false(); expect(stats.size).to.equal(0); }); itremote('returns information of root with stats as bigint', function () { const p = path.join(asarDir, 'a.asar'); const stats = fs.lstatSync(p, { bigint: false }); expect(stats.isFile()).to.be.false(); expect(stats.isDirectory()).to.be.true(); expect(stats.isSymbolicLink()).to.be.false(); expect(stats.size).to.equal(0); }); itremote('returns information of a normal file', function () { const ref2 = ['file1', 'file2', 'file3', path.join('dir1', 'file1'), path.join('link2', 'file1')]; for (let j = 0, len = ref2.length; j < len; j++) { const file = ref2[j]; const p = path.join(asarDir, 'a.asar', file); const stats = fs.lstatSync(p); expect(stats.isFile()).to.be.true(); expect(stats.isDirectory()).to.be.false(); expect(stats.isSymbolicLink()).to.be.false(); expect(stats.size).to.equal(6); } }); itremote('returns information of a normal directory', function () { const ref2 = ['dir1', 'dir2', 'dir3']; for (let j = 0, len = ref2.length; j < len; j++) { const file = ref2[j]; const p = path.join(asarDir, 'a.asar', file); const stats = fs.lstatSync(p); expect(stats.isFile()).to.be.false(); expect(stats.isDirectory()).to.be.true(); expect(stats.isSymbolicLink()).to.be.false(); expect(stats.size).to.equal(0); } }); itremote('returns information of a linked file', function () { const ref2 = ['link1', path.join('dir1', 'link1'), path.join('link2', 'link2')]; for (let j = 0, len = ref2.length; j < len; j++) { const file = ref2[j]; const p = path.join(asarDir, 'a.asar', file); const stats = fs.lstatSync(p); expect(stats.isFile()).to.be.false(); expect(stats.isDirectory()).to.be.false(); expect(stats.isSymbolicLink()).to.be.true(); expect(stats.size).to.equal(0); } }); itremote('returns information of a linked directory', function () { const ref2 = ['link2', path.join('dir1', 'link2'), path.join('link2', 'link2')]; for (let j = 0, len = ref2.length; j < len; j++) { const file = ref2[j]; const p = path.join(asarDir, 'a.asar', file); const stats = fs.lstatSync(p); expect(stats.isFile()).to.be.false(); expect(stats.isDirectory()).to.be.false(); expect(stats.isSymbolicLink()).to.be.true(); expect(stats.size).to.equal(0); } }); itremote('throws ENOENT error when can not find file', function () { const ref2 = ['file4', 'file5', path.join('dir1', 'file4')]; for (let j = 0, len = ref2.length; j < len; j++) { const file = ref2[j]; const p = path.join(asarDir, 'a.asar', file); expect(() => { fs.lstatSync(p); }).to.throw(/ENOENT/); } }); itremote('returns null when can not find file with throwIfNoEntry === false', function () { const ref2 = ['file4', 'file5', path.join('dir1', 'file4')]; for (let j = 0, len = ref2.length; j < len; j++) { const file = ref2[j]; const p = path.join(asarDir, 'a.asar', file); expect(fs.lstatSync(p, { throwIfNoEntry: false })).to.equal(null); } }); }); describe('fs.lstat', function () { itremote('handles path with trailing slash correctly', async function () { const p = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1'); await promisify(fs.lstat)(p + '/'); }); itremote('returns information of root', async function () { const p = path.join(asarDir, 'a.asar'); const stats = await promisify(fs.lstat)(p); expect(stats.isFile()).to.be.false(); expect(stats.isDirectory()).to.be.true(); expect(stats.isSymbolicLink()).to.be.false(); expect(stats.size).to.equal(0); }); itremote('returns information of root with stats as bigint', async function () { const p = path.join(asarDir, 'a.asar'); const stats = await promisify(fs.lstat)(p, { bigint: false }); expect(stats.isFile()).to.be.false(); expect(stats.isDirectory()).to.be.true(); expect(stats.isSymbolicLink()).to.be.false(); expect(stats.size).to.equal(0); }); itremote('returns information of a normal file', async function () { const p = path.join(asarDir, 'a.asar', 'link2', 'file1'); const stats = await promisify(fs.lstat)(p); expect(stats.isFile()).to.be.true(); expect(stats.isDirectory()).to.be.false(); expect(stats.isSymbolicLink()).to.be.false(); expect(stats.size).to.equal(6); }); itremote('returns information of a normal directory', async function () { const p = path.join(asarDir, 'a.asar', 'dir1'); const stats = await promisify(fs.lstat)(p); expect(stats.isFile()).to.be.false(); expect(stats.isDirectory()).to.be.true(); expect(stats.isSymbolicLink()).to.be.false(); expect(stats.size).to.equal(0); }); itremote('returns information of a linked file', async function () { const p = path.join(asarDir, 'a.asar', 'link2', 'link1'); const stats = await promisify(fs.lstat)(p); expect(stats.isFile()).to.be.false(); expect(stats.isDirectory()).to.be.false(); expect(stats.isSymbolicLink()).to.be.true(); expect(stats.size).to.equal(0); }); itremote('returns information of a linked directory', async function () { const p = path.join(asarDir, 'a.asar', 'link2', 'link2'); const stats = await promisify(fs.lstat)(p); expect(stats.isFile()).to.be.false(); expect(stats.isDirectory()).to.be.false(); expect(stats.isSymbolicLink()).to.be.true(); expect(stats.size).to.equal(0); }); itremote('throws ENOENT error when can not find file', async function () { const p = path.join(asarDir, 'a.asar', 'file4'); const err = await new Promise<any>(resolve => fs.lstat(p, resolve)); expect(err.code).to.equal('ENOENT'); }); }); describe('fs.promises.lstat', function () { itremote('handles path with trailing slash correctly', async function () { const p = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1'); await fs.promises.lstat(p + '/'); }); itremote('returns information of root', async function () { const p = path.join(asarDir, 'a.asar'); const stats = await fs.promises.lstat(p); expect(stats.isFile()).to.be.false(); expect(stats.isDirectory()).to.be.true(); expect(stats.isSymbolicLink()).to.be.false(); expect(stats.size).to.equal(0); }); itremote('returns information of root with stats as bigint', async function () { const p = path.join(asarDir, 'a.asar'); const stats = await fs.promises.lstat(p, { bigint: false }); expect(stats.isFile()).to.be.false(); expect(stats.isDirectory()).to.be.true(); expect(stats.isSymbolicLink()).to.be.false(); expect(stats.size).to.equal(0); }); itremote('returns information of a normal file', async function () { const p = path.join(asarDir, 'a.asar', 'link2', 'file1'); const stats = await fs.promises.lstat(p); expect(stats.isFile()).to.be.true(); expect(stats.isDirectory()).to.be.false(); expect(stats.isSymbolicLink()).to.be.false(); expect(stats.size).to.equal(6); }); itremote('returns information of a normal directory', async function () { const p = path.join(asarDir, 'a.asar', 'dir1'); const stats = await fs.promises.lstat(p); expect(stats.isFile()).to.be.false(); expect(stats.isDirectory()).to.be.true(); expect(stats.isSymbolicLink()).to.be.false(); expect(stats.size).to.equal(0); }); itremote('returns information of a linked file', async function () { const p = path.join(asarDir, 'a.asar', 'link2', 'link1'); const stats = await fs.promises.lstat(p); expect(stats.isFile()).to.be.false(); expect(stats.isDirectory()).to.be.false(); expect(stats.isSymbolicLink()).to.be.true(); expect(stats.size).to.equal(0); }); itremote('returns information of a linked directory', async function () { const p = path.join(asarDir, 'a.asar', 'link2', 'link2'); const stats = await fs.promises.lstat(p); expect(stats.isFile()).to.be.false(); expect(stats.isDirectory()).to.be.false(); expect(stats.isSymbolicLink()).to.be.true(); expect(stats.size).to.equal(0); }); itremote('throws ENOENT error when can not find file', async function () { const p = path.join(asarDir, 'a.asar', 'file4'); await expectToThrowErrorWithCode(() => fs.promises.lstat(p), 'ENOENT'); }); }); describe('fs.realpathSync', () => { itremote('returns real path root', () => { const parent = fs.realpathSync(asarDir); const p = 'a.asar'; const r = fs.realpathSync(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('returns real path of a normal file', () => { const parent = fs.realpathSync(asarDir); const p = path.join('a.asar', 'file1'); const r = fs.realpathSync(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('returns real path of a normal directory', () => { const parent = fs.realpathSync(asarDir); const p = path.join('a.asar', 'dir1'); const r = fs.realpathSync(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('returns real path of a linked file', () => { const parent = fs.realpathSync(asarDir); const p = path.join('a.asar', 'link2', 'link1'); const r = fs.realpathSync(path.join(parent, p)); expect(r).to.equal(path.join(parent, 'a.asar', 'file1')); }); itremote('returns real path of a linked directory', () => { const parent = fs.realpathSync(asarDir); const p = path.join('a.asar', 'link2', 'link2'); const r = fs.realpathSync(path.join(parent, p)); expect(r).to.equal(path.join(parent, 'a.asar', 'dir1')); }); itremote('returns real path of an unpacked file', () => { const parent = fs.realpathSync(asarDir); const p = path.join('unpack.asar', 'a.txt'); const r = fs.realpathSync(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('throws ENOENT error when can not find file', () => { const parent = fs.realpathSync(asarDir); const p = path.join('a.asar', 'not-exist'); expect(() => { fs.realpathSync(path.join(parent, p)); }).to.throw(/ENOENT/); }); }); describe('fs.realpathSync.native', () => { itremote('returns real path root', () => { const parent = fs.realpathSync.native(asarDir); const p = 'a.asar'; const r = fs.realpathSync.native(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('returns real path of a normal file', () => { const parent = fs.realpathSync.native(asarDir); const p = path.join('a.asar', 'file1'); const r = fs.realpathSync.native(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('returns real path of a normal directory', () => { const parent = fs.realpathSync.native(asarDir); const p = path.join('a.asar', 'dir1'); const r = fs.realpathSync.native(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('returns real path of a linked file', () => { const parent = fs.realpathSync.native(asarDir); const p = path.join('a.asar', 'link2', 'link1'); const r = fs.realpathSync.native(path.join(parent, p)); expect(r).to.equal(path.join(parent, 'a.asar', 'file1')); }); itremote('returns real path of a linked directory', () => { const parent = fs.realpathSync.native(asarDir); const p = path.join('a.asar', 'link2', 'link2'); const r = fs.realpathSync.native(path.join(parent, p)); expect(r).to.equal(path.join(parent, 'a.asar', 'dir1')); }); itremote('returns real path of an unpacked file', () => { const parent = fs.realpathSync.native(asarDir); const p = path.join('unpack.asar', 'a.txt'); const r = fs.realpathSync.native(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('throws ENOENT error when can not find file', () => { const parent = fs.realpathSync.native(asarDir); const p = path.join('a.asar', 'not-exist'); expect(() => { fs.realpathSync.native(path.join(parent, p)); }).to.throw(/ENOENT/); }); }); describe('fs.realpath', () => { itremote('returns real path root', async () => { const parent = fs.realpathSync(asarDir); const p = 'a.asar'; const r = await promisify(fs.realpath)(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('returns real path of a normal file', async () => { const parent = fs.realpathSync(asarDir); const p = path.join('a.asar', 'file1'); const r = await promisify(fs.realpath)(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('returns real path of a normal directory', async () => { const parent = fs.realpathSync(asarDir); const p = path.join('a.asar', 'dir1'); const r = await promisify(fs.realpath)(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('returns real path of a linked file', async () => { const parent = fs.realpathSync(asarDir); const p = path.join('a.asar', 'link2', 'link1'); const r = await promisify(fs.realpath)(path.join(parent, p)); expect(r).to.equal(path.join(parent, 'a.asar', 'file1')); }); itremote('returns real path of a linked directory', async () => { const parent = fs.realpathSync(asarDir); const p = path.join('a.asar', 'link2', 'link2'); const r = await promisify(fs.realpath)(path.join(parent, p)); expect(r).to.equal(path.join(parent, 'a.asar', 'dir1')); }); itremote('returns real path of an unpacked file', async () => { const parent = fs.realpathSync(asarDir); const p = path.join('unpack.asar', 'a.txt'); const r = await promisify(fs.realpath)(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('throws ENOENT error when can not find file', async () => { const parent = fs.realpathSync(asarDir); const p = path.join('a.asar', 'not-exist'); const err = await new Promise<any>(resolve => fs.realpath(path.join(parent, p), resolve)); expect(err.code).to.equal('ENOENT'); }); }); describe('fs.promises.realpath', () => { itremote('returns real path root', async () => { const parent = fs.realpathSync(asarDir); const p = 'a.asar'; const r = await fs.promises.realpath(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('returns real path of a normal file', async () => { const parent = fs.realpathSync(asarDir); const p = path.join('a.asar', 'file1'); const r = await fs.promises.realpath(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('returns real path of a normal directory', async () => { const parent = fs.realpathSync(asarDir); const p = path.join('a.asar', 'dir1'); const r = await fs.promises.realpath(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('returns real path of a linked file', async () => { const parent = fs.realpathSync(asarDir); const p = path.join('a.asar', 'link2', 'link1'); const r = await fs.promises.realpath(path.join(parent, p)); expect(r).to.equal(path.join(parent, 'a.asar', 'file1')); }); itremote('returns real path of a linked directory', async () => { const parent = fs.realpathSync(asarDir); const p = path.join('a.asar', 'link2', 'link2'); const r = await fs.promises.realpath(path.join(parent, p)); expect(r).to.equal(path.join(parent, 'a.asar', 'dir1')); }); itremote('returns real path of an unpacked file', async () => { const parent = fs.realpathSync(asarDir); const p = path.join('unpack.asar', 'a.txt'); const r = await fs.promises.realpath(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('throws ENOENT error when can not find file', async () => { const parent = fs.realpathSync(asarDir); const p = path.join('a.asar', 'not-exist'); await expectToThrowErrorWithCode(() => fs.promises.realpath(path.join(parent, p)), 'ENOENT'); }); }); describe('fs.realpath.native', () => { itremote('returns real path root', async () => { const parent = fs.realpathSync.native(asarDir); const p = 'a.asar'; const r = await promisify(fs.realpath.native)(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('returns real path of a normal file', async () => { const parent = fs.realpathSync.native(asarDir); const p = path.join('a.asar', 'file1'); const r = await promisify(fs.realpath.native)(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('returns real path of a normal directory', async () => { const parent = fs.realpathSync.native(asarDir); const p = path.join('a.asar', 'dir1'); const r = await promisify(fs.realpath.native)(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('returns real path of a linked file', async () => { const parent = fs.realpathSync.native(asarDir); const p = path.join('a.asar', 'link2', 'link1'); const r = await promisify(fs.realpath.native)(path.join(parent, p)); expect(r).to.equal(path.join(parent, 'a.asar', 'file1')); }); itremote('returns real path of a linked directory', async () => { const parent = fs.realpathSync.native(asarDir); const p = path.join('a.asar', 'link2', 'link2'); const r = await promisify(fs.realpath.native)(path.join(parent, p)); expect(r).to.equal(path.join(parent, 'a.asar', 'dir1')); }); itremote('returns real path of an unpacked file', async () => { const parent = fs.realpathSync.native(asarDir); const p = path.join('unpack.asar', 'a.txt'); const r = await promisify(fs.realpath.native)(path.join(parent, p)); expect(r).to.equal(path.join(parent, p)); }); itremote('throws ENOENT error when can not find file', async () => { const parent = fs.realpathSync.native(asarDir); const p = path.join('a.asar', 'not-exist'); const err = await new Promise<any>(resolve => fs.realpath.native(path.join(parent, p), resolve)); expect(err.code).to.equal('ENOENT'); }); }); describe('fs.readdirSync', function () { itremote('reads dirs from root', function () { const p = path.join(asarDir, 'a.asar'); const dirs = fs.readdirSync(p); expect(dirs).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']); }); itremote('reads dirs from a normal dir', function () { const p = path.join(asarDir, 'a.asar', 'dir1'); const dirs = fs.readdirSync(p); expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']); }); itremote('supports withFileTypes', function () { const p = path.join(asarDir, 'a.asar'); const dirs = fs.readdirSync(p, { withFileTypes: true }); for (const dir of dirs) { expect(dir).to.be.an.instanceof(fs.Dirent); } const names = dirs.map(a => a.name); expect(names).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']); }); itremote('supports withFileTypes for a deep directory', function () { const p = path.join(asarDir, 'a.asar', 'dir3'); const dirs = fs.readdirSync(p, { withFileTypes: true }); for (const dir of dirs) { expect(dir).to.be.an.instanceof(fs.Dirent); } const names = dirs.map(a => a.name); expect(names).to.deep.equal(['file1', 'file2', 'file3']); }); itremote('reads dirs from a linked dir', function () { const p = path.join(asarDir, 'a.asar', 'link2', 'link2'); const dirs = fs.readdirSync(p); expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']); }); itremote('throws ENOENT error when can not find file', function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); expect(() => { fs.readdirSync(p); }).to.throw(/ENOENT/); }); }); describe('fs.readdir', function () { itremote('reads dirs from root', async () => { const p = path.join(asarDir, 'a.asar'); const dirs = await promisify(fs.readdir)(p); expect(dirs).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']); }); itremote('supports withFileTypes', async () => { const p = path.join(asarDir, 'a.asar'); const dirs = await promisify(fs.readdir)(p, { withFileTypes: true }); for (const dir of dirs) { expect(dir).to.be.an.instanceof(fs.Dirent); } const names = dirs.map((a: any) => a.name); expect(names).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']); }); itremote('reads dirs from a normal dir', async () => { const p = path.join(asarDir, 'a.asar', 'dir1'); const dirs = await promisify(fs.readdir)(p); expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']); }); itremote('reads dirs from a linked dir', async () => { const p = path.join(asarDir, 'a.asar', 'link2', 'link2'); const dirs = await promisify(fs.readdir)(p); expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']); }); itremote('throws ENOENT error when can not find file', async () => { const p = path.join(asarDir, 'a.asar', 'not-exist'); const err = await new Promise<any>(resolve => fs.readdir(p, resolve)); expect(err.code).to.equal('ENOENT'); }); it('handles null for options', function (done) { const p = path.join(asarDir, 'a.asar', 'dir1'); fs.readdir(p, null, function (err, dirs) { try { expect(err).to.be.null(); expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']); done(); } catch (e) { done(e); } }); }); it('handles undefined for options', function (done) { const p = path.join(asarDir, 'a.asar', 'dir1'); fs.readdir(p, undefined, function (err, dirs) { try { expect(err).to.be.null(); expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']); done(); } catch (e) { done(e); } }); }); }); describe('fs.promises.readdir', function () { itremote('reads dirs from root', async function () { const p = path.join(asarDir, 'a.asar'); const dirs = await fs.promises.readdir(p); expect(dirs).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']); }); itremote('supports withFileTypes', async function () { const p = path.join(asarDir, 'a.asar'); const dirs = await fs.promises.readdir(p, { withFileTypes: true }); for (const dir of dirs) { expect(dir).to.be.an.instanceof(fs.Dirent); } const names = dirs.map(a => a.name); expect(names).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']); }); itremote('reads dirs from a normal dir', async function () { const p = path.join(asarDir, 'a.asar', 'dir1'); const dirs = await fs.promises.readdir(p); expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']); }); itremote('reads dirs from a linked dir', async function () { const p = path.join(asarDir, 'a.asar', 'link2', 'link2'); const dirs = await fs.promises.readdir(p); expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']); }); itremote('throws ENOENT error when can not find file', async function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); await expectToThrowErrorWithCode(() => fs.promises.readdir(p), 'ENOENT'); }); }); describe('fs.openSync', function () { itremote('opens a normal/linked/under-linked-directory file', function () { const ref2 = ['file1', 'link1', path.join('link2', 'file1')]; for (let j = 0, len = ref2.length; j < len; j++) { const file = ref2[j]; const p = path.join(asarDir, 'a.asar', file); const fd = fs.openSync(p, 'r'); const buffer = Buffer.alloc(6); fs.readSync(fd, buffer, 0, 6, 0); expect(String(buffer).trim()).to.equal('file1'); fs.closeSync(fd); } }); itremote('throws ENOENT error when can not find file', function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); expect(() => { (fs.openSync as any)(p); }).to.throw(/ENOENT/); }); }); describe('fs.open', function () { itremote('opens a normal file', async function () { const p = path.join(asarDir, 'a.asar', 'file1'); const fd = await promisify(fs.open)(p, 'r'); const buffer = Buffer.alloc(6); await promisify(fs.read)(fd, buffer, 0, 6, 0); expect(String(buffer).trim()).to.equal('file1'); await promisify(fs.close)(fd); }); itremote('throws ENOENT error when can not find file', async function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); const err = await new Promise<any>(resolve => fs.open(p, 'r', resolve)); expect(err.code).to.equal('ENOENT'); }); }); describe('fs.promises.open', function () { itremote('opens a normal file', async function () { const p = path.join(asarDir, 'a.asar', 'file1'); const fh = await fs.promises.open(p, 'r'); const buffer = Buffer.alloc(6); await fh.read(buffer, 0, 6, 0); expect(String(buffer).trim()).to.equal('file1'); await fh.close(); }); itremote('throws ENOENT error when can not find file', async function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); await expectToThrowErrorWithCode(() => fs.promises.open(p, 'r'), 'ENOENT'); }); }); describe('fs.mkdir', function () { itremote('throws error when calling inside asar archive', async function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); const err = await new Promise<any>(resolve => fs.mkdir(p, resolve)); expect(err.code).to.equal('ENOTDIR'); }); }); describe('fs.promises.mkdir', function () { itremote('throws error when calling inside asar archive', async function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); await expectToThrowErrorWithCode(() => fs.promises.mkdir(p), 'ENOTDIR'); }); }); describe('fs.mkdirSync', function () { itremote('throws error when calling inside asar archive', function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); expect(() => { fs.mkdirSync(p); }).to.throw(/ENOTDIR/); }); }); describe('fs.exists', function () { itremote('handles an existing file', async function () { const p = path.join(asarDir, 'a.asar', 'file1'); const exists = await new Promise(resolve => fs.exists(p, resolve)); expect(exists).to.be.true(); }); itremote('handles a non-existent file', async function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); const exists = await new Promise(resolve => fs.exists(p, resolve)); expect(exists).to.be.false(); }); itremote('promisified version handles an existing file', async () => { const p = path.join(asarDir, 'a.asar', 'file1'); const exists = await require('node:util').promisify(fs.exists)(p); expect(exists).to.be.true(); }); itremote('promisified version handles a non-existent file', async function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); const exists = await require('node:util').promisify(fs.exists)(p); expect(exists).to.be.false(); }); }); describe('fs.existsSync', function () { itremote('handles an existing file', function () { const p = path.join(asarDir, 'a.asar', 'file1'); expect(fs.existsSync(p)).to.be.true(); }); itremote('handles a non-existent file', function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); expect(fs.existsSync(p)).to.be.false(); }); }); describe('fs.access', function () { itremote('accesses a normal file', async function () { const p = path.join(asarDir, 'a.asar', 'file1'); await promisify(fs.access)(p); }); itremote('throws an error when called with write mode', async function () { const p = path.join(asarDir, 'a.asar', 'file1'); const err = await new Promise<any>(resolve => fs.access(p, fs.constants.R_OK | fs.constants.W_OK, resolve)); expect(err.code).to.equal('EACCES'); }); itremote('throws an error when called on non-existent file', async function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); const err = await new Promise<any>(resolve => fs.access(p, fs.constants.R_OK | fs.constants.W_OK, resolve)); expect(err.code).to.equal('ENOENT'); }); itremote('allows write mode for unpacked files', async function () { const p = path.join(asarDir, 'unpack.asar', 'a.txt'); await promisify(fs.access)(p, fs.constants.R_OK | fs.constants.W_OK); }); }); describe('fs.promises.access', function () { itremote('accesses a normal file', async function () { const p = path.join(asarDir, 'a.asar', 'file1'); await fs.promises.access(p); }); itremote('throws an error when called with write mode', async function () { const p = path.join(asarDir, 'a.asar', 'file1'); await expectToThrowErrorWithCode(() => fs.promises.access(p, fs.constants.R_OK | fs.constants.W_OK), 'EACCES'); }); itremote('throws an error when called on non-existent file', async function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); await expectToThrowErrorWithCode(() => fs.promises.access(p), 'ENOENT'); }); itremote('allows write mode for unpacked files', async function () { const p = path.join(asarDir, 'unpack.asar', 'a.txt'); await fs.promises.access(p, fs.constants.R_OK | fs.constants.W_OK); }); }); describe('fs.accessSync', function () { itremote('accesses a normal file', function () { const p = path.join(asarDir, 'a.asar', 'file1'); expect(() => { fs.accessSync(p); }).to.not.throw(); }); itremote('throws an error when called with write mode', function () { const p = path.join(asarDir, 'a.asar', 'file1'); expect(() => { fs.accessSync(p, fs.constants.R_OK | fs.constants.W_OK); }).to.throw(/EACCES/); }); itremote('throws an error when called on non-existent file', function () { const p = path.join(asarDir, 'a.asar', 'not-exist'); expect(() => { fs.accessSync(p); }).to.throw(/ENOENT/); }); itremote('allows write mode for unpacked files', function () { const p = path.join(asarDir, 'unpack.asar', 'a.txt'); expect(() => { fs.accessSync(p, fs.constants.R_OK | fs.constants.W_OK); }).to.not.throw(); }); }); function generateSpecs (childProcess: string) { describe(`${childProcess}.fork`, function () { itremote('opens a normal js file', async function (childProcess: string) { const child = require(childProcess).fork(path.join(asarDir, 'a.asar', 'ping.js')); child.send('message'); const msg = await new Promise(resolve => child.once('message', resolve)); expect(msg).to.equal('message'); }, [childProcess]); itremote('supports asar in the forked js', async function (childProcess: string, fixtures: string) { const file = path.join(asarDir, 'a.asar', 'file1'); const child = require(childProcess).fork(path.join(fixtures, 'module', 'asar.js')); child.send(file); const content = await new Promise(resolve => child.once('message', resolve)); expect(content).to.equal(fs.readFileSync(file).toString()); }, [childProcess, fixtures]); }); describe(`${childProcess}.exec`, function () { itremote('should not try to extract the command if there is a reference to a file inside an .asar', async function (childProcess: string) { const echo = path.join(asarDir, 'echo.asar', 'echo'); const stdout = await promisify(require(childProcess).exec)('echo ' + echo + ' foo bar'); expect(stdout.toString().replaceAll('\r', '')).to.equal(echo + ' foo bar\n'); }, [childProcess]); }); describe(`${childProcess}.execSync`, function () { itremote('should not try to extract the command if there is a reference to a file inside an .asar', async function (childProcess: string) { const echo = path.join(asarDir, 'echo.asar', 'echo'); const stdout = require(childProcess).execSync('echo ' + echo + ' foo bar'); expect(stdout.toString().replaceAll('\r', '')).to.equal(echo + ' foo bar\n'); }, [childProcess]); }); ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')(`${childProcess}.execFile`, function () { itremote('executes binaries', async function (childProcess: string) { const echo = path.join(asarDir, 'echo.asar', 'echo'); const stdout = await promisify(require(childProcess).execFile)(echo, ['test']); expect(stdout).to.equal('test\n'); }, [childProcess]); itremote('executes binaries without callback', async function (childProcess: string) { const echo = path.join(asarDir, 'echo.asar', 'echo'); const process = require(childProcess).execFile(echo, ['test']); const code = await new Promise(resolve => process.once('close', resolve)); expect(code).to.equal(0); process.on('error', function () { throw new Error('error'); }); }, [childProcess]); itremote('execFileSync executes binaries', function (childProcess: string) { const echo = path.join(asarDir, 'echo.asar', 'echo'); const output = require(childProcess).execFileSync(echo, ['test']); expect(String(output)).to.equal('test\n'); }, [childProcess]); }); } generateSpecs('child_process'); generateSpecs('node:child_process'); describe('internalModuleReadJSON', function () { itremote('reads a normal file', function () { const { internalModuleReadJSON } = (process as any).binding('fs'); const file1 = path.join(asarDir, 'a.asar', 'file1'); const [s1, c1] = internalModuleReadJSON(file1); expect([s1.toString().trim(), c1]).to.eql(['file1', true]); const file2 = path.join(asarDir, 'a.asar', 'file2'); const [s2, c2] = internalModuleReadJSON(file2); expect([s2.toString().trim(), c2]).to.eql(['file2', true]); const file3 = path.join(asarDir, 'a.asar', 'file3'); const [s3, c3] = internalModuleReadJSON(file3); expect([s3.toString().trim(), c3]).to.eql(['file3', true]); }); itremote('reads a normal file with unpacked files', function () { const { internalModuleReadJSON } = (process as any).binding('fs'); const p = path.join(asarDir, 'unpack.asar', 'a.txt'); const [s, c] = internalModuleReadJSON(p); expect([s.toString().trim(), c]).to.eql(['a', true]); }); }); describe('util.promisify', function () { itremote('can promisify all fs functions', function () { const originalFs = require('original-fs'); const util = require('node:util'); for (const [propertyName, originalValue] of Object.entries(originalFs)) { // Some properties exist but have a value of `undefined` on some platforms. // E.g. `fs.lchmod`, which in only available on MacOS, see // https://nodejs.org/docs/latest-v10.x/api/fs.html#fs_fs_lchmod_path_mode_callback // Also check for `null`s, `hasOwnProperty()` can't handle them. if (typeof originalValue === 'undefined' || originalValue === null) continue; if (Object.hasOwn(originalValue, util.promisify.custom)) { expect(fs).to.have.own.property(propertyName) .that.has.own.property(util.promisify.custom); } } }); }); describe('process.noAsar', function () { const errorName = process.platform === 'win32' ? 'ENOENT' : 'ENOTDIR'; beforeEach(async function () { return (await getRemoteContext()).webContents.executeJavaScript(` process.noAsar = true; `); }); afterEach(async function () { return (await getRemoteContext()).webContents.executeJavaScript(` process.noAsar = false; `); }); itremote('disables asar support in sync API', function (errorName: string) { const file = path.join(asarDir, 'a.asar', 'file1'); const dir = path.join(asarDir, 'a.asar', 'dir1'); console.log(1); expect(() => { fs.readFileSync(file); }).to.throw(new RegExp(errorName)); expect(() => { fs.lstatSync(file); }).to.throw(new RegExp(errorName)); expect(() => { fs.realpathSync(file); }).to.throw(new RegExp(errorName)); expect(() => { fs.readdirSync(dir); }).to.throw(new RegExp(errorName)); }, [errorName]); itremote('disables asar support in async API', async function (errorName: string) { const file = path.join(asarDir, 'a.asar', 'file1'); const dir = path.join(asarDir, 'a.asar', 'dir1'); await new Promise<void>(resolve => { fs.readFile(file, function (error) { expect(error?.code).to.equal(errorName); fs.lstat(file, function (error) { expect(error?.code).to.equal(errorName); fs.realpath(file, function (error) { expect(error?.code).to.equal(errorName); fs.readdir(dir, function (error) { expect(error?.code).to.equal(errorName); resolve(); }); }); }); }); }); }, [errorName]); itremote('disables asar support in promises API', async function (errorName: string) { const file = path.join(asarDir, 'a.asar', 'file1'); const dir = path.join(asarDir, 'a.asar', 'dir1'); await expect(fs.promises.readFile(file)).to.be.eventually.rejectedWith(Error, new RegExp(errorName)); await expect(fs.promises.lstat(file)).to.be.eventually.rejectedWith(Error, new RegExp(errorName)); await expect(fs.promises.realpath(file)).to.be.eventually.rejectedWith(Error, new RegExp(errorName)); await expect(fs.promises.readdir(dir)).to.be.eventually.rejectedWith(Error, new RegExp(errorName)); }, [errorName]); itremote('treats *.asar as normal file', function () { const originalFs = require('original-fs'); const asar = path.join(asarDir, 'a.asar'); const content1 = fs.readFileSync(asar); const content2 = originalFs.readFileSync(asar); expect(content1.compare(content2)).to.equal(0); expect(() => { fs.readdirSync(asar); }).to.throw(/ENOTDIR/); }); itremote('is reset to its original value when execSync throws an error', function () { process.noAsar = false; expect(() => { require('node:child_process').execSync(path.join(__dirname, 'does-not-exist.txt')); }).to.throw(); expect(process.noAsar).to.be.false(); }); }); /* describe('process.env.ELECTRON_NO_ASAR', function () { itremote('disables asar support in forked processes', function (done) { const forked = ChildProcess.fork(path.join(__dirname, 'fixtures', 'module', 'no-asar.js'), [], { env: { ELECTRON_NO_ASAR: true } }); forked.on('message', function (stats) { try { expect(stats.isFile).to.be.true(); expect(stats.size).to.equal(3458); done(); } catch (e) { done(e); } }); }); itremote('disables asar support in spawned processes', function (done) { const spawned = ChildProcess.spawn(process.execPath, [path.join(__dirname, 'fixtures', 'module', 'no-asar.js')], { env: { ELECTRON_NO_ASAR: true, ELECTRON_RUN_AS_NODE: true } }); let output = ''; spawned.stdout.on('data', function (data) { output += data; }); spawned.stdout.on('close', function () { try { const stats = JSON.parse(output); expect(stats.isFile).to.be.true(); expect(stats.size).to.equal(3458); done(); } catch (e) { done(e); } }); }); }); */ }); describe('asar protocol', function () { itremote('can request a file in package', async function () { const p = path.resolve(asarDir, 'a.asar', 'file1'); const response = await fetch('file://' + p); const data = await response.text(); expect(data.trim()).to.equal('file1'); }); itremote('can request a file in package with unpacked files', async function () { const p = path.resolve(asarDir, 'unpack.asar', 'a.txt'); const response = await fetch('file://' + p); const data = await response.text(); expect(data.trim()).to.equal('a'); }); itremote('can request a linked file in package', async function () { const p = path.resolve(asarDir, 'a.asar', 'link2', 'link1'); const response = await fetch('file://' + p); const data = await response.text(); expect(data.trim()).to.equal('file1'); }); itremote('can request a file in filesystem', async function () { const p = path.resolve(asarDir, 'file'); const response = await fetch('file://' + p); const data = await response.text(); expect(data.trim()).to.equal('file'); }); itremote('gets error when file is not found', async function () { const p = path.resolve(asarDir, 'a.asar', 'no-exist'); try { const response = await fetch('file://' + p); expect(response.status).to.equal(404); } catch (error: any) { expect(error.message).to.equal('Failed to fetch'); } }); }); describe('original-fs module', function () { itremote('treats .asar as file', function () { const file = path.join(asarDir, 'a.asar'); const originalFs = require('original-fs'); const stats = originalFs.statSync(file); expect(stats.isFile()).to.be.true(); }); /* it('is available in forked scripts', async function () { const child = ChildProcess.fork(path.join(fixtures, 'module', 'original-fs.js')); const message = once(child, 'message'); child.send('message'); const [msg] = await message; expect(msg).to.equal('object'); }); */ itremote('can be used with streams', () => { const originalFs = require('original-fs'); originalFs.createReadStream(path.join(asarDir, 'a.asar')); }); itremote('can recursively delete a directory with an asar file in itremote', () => { const deleteDir = path.join(asarDir, 'deleteme'); fs.mkdirSync(deleteDir); const originalFs = require('original-fs'); originalFs.rmdirSync(deleteDir, { recursive: true }); expect(fs.existsSync(deleteDir)).to.be.false(); }); itremote('has the same APIs as fs', function () { expect(Object.keys(require('node:fs'))).to.deep.equal(Object.keys(require('original-fs'))); expect(Object.keys(require('node:fs').promises)).to.deep.equal(Object.keys(require('original-fs').promises)); }); }); describe('graceful-fs module', function () { itremote('recognize asar archives', function () { const gfs = require('graceful-fs'); const p = path.join(asarDir, 'a.asar', 'link1'); expect(gfs.readFileSync(p).toString().trim()).to.equal('file1'); }); itremote('does not touch global fs object', function () { const gfs = require('graceful-fs'); expect(fs.readdir).to.not.equal(gfs.readdir); }); }); describe('mkdirp module', function () { itremote('throws error when calling inside asar archive', function () { const mkdirp = require('mkdirp'); const p = path.join(asarDir, 'a.asar', 'not-exist'); expect(() => { mkdirp.sync(p); }).to.throw(/ENOTDIR/); }); }); describe('native-image', function () { itremote('reads image from asar archive', function () { const p = path.join(asarDir, 'logo.asar', 'logo.png'); const logo = require('electron').nativeImage.createFromPath(p); expect(logo.getSize()).to.deep.equal({ width: 55, height: 55 }); }); itremote('reads image from asar archive with unpacked files', function () { const p = path.join(asarDir, 'unpack.asar', 'atom.png'); const logo = require('electron').nativeImage.createFromPath(p); expect(logo.getSize()).to.deep.equal({ width: 1024, height: 1024 }); }); }); });
closed
electron/electron
https://github.com/electron/electron
38,955
[Bug]: `BrowserWindow.isVisible()` doesn't take into account occlusion state
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? macOS ### Operating System Version Ventura 13.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I found out that BrowserWindow on Mac started to take into account page occlusion state since this PR: https://github.com/electron/electron/pull/17463/files BrowserWindow.isVisible() should return false if window is occluded by another window. ### Actual Behavior BrowserWindow.isVisible() always returns true unless minimized. ### Testcase Gist URL https://gist.github.com/Imperat/0ecffacee8d1386258d67a91e0017644 ### Additional Information Provided fiddle is best way to reproduce the issue: move browser window to the corner (or another screen) and open another app on top of browserWindow. Observe that in fiddle console "visible true" still logged.
https://github.com/electron/electron/issues/38955
https://github.com/electron/electron/pull/38982
08236f7a9e9d664513e2b76b54b9bea003101e5d
768ece6b54f78e65efbea2c3fd39eea30e48332b
2023-06-30T00:50:25Z
c++
2024-02-06T10:30:35Z
docs/api/browser-window.md
# BrowserWindow > Create and control browser windows. Process: [Main](../glossary.md#main-process) This module cannot be used until the `ready` event of the `app` module is emitted. ```js // In the main process. const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) // Load a remote URL win.loadURL('https://github.com') // Or load a local HTML file win.loadFile('index.html') ``` ## Window customization The `BrowserWindow` class exposes various ways to modify the look and behavior of your app's windows. For more details, see the [Window Customization](../tutorial/window-customization.md) tutorial. ## Showing the window gracefully When loading a page in the window directly, users may see the page load incrementally, which is not a good experience for a native app. To make the window display without a visual flash, there are two solutions for different situations. ### Using the `ready-to-show` event While loading the page, the `ready-to-show` event will be emitted when the renderer process has rendered the page for the first time if the window has not been shown yet. Showing the window after this event will have no visual flash: ```js const { BrowserWindow } = require('electron') const win = new BrowserWindow({ show: false }) win.once('ready-to-show', () => { win.show() }) ``` This event is usually emitted after the `did-finish-load` event, but for pages with many remote resources, it may be emitted before the `did-finish-load` event. Please note that using this event implies that the renderer will be considered "visible" and paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false` ### Setting the `backgroundColor` property For a complex app, the `ready-to-show` event could be emitted too late, making the app feel slow. In this case, it is recommended to show the window immediately, and use a `backgroundColor` close to your app's background: ```js const { BrowserWindow } = require('electron') const win = new BrowserWindow({ backgroundColor: '#2e2c29' }) win.loadURL('https://github.com') ``` Note that even for apps that use `ready-to-show` event, it is still recommended to set `backgroundColor` to make the app feel more native. Some examples of valid `backgroundColor` values include: ```js const win = new BrowserWindow() win.setBackgroundColor('hsl(230, 100%, 50%)') win.setBackgroundColor('rgb(255, 145, 145)') win.setBackgroundColor('#ff00a3') win.setBackgroundColor('blueviolet') ``` For more information about these color types see valid options in [win.setBackgroundColor](browser-window.md#winsetbackgroundcolorbackgroundcolor). ## Parent and child windows By using `parent` option, you can create child windows: ```js const { BrowserWindow } = require('electron') const top = new BrowserWindow() const child = new BrowserWindow({ parent: top }) child.show() top.show() ``` The `child` window will always show on top of the `top` window. ## Modal windows A modal window is a child window that disables parent window. To create a modal window, you have to set both the `parent` and `modal` options: ```js const { BrowserWindow } = require('electron') const top = new BrowserWindow() const child = new BrowserWindow({ parent: top, modal: true, show: false }) child.loadURL('https://github.com') child.once('ready-to-show', () => { child.show() }) ``` ## Page visibility The [Page Visibility API][page-visibility-api] works as follows: * On all platforms, the visibility state tracks whether the window is hidden/minimized or not. * Additionally, on macOS, the visibility state also tracks the window occlusion state. If the window is occluded (i.e. fully covered) by another window, the visibility state will be `hidden`. On other platforms, the visibility state will be `hidden` only when the window is minimized or explicitly hidden with `win.hide()`. * If a `BrowserWindow` is created with `show: false`, the initial visibility state will be `visible` despite the window actually being hidden. * If `backgroundThrottling` is disabled, the visibility state will remain `visible` even if the window is minimized, occluded, or hidden. It is recommended that you pause expensive operations when the visibility state is `hidden` in order to minimize power consumption. ## Platform notices * On macOS modal windows will be displayed as sheets attached to the parent window. * On macOS the child windows will keep the relative position to parent window when parent window moves, while on Windows and Linux child windows will not move. * On Linux the type of modal windows will be changed to `dialog`. * On Linux many desktop environments do not support hiding a modal window. ## Class: BrowserWindow extends `BaseWindow` > Create and control browser windows. Process: [Main](../glossary.md#main-process) `BrowserWindow` is an [EventEmitter][event-emitter]. It creates a new `BrowserWindow` with native properties as set by the `options`. ### `new BrowserWindow([options])` * `options` [BrowserWindowConstructorOptions](structures/browser-window-options.md?inline) (optional) ### Instance Events Objects created with `new BrowserWindow` emit the following events: **Note:** Some events are only available on specific operating systems and are labeled as such. #### Event: 'page-title-updated' Returns: * `event` Event * `title` string * `explicitSet` boolean Emitted when the document changed its title, calling `event.preventDefault()` will prevent the native window's title from changing. `explicitSet` is false when title is synthesized from file URL. #### Event: 'close' Returns: * `event` Event Emitted when the window is going to be closed. It's emitted before the `beforeunload` and `unload` event of the DOM. Calling `event.preventDefault()` will cancel the close. Usually you would want to use the `beforeunload` handler to decide whether the window should be closed, which will also be called when the window is reloaded. In Electron, returning any value other than `undefined` would cancel the close. For example: ```js window.onbeforeunload = (e) => { console.log('I do not want to be closed') // Unlike usual browsers that a message box will be prompted to users, returning // a non-void value will silently cancel the close. // It is recommended to use the dialog API to let the user confirm closing the // application. e.returnValue = false } ``` _**Note**: There is a subtle difference between the behaviors of `window.onbeforeunload = handler` and `window.addEventListener('beforeunload', handler)`. It is recommended to always set the `event.returnValue` explicitly, instead of only returning a value, as the former works more consistently within Electron._ #### Event: 'closed' Emitted when the window is closed. After you have received this event you should remove the reference to the window and avoid using it any more. #### Event: 'session-end' _Windows_ Emitted when window session is going to end due to force shutdown or machine restart or session log off. #### Event: 'unresponsive' Emitted when the web page becomes unresponsive. #### Event: 'responsive' Emitted when the unresponsive web page becomes responsive again. #### Event: 'blur' Emitted when the window loses focus. #### Event: 'focus' Emitted when the window gains focus. #### Event: 'show' Emitted when the window is shown. #### Event: 'hide' Emitted when the window is hidden. #### Event: 'ready-to-show' Emitted when the web page has been rendered (while not being shown) and window can be displayed without a visual flash. Please note that using this event implies that the renderer will be considered "visible" and paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false` #### Event: 'maximize' Emitted when window is maximized. #### Event: 'unmaximize' Emitted when the window exits from a maximized state. #### Event: 'minimize' Emitted when the window is minimized. #### Event: 'restore' Emitted when the window is restored from a minimized state. #### Event: 'will-resize' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Size the window is being resized to. * `details` Object * `edge` (string) - The edge of the window being dragged for resizing. Can be `bottom`, `left`, `right`, `top-left`, `top-right`, `bottom-left` or `bottom-right`. Emitted before the window is resized. Calling `event.preventDefault()` will prevent the window from being resized. Note that this is only emitted when the window is being resized manually. Resizing the window with `setBounds`/`setSize` will not emit this event. The possible values and behaviors of the `edge` option are platform dependent. Possible values are: * On Windows, possible values are `bottom`, `top`, `left`, `right`, `top-left`, `top-right`, `bottom-left`, `bottom-right`. * On macOS, possible values are `bottom` and `right`. * The value `bottom` is used to denote vertical resizing. * The value `right` is used to denote horizontal resizing. #### Event: 'resize' Emitted after the window has been resized. #### Event: 'resized' _macOS_ _Windows_ Emitted once when the window has finished being resized. This is usually emitted when the window has been resized manually. On macOS, resizing the window with `setBounds`/`setSize` and setting the `animate` parameter to `true` will also emit this event once resizing has finished. #### Event: 'will-move' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Location the window is being moved to. Emitted before the window is moved. On Windows, calling `event.preventDefault()` will prevent the window from being moved. Note that this is only emitted when the window is being moved manually. Moving the window with `setPosition`/`setBounds`/`center` will not emit this event. #### Event: 'move' Emitted when the window is being moved to a new position. #### Event: 'moved' _macOS_ _Windows_ Emitted once when the window is moved to a new position. **Note**: On macOS this event is an alias of `move`. #### Event: 'enter-full-screen' Emitted when the window enters a full-screen state. #### Event: 'leave-full-screen' Emitted when the window leaves a full-screen state. #### Event: 'enter-html-full-screen' Emitted when the window enters a full-screen state triggered by HTML API. #### Event: 'leave-html-full-screen' Emitted when the window leaves a full-screen state triggered by HTML API. #### Event: 'always-on-top-changed' Returns: * `event` Event * `isAlwaysOnTop` boolean Emitted when the window is set or unset to show always on top of other windows. #### Event: 'app-command' _Windows_ _Linux_ Returns: * `event` Event * `command` string Emitted when an [App Command](https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-appcommand) is invoked. These are typically related to keyboard media keys or browser commands, as well as the "Back" button built into some mice on Windows. Commands are lowercased, underscores are replaced with hyphens, and the `APPCOMMAND_` prefix is stripped off. e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`. ```js const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.on('app-command', (e, cmd) => { // Navigate the window back when the user hits their mouse back button if (cmd === 'browser-backward' && win.webContents.canGoBack()) { win.webContents.goBack() } }) ``` The following app commands are explicitly supported on Linux: * `browser-backward` * `browser-forward` #### Event: 'swipe' _macOS_ Returns: * `event` Event * `direction` string Emitted on 3-finger swipe. Possible directions are `up`, `right`, `down`, `left`. The method underlying this event is built to handle older macOS-style trackpad swiping, where the content on the screen doesn't move with the swipe. Most macOS trackpads are not configured to allow this kind of swiping anymore, so in order for it to emit properly the 'Swipe between pages' preference in `System Preferences > Trackpad > More Gestures` must be set to 'Swipe with two or three fingers'. #### Event: 'rotate-gesture' _macOS_ Returns: * `event` Event * `rotation` Float Emitted on trackpad rotation gesture. Continually emitted until rotation gesture is ended. The `rotation` value on each emission is the angle in degrees rotated since the last emission. The last emitted event upon a rotation gesture will always be of value `0`. Counter-clockwise rotation values are positive, while clockwise ones are negative. #### Event: 'sheet-begin' _macOS_ Emitted when the window opens a sheet. #### Event: 'sheet-end' _macOS_ Emitted when the window has closed a sheet. #### Event: 'new-window-for-tab' _macOS_ Emitted when the native new tab button is clicked. #### Event: 'system-context-menu' _Windows_ Returns: * `event` Event * `point` [Point](structures/point.md) - The screen coordinates the context menu was triggered at Emitted when the system context menu is triggered on the window, this is normally only triggered when the user right clicks on the non-client area of your window. This is the window titlebar or any area you have declared as `-webkit-app-region: drag` in a frameless window. Calling `event.preventDefault()` will prevent the menu from being displayed. ### Static Methods The `BrowserWindow` class has the following static methods: #### `BrowserWindow.getAllWindows()` Returns `BrowserWindow[]` - An array of all opened browser windows. #### `BrowserWindow.getFocusedWindow()` Returns `BrowserWindow | null` - The window that is focused in this application, otherwise returns `null`. #### `BrowserWindow.fromWebContents(webContents)` * `webContents` [WebContents](web-contents.md) Returns `BrowserWindow | null` - The window that owns the given `webContents` or `null` if the contents are not owned by a window. #### `BrowserWindow.fromBrowserView(browserView)` _Deprecated_ * `browserView` [BrowserView](browser-view.md) > **Note** > The `BrowserView` class is deprecated, and replaced by the new > [`WebContentsView`](web-contents-view.md) class. Returns `BrowserWindow | null` - The window that owns the given `browserView`. If the given view is not attached to any window, returns `null`. #### `BrowserWindow.fromId(id)` * `id` Integer Returns `BrowserWindow | null` - The window with the given `id`. ### Instance Properties Objects created with `new BrowserWindow` have the following properties: ```js const { BrowserWindow } = require('electron') // In this example `win` is our instance const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('https://github.com') ``` #### `win.webContents` _Readonly_ A `WebContents` object this window owns. All web page related events and operations will be done via it. See the [`webContents` documentation](web-contents.md) for its methods and events. #### `win.id` _Readonly_ A `Integer` property representing the unique ID of the window. Each ID is unique among all `BrowserWindow` instances of the entire Electron application. #### `win.tabbingIdentifier` _macOS_ _Readonly_ A `string` (optional) property that is equal to the `tabbingIdentifier` passed to the `BrowserWindow` constructor or `undefined` if none was set. #### `win.autoHideMenuBar` A `boolean` property that determines whether the window menu bar should hide itself automatically. Once set, the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, setting this property to `true` won't hide it immediately. #### `win.simpleFullScreen` A `boolean` property that determines whether the window is in simple (pre-Lion) fullscreen mode. #### `win.fullScreen` A `boolean` property that determines whether the window is in fullscreen mode. #### `win.focusable` _Windows_ _macOS_ A `boolean` property that determines whether the window is focusable. #### `win.visibleOnAllWorkspaces` _macOS_ _Linux_ A `boolean` property that determines whether the window is visible on all workspaces. **Note:** Always returns false on Windows. #### `win.shadow` A `boolean` property that determines whether the window has a shadow. #### `win.menuBarVisible` _Windows_ _Linux_ A `boolean` property that determines whether the menu bar should be visible. **Note:** If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.kiosk` A `boolean` property that determines whether the window is in kiosk mode. #### `win.documentEdited` _macOS_ A `boolean` property that specifies whether the window’s document has been edited. The icon in title bar will become gray when set to `true`. #### `win.representedFilename` _macOS_ A `string` property that determines the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.title` A `string` property that determines the title of the native window. **Note:** The title of the web page can be different from the title of the native window. #### `win.minimizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually minimized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.maximizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually maximized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.fullScreenable` A `boolean` property that determines whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.resizable` A `boolean` property that determines whether the window can be manually resized by user. #### `win.closable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually closed by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.movable` _macOS_ _Windows_ A `boolean` property that determines Whether the window can be moved by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.excludedFromShownWindowsMenu` _macOS_ A `boolean` property that determines whether the window is excluded from the application’s Windows menu. `false` by default. ```js @ts-expect-error=[11] const win = new BrowserWindow({ height: 600, width: 600 }) const template = [ { role: 'windowmenu' } ] win.excludedFromShownWindowsMenu = true const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) ``` #### `win.accessibleTitle` A `string` property that defines an alternative title provided only to accessibility tools such as screen readers. This string is not directly visible to users. ### Instance Methods Objects created with `new BrowserWindow` have the following instance methods: **Note:** Some methods are only available on specific operating systems and are labeled as such. #### `win.destroy()` Force closing the window, the `unload` and `beforeunload` event won't be emitted for the web page, and `close` event will also not be emitted for this window, but it guarantees the `closed` event will be emitted. #### `win.close()` Try to close the window. This has the same effect as a user manually clicking the close button of the window. The web page may cancel the close though. See the [close event](#event-close). #### `win.focus()` Focuses on the window. #### `win.blur()` Removes focus from the window. #### `win.isFocused()` Returns `boolean` - Whether the window is focused. #### `win.isDestroyed()` Returns `boolean` - Whether the window is destroyed. #### `win.show()` Shows and gives focus to the window. #### `win.showInactive()` Shows the window but doesn't focus on it. #### `win.hide()` Hides the window. #### `win.isVisible()` Returns `boolean` - Whether the window is visible to the user in the foreground of the app. #### `win.isModal()` Returns `boolean` - Whether current window is a modal window. #### `win.maximize()` Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already. #### `win.unmaximize()` Unmaximizes the window. #### `win.isMaximized()` Returns `boolean` - Whether the window is maximized. #### `win.minimize()` Minimizes the window. On some platforms the minimized window will be shown in the Dock. #### `win.restore()` Restores the window from minimized state to its previous state. #### `win.isMinimized()` Returns `boolean` - Whether the window is minimized. #### `win.setFullScreen(flag)` * `flag` boolean Sets whether the window should be in fullscreen mode. **Note:** On macOS, fullscreen transitions take place asynchronously. If further actions depend on the fullscreen state, use the ['enter-full-screen'](browser-window.md#event-enter-full-screen) or ['leave-full-screen'](browser-window.md#event-leave-full-screen) events. #### `win.isFullScreen()` Returns `boolean` - Whether the window is in fullscreen mode. #### `win.setSimpleFullScreen(flag)` _macOS_ * `flag` boolean Enters or leaves simple fullscreen mode. Simple fullscreen mode emulates the native fullscreen behavior found in versions of macOS prior to Lion (10.7). #### `win.isSimpleFullScreen()` _macOS_ Returns `boolean` - Whether the window is in simple (pre-Lion) fullscreen mode. #### `win.isNormal()` Returns `boolean` - Whether the window is in normal state (not maximized, not minimized, not in fullscreen mode). #### `win.setAspectRatio(aspectRatio[, extraSize])` * `aspectRatio` Float - The aspect ratio to maintain for some portion of the content view. * `extraSize` [Size](structures/size.md) (optional) _macOS_ - The extra size not to be included while maintaining the aspect ratio. This will make a window maintain an aspect ratio. The extra size allows a developer to have space, specified in pixels, not included within the aspect ratio calculations. This API already takes into account the difference between a window's size and its content size. Consider a normal window with an HD video player and associated controls. Perhaps there are 15 pixels of controls on the left edge, 25 pixels of controls on the right edge and 50 pixels of controls below the player. In order to maintain a 16:9 aspect ratio (standard aspect ratio for HD @1920x1080) within the player itself we would call this function with arguments of 16/9 and { width: 40, height: 50 }. The second argument doesn't care where the extra width and height are within the content view--only that they exist. Sum any extra width and height areas you have within the overall content view. The aspect ratio is not respected when window is resized programmatically with APIs like `win.setSize`. To reset an aspect ratio, pass 0 as the `aspectRatio` value: `win.setAspectRatio(0)`. #### `win.setBackgroundColor(backgroundColor)` * `backgroundColor` string - Color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type. Examples of valid `backgroundColor` values: * Hex * #fff (shorthand RGB) * #ffff (shorthand ARGB) * #ffffff (RGB) * #ffffffff (ARGB) * RGB * rgb\((\[\d]+),\s*(\[\d]+),\s*(\[\d]+)\) * e.g. rgb(255, 255, 255) * RGBA * rgba\((\[\d]+),\s*(\[\d]+),\s*(\[\d]+),\s*(\[\d.]+)\) * e.g. rgba(255, 255, 255, 1.0) * HSL * hsl\((-?\[\d.]+),\s*(\[\d.]+)%,\s*(\[\d.]+)%\) * e.g. hsl(200, 20%, 50%) * HSLA * hsla\((-?\[\d.]+),\s*(\[\d.]+)%,\s*(\[\d.]+)%,\s*(\[\d.]+)\) * e.g. hsla(200, 20%, 50%, 0.5) * Color name * Options are listed in [SkParseColor.cpp](https://source.chromium.org/chromium/chromium/src/+/main:third_party/skia/src/utils/SkParseColor.cpp;l=11-152;drc=eea4bf52cb0d55e2a39c828b017c80a5ee054148) * Similar to CSS Color Module Level 3 keywords, but case-sensitive. * e.g. `blueviolet` or `red` Sets the background color of the window. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property). #### `win.previewFile(path[, displayName])` _macOS_ * `path` string - The absolute path to the file to preview with QuickLook. This is important as Quick Look uses the file name and file extension on the path to determine the content type of the file to open. * `displayName` string (optional) - The name of the file to display on the Quick Look modal view. This is purely visual and does not affect the content type of the file. Defaults to `path`. Uses [Quick Look][quick-look] to preview a file at a given path. #### `win.closeFilePreview()` _macOS_ Closes the currently open [Quick Look][quick-look] panel. #### `win.setBounds(bounds[, animate])` * `bounds` Partial<[Rectangle](structures/rectangle.md)> * `animate` boolean (optional) _macOS_ Resizes and moves the window to the supplied bounds. Any properties that are not supplied will default to their current values. ```js const { BrowserWindow } = require('electron') const win = new BrowserWindow() // set all bounds properties win.setBounds({ x: 440, y: 225, width: 800, height: 600 }) // set a single bounds property win.setBounds({ width: 100 }) // { x: 440, y: 225, width: 100, height: 600 } console.log(win.getBounds()) ``` **Note:** On macOS, the y-coordinate value cannot be smaller than the [Tray](tray.md) height. The tray height has changed over time and depends on the operating system, but is between 20-40px. Passing a value lower than the tray height will result in a window that is flush to the tray. #### `win.getBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window as `Object`. **Note:** On macOS, the y-coordinate value returned will be at minimum the [Tray](tray.md) height. For example, calling `win.setBounds({ x: 25, y: 20, width: 800, height: 600 })` with a tray height of 38 means that `win.getBounds()` will return `{ x: 25, y: 38, width: 800, height: 600 }`. #### `win.getBackgroundColor()` Returns `string` - Gets the background color of the window in Hex (`#RRGGBB`) format. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property). **Note:** The alpha value is _not_ returned alongside the red, green, and blue values. #### `win.setContentBounds(bounds[, animate])` * `bounds` [Rectangle](structures/rectangle.md) * `animate` boolean (optional) _macOS_ Resizes and moves the window's client area (e.g. the web page) to the supplied bounds. #### `win.getContentBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window's client area as `Object`. #### `win.getNormalBounds()` Returns [`Rectangle`](structures/rectangle.md) - Contains the window bounds of the normal state **Note:** whatever the current state of the window : maximized, minimized or in fullscreen, this function always returns the position and size of the window in normal state. In normal state, getBounds and getNormalBounds returns the same [`Rectangle`](structures/rectangle.md). #### `win.setEnabled(enable)` * `enable` boolean Disable or enable the window. #### `win.isEnabled()` Returns `boolean` - whether the window is enabled. #### `win.setSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window to `width` and `height`. If `width` or `height` are below any set minimum size constraints the window will snap to its minimum size. #### `win.getSize()` Returns `Integer[]` - Contains the window's width and height. #### `win.setContentSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window's client area (e.g. the web page) to `width` and `height`. #### `win.getContentSize()` Returns `Integer[]` - Contains the window's client area's width and height. #### `win.setMinimumSize(width, height)` * `width` Integer * `height` Integer Sets the minimum size of window to `width` and `height`. #### `win.getMinimumSize()` Returns `Integer[]` - Contains the window's minimum width and height. #### `win.setMaximumSize(width, height)` * `width` Integer * `height` Integer Sets the maximum size of window to `width` and `height`. #### `win.getMaximumSize()` Returns `Integer[]` - Contains the window's maximum width and height. #### `win.setResizable(resizable)` * `resizable` boolean Sets whether the window can be manually resized by the user. #### `win.isResizable()` Returns `boolean` - Whether the window can be manually resized by the user. #### `win.setMovable(movable)` _macOS_ _Windows_ * `movable` boolean Sets whether the window can be moved by user. On Linux does nothing. #### `win.isMovable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be moved by user. On Linux always returns `true`. #### `win.setMinimizable(minimizable)` _macOS_ _Windows_ * `minimizable` boolean Sets whether the window can be manually minimized by user. On Linux does nothing. #### `win.isMinimizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually minimized by the user. On Linux always returns `true`. #### `win.setMaximizable(maximizable)` _macOS_ _Windows_ * `maximizable` boolean Sets whether the window can be manually maximized by user. On Linux does nothing. #### `win.isMaximizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually maximized by user. On Linux always returns `true`. #### `win.setFullScreenable(fullscreenable)` * `fullscreenable` boolean Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.isFullScreenable()` Returns `boolean` - Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.setClosable(closable)` _macOS_ _Windows_ * `closable` boolean Sets whether the window can be manually closed by user. On Linux does nothing. #### `win.isClosable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually closed by user. On Linux always returns `true`. #### `win.setHiddenInMissionControl(hidden)` _macOS_ * `hidden` boolean Sets whether the window will be hidden when the user toggles into mission control. #### `win.isHiddenInMissionControl()` _macOS_ Returns `boolean` - Whether the window will be hidden when the user toggles into mission control. #### `win.setAlwaysOnTop(flag[, level][, relativeLevel])` * `flag` boolean * `level` string (optional) _macOS_ _Windows_ - Values include `normal`, `floating`, `torn-off-menu`, `modal-panel`, `main-menu`, `status`, `pop-up-menu`, `screen-saver`, and ~~`dock`~~ (Deprecated). The default is `floating` when `flag` is true. The `level` is reset to `normal` when the flag is false. Note that from `floating` to `status` included, the window is placed below the Dock on macOS and below the taskbar on Windows. From `pop-up-menu` to a higher it is shown above the Dock on macOS and above the taskbar on Windows. See the [macOS docs][window-levels] for more details. * `relativeLevel` Integer (optional) _macOS_ - The number of layers higher to set this window relative to the given `level`. The default is `0`. Note that Apple discourages setting levels higher than 1 above `screen-saver`. Sets whether the window should show always on top of other windows. After setting this, the window is still a normal window, not a toolbox window which can not be focused on. #### `win.isAlwaysOnTop()` Returns `boolean` - Whether the window is always on top of other windows. #### `win.moveAbove(mediaSourceId)` * `mediaSourceId` string - Window id in the format of DesktopCapturerSource's id. For example "window:1869:0". Moves window above the source window in the sense of z-order. If the `mediaSourceId` is not of type window or if the window does not exist then this method throws an error. #### `win.moveTop()` Moves window to top(z-order) regardless of focus #### `win.center()` Moves window to the center of the screen. #### `win.setPosition(x, y[, animate])` * `x` Integer * `y` Integer * `animate` boolean (optional) _macOS_ Moves window to `x` and `y`. #### `win.getPosition()` Returns `Integer[]` - Contains the window's current position. #### `win.setTitle(title)` * `title` string Changes the title of native window to `title`. #### `win.getTitle()` Returns `string` - The title of the native window. **Note:** The title of the web page can be different from the title of the native window. #### `win.setSheetOffset(offsetY[, offsetX])` _macOS_ * `offsetY` Float * `offsetX` Float (optional) Changes the attachment point for sheets on macOS. By default, sheets are attached just below the window frame, but you may want to display them beneath a HTML-rendered toolbar. For example: ```js const { BrowserWindow } = require('electron') const win = new BrowserWindow() const toolbarRect = document.getElementById('toolbar').getBoundingClientRect() win.setSheetOffset(toolbarRect.height) ``` #### `win.flashFrame(flag)` * `flag` boolean Starts or stops flashing the window to attract user's attention. #### `win.setSkipTaskbar(skip)` _macOS_ _Windows_ * `skip` boolean Makes the window not show in the taskbar. #### `win.setKiosk(flag)` * `flag` boolean Enters or leaves kiosk mode. #### `win.isKiosk()` Returns `boolean` - Whether the window is in kiosk mode. #### `win.isTabletMode()` _Windows_ Returns `boolean` - Whether the window is in Windows 10 tablet mode. Since Windows 10 users can [use their PC as tablet](https://support.microsoft.com/en-us/help/17210/windows-10-use-your-pc-like-a-tablet), under this mode apps can choose to optimize their UI for tablets, such as enlarging the titlebar and hiding titlebar buttons. This API returns whether the window is in tablet mode, and the `resize` event can be be used to listen to changes to tablet mode. #### `win.getMediaSourceId()` Returns `string` - Window id in the format of DesktopCapturerSource's id. For example "window:1324:0". More precisely the format is `window:id:other_id` where `id` is `HWND` on Windows, `CGWindowID` (`uint64_t`) on macOS and `Window` (`unsigned long`) on Linux. `other_id` is used to identify web contents (tabs) so within the same top level window. #### `win.getNativeWindowHandle()` Returns `Buffer` - The platform-specific handle of the window. The native type of the handle is `HWND` on Windows, `NSView*` on macOS, and `Window` (`unsigned long`) on Linux. #### `win.hookWindowMessage(message, callback)` _Windows_ * `message` Integer * `callback` Function * `wParam` Buffer - The `wParam` provided to the WndProc * `lParam` Buffer - The `lParam` provided to the WndProc Hooks a windows message. The `callback` is called when the message is received in the WndProc. #### `win.isWindowMessageHooked(message)` _Windows_ * `message` Integer Returns `boolean` - `true` or `false` depending on whether the message is hooked. #### `win.unhookWindowMessage(message)` _Windows_ * `message` Integer Unhook the window message. #### `win.unhookAllWindowMessages()` _Windows_ Unhooks all of the window messages. #### `win.setRepresentedFilename(filename)` _macOS_ * `filename` string Sets the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.getRepresentedFilename()` _macOS_ Returns `string` - The pathname of the file the window represents. #### `win.setDocumentEdited(edited)` _macOS_ * `edited` boolean Specifies whether the window’s document has been edited, and the icon in title bar will become gray when set to `true`. #### `win.isDocumentEdited()` _macOS_ Returns `boolean` - Whether the window's document has been edited. #### `win.focusOnWebView()` #### `win.blurWebView()` #### `win.capturePage([rect, opts])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The bounds to capture * `opts` Object (optional) * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. If the page is not visible, `rect` may be empty. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true. #### `win.loadURL(url[, options])` * `url` string * `options` Object (optional) * `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer URL. * `userAgent` string (optional) - A user agent originating the request. * `extraHeaders` string (optional) - Extra headers separated by "\n" * `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional) * `baseURLForDataURL` string (optional) - Base URL (with trailing path separator) for files to be loaded by the data URL. This is needed only if the specified `url` is a data URL and needs to load other files. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Same as [`webContents.loadURL(url[, options])`](web-contents.md#contentsloadurlurl-options). The `url` can be a remote address (e.g. `http://`) or a path to a local HTML file using the `file://` protocol. To ensure that file URLs are properly formatted, it is recommended to use Node's [`url.format`](https://nodejs.org/api/url.html#url_url_format_urlobject) method: ```js const { BrowserWindow } = require('electron') const win = new BrowserWindow() const url = require('url').format({ protocol: 'file', slashes: true, pathname: require('node:path').join(__dirname, 'index.html') }) win.loadURL(url) ``` You can load a URL using a `POST` request with URL-encoded data by doing the following: ```js const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.loadURL('http://localhost:8000/post', { postData: [{ type: 'rawData', bytes: Buffer.from('hello=world') }], extraHeaders: 'Content-Type: application/x-www-form-urlencoded' }) ``` #### `win.loadFile(filePath[, options])` * `filePath` string * `options` Object (optional) * `query` Record<string, string> (optional) - Passed to `url.format()`. * `search` string (optional) - Passed to `url.format()`. * `hash` string (optional) - Passed to `url.format()`. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Same as `webContents.loadFile`, `filePath` should be a path to an HTML file relative to the root of your application. See the `webContents` docs for more information. #### `win.reload()` Same as `webContents.reload`. #### `win.setMenu(menu)` _Linux_ _Windows_ * `menu` Menu | null Sets the `menu` as the window's menu bar. #### `win.removeMenu()` _Linux_ _Windows_ Remove the window's menu bar. #### `win.setProgressBar(progress[, options])` * `progress` Double * `options` Object (optional) * `mode` string _Windows_ - Mode for the progress bar. Can be `none`, `normal`, `indeterminate`, `error` or `paused`. Sets progress value in progress bar. Valid range is \[0, 1.0]. Remove progress bar when progress < 0; Change to indeterminate mode when progress > 1. On Linux platform, only supports Unity desktop environment, you need to specify the `*.desktop` file name to `desktopName` field in `package.json`. By default, it will assume `{app.name}.desktop`. On Windows, a mode can be passed. Accepted values are `none`, `normal`, `indeterminate`, `error`, and `paused`. If you call `setProgressBar` without a mode set (but with a value within the valid range), `normal` will be assumed. #### `win.setOverlayIcon(overlay, description)` _Windows_ * `overlay` [NativeImage](native-image.md) | null - the icon to display on the bottom right corner of the taskbar icon. If this parameter is `null`, the overlay is cleared * `description` string - a description that will be provided to Accessibility screen readers Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to convey some sort of application status or to passively notify the user. #### `win.invalidateShadow()` _macOS_ Invalidates the window shadow so that it is recomputed based on the current window shape. `BrowserWindows` that are transparent can sometimes leave behind visual artifacts on macOS. This method can be used to clear these artifacts when, for example, performing an animation. #### `win.setHasShadow(hasShadow)` * `hasShadow` boolean Sets whether the window should have a shadow. #### `win.hasShadow()` Returns `boolean` - Whether the window has a shadow. #### `win.setOpacity(opacity)` _Windows_ _macOS_ * `opacity` number - between 0.0 (fully transparent) and 1.0 (fully opaque) Sets the opacity of the window. On Linux, does nothing. Out of bound number values are clamped to the \[0, 1] range. #### `win.getOpacity()` Returns `number` - between 0.0 (fully transparent) and 1.0 (fully opaque). On Linux, always returns 1. #### `win.setShape(rects)` _Windows_ _Linux_ _Experimental_ * `rects` [Rectangle[]](structures/rectangle.md) - Sets a shape on the window. Passing an empty list reverts the window to being rectangular. Setting a window shape determines the area within the window where the system permits drawing and user interaction. Outside of the given region, no pixels will be drawn and no mouse events will be registered. Mouse events outside of the region will not be received by that window, but will fall through to whatever is behind the window. #### `win.setThumbarButtons(buttons)` _Windows_ * `buttons` [ThumbarButton[]](structures/thumbar-button.md) Returns `boolean` - Whether the buttons were added successfully Add a thumbnail toolbar with a specified set of buttons to the thumbnail image of a window in a taskbar button layout. Returns a `boolean` object indicates whether the thumbnail has been added successfully. The number of buttons in thumbnail toolbar should be no greater than 7 due to the limited room. Once you setup the thumbnail toolbar, the toolbar cannot be removed due to the platform's limitation. But you can call the API with an empty array to clean the buttons. The `buttons` is an array of `Button` objects: * `Button` Object * `icon` [NativeImage](native-image.md) - The icon showing in thumbnail toolbar. * `click` Function * `tooltip` string (optional) - The text of the button's tooltip. * `flags` string[] (optional) - Control specific states and behaviors of the button. By default, it is `['enabled']`. The `flags` is an array that can include following `string`s: * `enabled` - The button is active and available to the user. * `disabled` - The button is disabled. It is present, but has a visual state indicating it will not respond to user action. * `dismissonclick` - When the button is clicked, the thumbnail window closes immediately. * `nobackground` - Do not draw a button border, use only the image. * `hidden` - The button is not shown to the user. * `noninteractive` - The button is enabled but not interactive; no pressed button state is drawn. This value is intended for instances where the button is used in a notification. #### `win.setThumbnailClip(region)` _Windows_ * `region` [Rectangle](structures/rectangle.md) - Region of the window Sets the region of the window to show as the thumbnail image displayed when hovering over the window in the taskbar. You can reset the thumbnail to be the entire window by specifying an empty region: `{ x: 0, y: 0, width: 0, height: 0 }`. #### `win.setThumbnailToolTip(toolTip)` _Windows_ * `toolTip` string Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar. #### `win.setAppDetails(options)` _Windows_ * `options` Object * `appId` string (optional) - Window's [App User Model ID](https://learn.microsoft.com/en-us/windows/win32/shell/appids). It has to be set, otherwise the other options will have no effect. * `appIconPath` string (optional) - Window's [Relaunch Icon](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchiconresource). * `appIconIndex` Integer (optional) - Index of the icon in `appIconPath`. Ignored when `appIconPath` is not set. Default is `0`. * `relaunchCommand` string (optional) - Window's [Relaunch Command](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchcommand). * `relaunchDisplayName` string (optional) - Window's [Relaunch Display Name](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchdisplaynameresource). Sets the properties for the window's taskbar button. **Note:** `relaunchCommand` and `relaunchDisplayName` must always be set together. If one of those properties is not set, then neither will be used. #### `win.showDefinitionForSelection()` _macOS_ Same as `webContents.showDefinitionForSelection()`. #### `win.setIcon(icon)` _Windows_ _Linux_ * `icon` [NativeImage](native-image.md) | string Changes window icon. #### `win.setWindowButtonVisibility(visible)` _macOS_ * `visible` boolean Sets whether the window traffic light buttons should be visible. #### `win.setAutoHideMenuBar(hide)` _Windows_ _Linux_ * `hide` boolean Sets whether the window menu bar should hide itself automatically. Once set the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, calling `setAutoHideMenuBar(true)` won't hide it immediately. #### `win.isMenuBarAutoHide()` _Windows_ _Linux_ Returns `boolean` - Whether menu bar automatically hides itself. #### `win.setMenuBarVisibility(visible)` _Windows_ _Linux_ * `visible` boolean Sets whether the menu bar should be visible. If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.isMenuBarVisible()` _Windows_ _Linux_ Returns `boolean` - Whether the menu bar is visible. #### `win.setVisibleOnAllWorkspaces(visible[, options])` _macOS_ _Linux_ * `visible` boolean * `options` Object (optional) * `visibleOnFullScreen` boolean (optional) _macOS_ - Sets whether the window should be visible above fullscreen windows. * `skipTransformProcessType` boolean (optional) _macOS_ - Calling setVisibleOnAllWorkspaces will by default transform the process type between UIElementApplication and ForegroundApplication to ensure the correct behavior. However, this will hide the window and dock for a short time every time it is called. If your window is already of type UIElementApplication, you can bypass this transformation by passing true to skipTransformProcessType. Sets whether the window should be visible on all workspaces. **Note:** This API does nothing on Windows. #### `win.isVisibleOnAllWorkspaces()` _macOS_ _Linux_ Returns `boolean` - Whether the window is visible on all workspaces. **Note:** This API always returns false on Windows. #### `win.setIgnoreMouseEvents(ignore[, options])` * `ignore` boolean * `options` Object (optional) * `forward` boolean (optional) _macOS_ _Windows_ - If true, forwards mouse move messages to Chromium, enabling mouse related events such as `mouseleave`. Only used when `ignore` is true. If `ignore` is false, forwarding is always disabled regardless of this value. Makes the window ignore all mouse events. All mouse events happened in this window will be passed to the window below this window, but if this window has focus, it will still receive keyboard events. #### `win.setContentProtection(enable)` _macOS_ _Windows_ * `enable` boolean Prevents the window contents from being captured by other apps. On macOS it sets the NSWindow's sharingType to NSWindowSharingNone. On Windows it calls SetWindowDisplayAffinity with `WDA_EXCLUDEFROMCAPTURE`. For Windows 10 version 2004 and up the window will be removed from capture entirely, older Windows versions behave as if `WDA_MONITOR` is applied capturing a black window. #### `win.setFocusable(focusable)` _macOS_ _Windows_ * `focusable` boolean Changes whether the window can be focused. On macOS it does not remove the focus from the window. #### `win.isFocusable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be focused. #### `win.setParentWindow(parent)` * `parent` BrowserWindow | null Sets `parent` as current window's parent window, passing `null` will turn current window into a top-level window. #### `win.getParentWindow()` Returns `BrowserWindow | null` - The parent window or `null` if there is no parent. #### `win.getChildWindows()` Returns `BrowserWindow[]` - All child windows. #### `win.setAutoHideCursor(autoHide)` _macOS_ * `autoHide` boolean Controls whether to hide cursor when typing. #### `win.selectPreviousTab()` _macOS_ Selects the previous tab when native tabs are enabled and there are other tabs in the window. #### `win.selectNextTab()` _macOS_ Selects the next tab when native tabs are enabled and there are other tabs in the window. #### `win.showAllTabs()` _macOS_ Shows or hides the tab overview when native tabs are enabled. #### `win.mergeAllWindows()` _macOS_ Merges all windows into one window with multiple tabs when native tabs are enabled and there is more than one open window. #### `win.moveTabToNewWindow()` _macOS_ Moves the current tab into a new window if native tabs are enabled and there is more than one tab in the current window. #### `win.toggleTabBar()` _macOS_ Toggles the visibility of the tab bar if native tabs are enabled and there is only one tab in the current window. #### `win.addTabbedWindow(browserWindow)` _macOS_ * `browserWindow` BrowserWindow Adds a window as a tab on this window, after the tab for the window instance. #### `win.setVibrancy(type)` _macOS_ * `type` string | null - Can be `titlebar`, `selection`, `menu`, `popover`, `sidebar`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. See the [macOS documentation][vibrancy-docs] for more details. Adds a vibrancy effect to the browser window. Passing `null` or an empty string will remove the vibrancy effect on the window. #### `win.setBackgroundMaterial(material)` _Windows_ * `material` string * `auto` - Let the Desktop Window Manager (DWM) automatically decide the system-drawn backdrop material for this window. This is the default. * `none` - Don't draw any system backdrop. * `mica` - Draw the backdrop material effect corresponding to a long-lived window. * `acrylic` - Draw the backdrop material effect corresponding to a transient window. * `tabbed` - Draw the backdrop material effect corresponding to a window with a tabbed title bar. This method sets the browser window's system-drawn background material, including behind the non-client area. See the [Windows documentation](https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_systembackdrop_type) for more details. **Note:** This method is only supported on Windows 11 22H2 and up. #### `win.setWindowButtonPosition(position)` _macOS_ * `position` [Point](structures/point.md) | null Set a custom position for the traffic light buttons in frameless window. Passing `null` will reset the position to default. #### `win.getWindowButtonPosition()` _macOS_ Returns `Point | null` - The custom position for the traffic light buttons in frameless window, `null` will be returned when there is no custom position. #### `win.setTouchBar(touchBar)` _macOS_ * `touchBar` TouchBar | null Sets the touchBar layout for the current window. Specifying `null` or `undefined` clears the touch bar. This method only has an effect if the machine has a touch bar. **Note:** The TouchBar API is currently experimental and may change or be removed in future Electron releases. #### `win.setBrowserView(browserView)` _Experimental_ _Deprecated_ * `browserView` [BrowserView](browser-view.md) | null - Attach `browserView` to `win`. If there are other `BrowserView`s attached, they will be removed from this window. > **Note** > The `BrowserView` class is deprecated, and replaced by the new > [`WebContentsView`](web-contents-view.md) class. #### `win.getBrowserView()` _Experimental_ _Deprecated_ Returns `BrowserView | null` - The `BrowserView` attached to `win`. Returns `null` if one is not attached. Throws an error if multiple `BrowserView`s are attached. > **Note** > The `BrowserView` class is deprecated, and replaced by the new > [`WebContentsView`](web-contents-view.md) class. #### `win.addBrowserView(browserView)` _Experimental_ _Deprecated_ * `browserView` [BrowserView](browser-view.md) Replacement API for setBrowserView supporting work with multi browser views. > **Note** > The `BrowserView` class is deprecated, and replaced by the new > [`WebContentsView`](web-contents-view.md) class. #### `win.removeBrowserView(browserView)` _Experimental_ _Deprecated_ * `browserView` [BrowserView](browser-view.md) > **Note** > The `BrowserView` class is deprecated, and replaced by the new > [`WebContentsView`](web-contents-view.md) class. #### `win.setTopBrowserView(browserView)` _Experimental_ _Deprecated_ * `browserView` [BrowserView](browser-view.md) Raises `browserView` above other `BrowserView`s attached to `win`. Throws an error if `browserView` is not attached to `win`. > **Note** > The `BrowserView` class is deprecated, and replaced by the new > [`WebContentsView`](web-contents-view.md) class. #### `win.getBrowserViews()` _Experimental_ _Deprecated_ Returns `BrowserView[]` - a sorted by z-index array of all BrowserViews that have been attached with `addBrowserView` or `setBrowserView`. The top-most BrowserView is the last element of the array. > **Note** > The `BrowserView` class is deprecated, and replaced by the new > [`WebContentsView`](web-contents-view.md) class. #### `win.setTitleBarOverlay(options)` _Windows_ * `options` Object * `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled. * `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled. * `height` Integer (optional) _macOS_ _Windows_ - The height of the title bar and Window Controls Overlay in pixels. On a Window with Window Controls Overlay already enabled, this method updates the style of the title bar overlay. [page-visibility-api]: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API [quick-look]: https://en.wikipedia.org/wiki/Quick_Look [vibrancy-docs]: https://developer.apple.com/documentation/appkit/nsvisualeffectview?preferredLanguage=objc [window-levels]: https://developer.apple.com/documentation/appkit/nswindow/level [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
closed
electron/electron
https://github.com/electron/electron
38,955
[Bug]: `BrowserWindow.isVisible()` doesn't take into account occlusion state
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? macOS ### Operating System Version Ventura 13.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I found out that BrowserWindow on Mac started to take into account page occlusion state since this PR: https://github.com/electron/electron/pull/17463/files BrowserWindow.isVisible() should return false if window is occluded by another window. ### Actual Behavior BrowserWindow.isVisible() always returns true unless minimized. ### Testcase Gist URL https://gist.github.com/Imperat/0ecffacee8d1386258d67a91e0017644 ### Additional Information Provided fiddle is best way to reproduce the issue: move browser window to the corner (or another screen) and open another app on top of browserWindow. Observe that in fiddle console "visible true" still logged.
https://github.com/electron/electron/issues/38955
https://github.com/electron/electron/pull/38982
08236f7a9e9d664513e2b76b54b9bea003101e5d
768ece6b54f78e65efbea2c3fd39eea30e48332b
2023-06-30T00:50:25Z
c++
2024-02-06T10:30:35Z
shell/browser/api/electron_api_base_window.cc
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_base_window.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/containers/contains.h" #include "base/task/single_thread_task_runner.h" #include "electron/buildflags/buildflags.h" #include "gin/dictionary.h" #include "shell/browser/api/electron_api_menu.h" #include "shell/browser/api/electron_api_view.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/javascript_environment.h" #include "shell/common/color_util.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/native_window_converter.h" #include "shell/common/gin_converters/optional_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/gin_helper/persistent_dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #if defined(TOOLKIT_VIEWS) #include "shell/browser/native_window_views.h" #endif #if BUILDFLAG(IS_WIN) #include "shell/browser/ui/win/taskbar_host.h" #include "ui/base/win/shell.h" #endif #if BUILDFLAG(IS_WIN) namespace gin { template <> struct Converter<electron::TaskbarHost::ThumbarButton> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::TaskbarHost::ThumbarButton* out) { gin::Dictionary dict(isolate); if (!gin::ConvertFromV8(isolate, val, &dict)) return false; dict.Get("click", &(out->clicked_callback)); dict.Get("tooltip", &(out->tooltip)); dict.Get("flags", &out->flags); return dict.Get("icon", &(out->icon)); } }; } // namespace gin #endif namespace electron::api { namespace { // Converts binary data to Buffer. v8::Local<v8::Value> ToBuffer(v8::Isolate* isolate, void* val, int size) { auto buffer = node::Buffer::Copy(isolate, static_cast<char*>(val), size); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } } // namespace BaseWindow::BaseWindow(v8::Isolate* isolate, const gin_helper::Dictionary& options) { // The parent window. gin::Handle<BaseWindow> parent; if (options.Get("parent", &parent) && !parent.IsEmpty()) parent_window_.Reset(isolate, parent.ToV8()); // Offscreen windows are always created frameless. gin_helper::Dictionary web_preferences; bool offscreen; if (options.Get(options::kWebPreferences, &web_preferences) && web_preferences.Get(options::kOffscreen, &offscreen) && offscreen) { const_cast<gin_helper::Dictionary&>(options).Set(options::kFrame, false); } // Creates NativeWindow. window_.reset(NativeWindow::Create( options, parent.IsEmpty() ? nullptr : parent->window_.get())); window_->AddObserver(this); SetContentView(View::Create(isolate)); #if defined(TOOLKIT_VIEWS) v8::Local<v8::Value> icon; if (options.Get(options::kIcon, &icon)) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kWarn); } #endif } BaseWindow::BaseWindow(gin_helper::Arguments* args, const gin_helper::Dictionary& options) : BaseWindow(args->isolate(), options) { InitWithArgs(args); // Init window after everything has been setup. window()->InitFromOptions(options); } BaseWindow::~BaseWindow() { CloseImmediately(); // Destroy the native window in next tick because the native code might be // iterating all windows. base::SingleThreadTaskRunner::GetCurrentDefault()->DeleteSoon( FROM_HERE, window_.release()); // Remove global reference so the JS object can be garbage collected. self_ref_.Reset(); } void BaseWindow::InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) { AttachAsUserData(window_.get()); gin_helper::TrackableObject<BaseWindow>::InitWith(isolate, wrapper); // We can only append this window to parent window's child windows after this // window's JS wrapper gets initialized. if (!parent_window_.IsEmpty()) { gin::Handle<BaseWindow> parent; gin::ConvertFromV8(isolate, GetParentWindow(), &parent); DCHECK(!parent.IsEmpty()); parent->child_windows_.Set(isolate, weak_map_id(), wrapper); } // Reference this object in case it got garbage collected. self_ref_.Reset(isolate, wrapper); } void BaseWindow::WillCloseWindow(bool* prevent_default) { if (Emit("close")) { *prevent_default = true; } } void BaseWindow::OnWindowClosed() { // Invalidate weak ptrs before the Javascript object is destroyed, // there might be some delayed emit events which shouldn't be // triggered after this. weak_factory_.InvalidateWeakPtrs(); RemoveFromWeakMap(); window_->RemoveObserver(this); // We can not call Destroy here because we need to call Emit first, but we // also do not want any method to be used, so just mark as destroyed here. MarkDestroyed(); Emit("closed"); RemoveFromParentChildWindows(); // Destroy the native class when window is closed. base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, GetDestroyClosure()); } void BaseWindow::OnWindowEndSession() { Emit("session-end"); } void BaseWindow::OnWindowBlur() { EmitEventSoon("blur"); } void BaseWindow::OnWindowFocus() { EmitEventSoon("focus"); } void BaseWindow::OnWindowShow() { Emit("show"); } void BaseWindow::OnWindowHide() { Emit("hide"); } void BaseWindow::OnWindowMaximize() { Emit("maximize"); } void BaseWindow::OnWindowUnmaximize() { Emit("unmaximize"); } void BaseWindow::OnWindowMinimize() { Emit("minimize"); } void BaseWindow::OnWindowRestore() { Emit("restore"); } void BaseWindow::OnWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto info = gin::Dictionary::CreateEmpty(isolate); info.Set("edge", edge); if (Emit("will-resize", new_bounds, info)) { *prevent_default = true; } } void BaseWindow::OnWindowResize() { Emit("resize"); } void BaseWindow::OnWindowResized() { Emit("resized"); } void BaseWindow::OnWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { if (Emit("will-move", new_bounds)) { *prevent_default = true; } } void BaseWindow::OnWindowMove() { Emit("move"); } void BaseWindow::OnWindowMoved() { Emit("moved"); } void BaseWindow::OnWindowEnterFullScreen() { Emit("enter-full-screen"); } void BaseWindow::OnWindowLeaveFullScreen() { Emit("leave-full-screen"); } void BaseWindow::OnWindowSwipe(const std::string& direction) { Emit("swipe", direction); } void BaseWindow::OnWindowRotateGesture(float rotation) { Emit("rotate-gesture", rotation); } void BaseWindow::OnWindowSheetBegin() { Emit("sheet-begin"); } void BaseWindow::OnWindowSheetEnd() { Emit("sheet-end"); } void BaseWindow::OnWindowEnterHtmlFullScreen() { Emit("enter-html-full-screen"); } void BaseWindow::OnWindowLeaveHtmlFullScreen() { Emit("leave-html-full-screen"); } void BaseWindow::OnWindowAlwaysOnTopChanged() { Emit("always-on-top-changed", IsAlwaysOnTop()); } void BaseWindow::OnExecuteAppCommand(const std::string& command_name) { Emit("app-command", command_name); } void BaseWindow::OnTouchBarItemResult(const std::string& item_id, const base::Value::Dict& details) { Emit("-touch-bar-interaction", item_id, details); } void BaseWindow::OnNewWindowForTab() { Emit("new-window-for-tab"); } void BaseWindow::OnSystemContextMenu(int x, int y, bool* prevent_default) { if (Emit("system-context-menu", gfx::Point(x, y))) { *prevent_default = true; } } #if BUILDFLAG(IS_WIN) void BaseWindow::OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { if (IsWindowMessageHooked(message)) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); messages_callback_map_[message].Run( ToBuffer(isolate, static_cast<void*>(&w_param), sizeof(WPARAM)), ToBuffer(isolate, static_cast<void*>(&l_param), sizeof(LPARAM))); } } #endif void BaseWindow::SetContentView(gin::Handle<View> view) { content_view_.Reset(JavascriptEnvironment::GetIsolate(), view.ToV8()); window_->SetContentView(view->view()); } void BaseWindow::CloseImmediately() { if (!window_->IsClosed()) window_->CloseImmediately(); } void BaseWindow::Close() { window_->Close(); } void BaseWindow::Focus() { window_->Focus(true); } void BaseWindow::Blur() { window_->Focus(false); } bool BaseWindow::IsFocused() const { return window_->IsFocused(); } void BaseWindow::Show() { window_->Show(); } void BaseWindow::ShowInactive() { // This method doesn't make sense for modal window. if (IsModal()) return; window_->ShowInactive(); } void BaseWindow::Hide() { window_->Hide(); } bool BaseWindow::IsVisible() const { return window_->IsVisible(); } bool BaseWindow::IsEnabled() const { return window_->IsEnabled(); } void BaseWindow::SetEnabled(bool enable) { window_->SetEnabled(enable); } void BaseWindow::Maximize() { window_->Maximize(); } void BaseWindow::Unmaximize() { window_->Unmaximize(); } bool BaseWindow::IsMaximized() const { return window_->IsMaximized(); } void BaseWindow::Minimize() { window_->Minimize(); } void BaseWindow::Restore() { window_->Restore(); } bool BaseWindow::IsMinimized() const { return window_->IsMinimized(); } void BaseWindow::SetFullScreen(bool fullscreen) { window_->SetFullScreen(fullscreen); } bool BaseWindow::IsFullscreen() const { return window_->IsFullscreen(); } void BaseWindow::SetBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetBounds(bounds, animate); } gfx::Rect BaseWindow::GetBounds() const { return window_->GetBounds(); } bool BaseWindow::IsNormal() const { return window_->IsNormal(); } gfx::Rect BaseWindow::GetNormalBounds() const { return window_->GetNormalBounds(); } void BaseWindow::SetContentBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentBounds(bounds, animate); } gfx::Rect BaseWindow::GetContentBounds() const { return window_->GetContentBounds(); } void BaseWindow::SetSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; gfx::Size size = window_->GetMinimumSize(); size.SetToMax(gfx::Size(width, height)); args->GetNext(&animate); window_->SetSize(size, animate); } std::vector<int> BaseWindow::GetSize() const { std::vector<int> result(2); gfx::Size size = window_->GetSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetContentSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentSize(gfx::Size(width, height), animate); } std::vector<int> BaseWindow::GetContentSize() const { std::vector<int> result(2); gfx::Size size = window_->GetContentSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMinimumSize(int width, int height) { window_->SetMinimumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMinimumSize() const { std::vector<int> result(2); gfx::Size size = window_->GetMinimumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMaximumSize(int width, int height) { window_->SetMaximumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMaximumSize() const { std::vector<int> result(2); gfx::Size size = window_->GetMaximumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetSheetOffset(double offsetY, gin_helper::Arguments* args) { double offsetX = 0.0; args->GetNext(&offsetX); window_->SetSheetOffset(offsetX, offsetY); } void BaseWindow::SetResizable(bool resizable) { window_->SetResizable(resizable); } bool BaseWindow::IsResizable() const { return window_->IsResizable(); } void BaseWindow::SetMovable(bool movable) { window_->SetMovable(movable); } bool BaseWindow::IsMovable() const { return window_->IsMovable(); } void BaseWindow::SetMinimizable(bool minimizable) { window_->SetMinimizable(minimizable); } bool BaseWindow::IsMinimizable() const { return window_->IsMinimizable(); } void BaseWindow::SetMaximizable(bool maximizable) { window_->SetMaximizable(maximizable); } bool BaseWindow::IsMaximizable() const { return window_->IsMaximizable(); } void BaseWindow::SetFullScreenable(bool fullscreenable) { window_->SetFullScreenable(fullscreenable); } bool BaseWindow::IsFullScreenable() const { return window_->IsFullScreenable(); } void BaseWindow::SetClosable(bool closable) { window_->SetClosable(closable); } bool BaseWindow::IsClosable() const { return window_->IsClosable(); } void BaseWindow::SetAlwaysOnTop(bool top, gin_helper::Arguments* args) { std::string level = "floating"; int relative_level = 0; args->GetNext(&level); args->GetNext(&relative_level); ui::ZOrderLevel z_order = top ? ui::ZOrderLevel::kFloatingWindow : ui::ZOrderLevel::kNormal; window_->SetAlwaysOnTop(z_order, level, relative_level); } bool BaseWindow::IsAlwaysOnTop() const { return window_->GetZOrderLevel() != ui::ZOrderLevel::kNormal; } void BaseWindow::Center() { window_->Center(); } void BaseWindow::SetPosition(int x, int y, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetPosition(gfx::Point(x, y), animate); } std::vector<int> BaseWindow::GetPosition() const { std::vector<int> result(2); gfx::Point pos = window_->GetPosition(); result[0] = pos.x(); result[1] = pos.y(); return result; } void BaseWindow::MoveAbove(const std::string& sourceId, gin_helper::Arguments* args) { if (!window_->MoveAbove(sourceId)) args->ThrowError("Invalid media source id"); } void BaseWindow::MoveTop() { window_->MoveTop(); } void BaseWindow::SetTitle(const std::string& title) { window_->SetTitle(title); } std::string BaseWindow::GetTitle() const { return window_->GetTitle(); } void BaseWindow::SetAccessibleTitle(const std::string& title) { window_->SetAccessibleTitle(title); } std::string BaseWindow::GetAccessibleTitle() const { return window_->GetAccessibleTitle(); } void BaseWindow::FlashFrame(bool flash) { window_->FlashFrame(flash); } void BaseWindow::SetSkipTaskbar(bool skip) { window_->SetSkipTaskbar(skip); } void BaseWindow::SetExcludedFromShownWindowsMenu(bool excluded) { window_->SetExcludedFromShownWindowsMenu(excluded); } bool BaseWindow::IsExcludedFromShownWindowsMenu() const { return window_->IsExcludedFromShownWindowsMenu(); } void BaseWindow::SetSimpleFullScreen(bool simple_fullscreen) { window_->SetSimpleFullScreen(simple_fullscreen); } bool BaseWindow::IsSimpleFullScreen() const { return window_->IsSimpleFullScreen(); } void BaseWindow::SetKiosk(bool kiosk) { window_->SetKiosk(kiosk); } bool BaseWindow::IsKiosk() const { return window_->IsKiosk(); } bool BaseWindow::IsTabletMode() const { return window_->IsTabletMode(); } void BaseWindow::SetBackgroundColor(const std::string& color_name) { SkColor color = ParseCSSColor(color_name); window_->SetBackgroundColor(color); } std::string BaseWindow::GetBackgroundColor(gin_helper::Arguments* args) const { return ToRGBHex(window_->GetBackgroundColor()); } void BaseWindow::InvalidateShadow() { window_->InvalidateShadow(); } void BaseWindow::SetHasShadow(bool has_shadow) { window_->SetHasShadow(has_shadow); } bool BaseWindow::HasShadow() const { return window_->HasShadow(); } void BaseWindow::SetOpacity(const double opacity) { window_->SetOpacity(opacity); } double BaseWindow::GetOpacity() const { return window_->GetOpacity(); } void BaseWindow::SetShape(const std::vector<gfx::Rect>& rects) { window_->widget()->SetShape(std::make_unique<std::vector<gfx::Rect>>(rects)); } void BaseWindow::SetRepresentedFilename(const std::string& filename) { window_->SetRepresentedFilename(filename); } std::string BaseWindow::GetRepresentedFilename() const { return window_->GetRepresentedFilename(); } void BaseWindow::SetDocumentEdited(bool edited) { window_->SetDocumentEdited(edited); } bool BaseWindow::IsDocumentEdited() const { return window_->IsDocumentEdited(); } void BaseWindow::SetIgnoreMouseEvents(bool ignore, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool forward = false; args->GetNext(&options) && options.Get("forward", &forward); return window_->SetIgnoreMouseEvents(ignore, forward); } void BaseWindow::SetContentProtection(bool enable) { return window_->SetContentProtection(enable); } void BaseWindow::SetFocusable(bool focusable) { return window_->SetFocusable(focusable); } bool BaseWindow::IsFocusable() const { return window_->IsFocusable(); } void BaseWindow::SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> value) { auto context = isolate->GetCurrentContext(); gin::Handle<Menu> menu; v8::Local<v8::Object> object; if (value->IsObject() && value->ToObject(context).ToLocal(&object) && gin::ConvertFromV8(isolate, value, &menu) && !menu.IsEmpty()) { // We only want to update the menu if the menu has a non-zero item count, // or we risk crashes. if (menu->model()->GetItemCount() == 0) { RemoveMenu(); } else { window_->SetMenu(menu->model()); } menu_.Reset(isolate, menu.ToV8()); } else if (value->IsNull()) { RemoveMenu(); } else { isolate->ThrowException( v8::Exception::TypeError(gin::StringToV8(isolate, "Invalid Menu"))); } } void BaseWindow::RemoveMenu() { menu_.Reset(); window_->SetMenu(nullptr); } void BaseWindow::SetParentWindow(v8::Local<v8::Value> value, gin_helper::Arguments* args) { if (IsModal()) { args->ThrowError("Can not be called for modal window"); return; } gin::Handle<BaseWindow> parent; if (value->IsNull() || value->IsUndefined()) { RemoveFromParentChildWindows(); parent_window_.Reset(); window_->SetParentWindow(nullptr); } else if (gin::ConvertFromV8(isolate(), value, &parent)) { RemoveFromParentChildWindows(); parent_window_.Reset(isolate(), value); window_->SetParentWindow(parent->window_.get()); parent->child_windows_.Set(isolate(), weak_map_id(), GetWrapper()); } else { args->ThrowError("Must pass BaseWindow instance or null"); } } std::string BaseWindow::GetMediaSourceId() const { return window_->GetDesktopMediaID().ToString(); } v8::Local<v8::Value> BaseWindow::GetNativeWindowHandle() { // TODO(MarshallOfSound): Replace once // https://chromium-review.googlesource.com/c/chromium/src/+/1253094/ has // landed NativeWindowHandle handle = window_->GetNativeWindowHandle(); return ToBuffer(isolate(), &handle, sizeof(handle)); } void BaseWindow::SetProgressBar(double progress, gin_helper::Arguments* args) { gin_helper::Dictionary options; std::string mode; args->GetNext(&options) && options.Get("mode", &mode); NativeWindow::ProgressState state = NativeWindow::ProgressState::kNormal; if (mode == "error") state = NativeWindow::ProgressState::kError; else if (mode == "paused") state = NativeWindow::ProgressState::kPaused; else if (mode == "indeterminate") state = NativeWindow::ProgressState::kIndeterminate; else if (mode == "none") state = NativeWindow::ProgressState::kNone; window_->SetProgressBar(progress, state); } void BaseWindow::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { window_->SetOverlayIcon(overlay, description); } void BaseWindow::SetVisibleOnAllWorkspaces(bool visible, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool visibleOnFullScreen = false; bool skipTransformProcessType = false; if (args->GetNext(&options)) { options.Get("visibleOnFullScreen", &visibleOnFullScreen); options.Get("skipTransformProcessType", &skipTransformProcessType); } return window_->SetVisibleOnAllWorkspaces(visible, visibleOnFullScreen, skipTransformProcessType); } bool BaseWindow::IsVisibleOnAllWorkspaces() const { return window_->IsVisibleOnAllWorkspaces(); } void BaseWindow::SetAutoHideCursor(bool auto_hide) { window_->SetAutoHideCursor(auto_hide); } void BaseWindow::SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value) { std::string type = gin::V8ToString(isolate, value); window_->SetVibrancy(type); } void BaseWindow::SetBackgroundMaterial(const std::string& material_type) { window_->SetBackgroundMaterial(material_type); } #if BUILDFLAG(IS_MAC) std::string BaseWindow::GetAlwaysOnTopLevel() const { return window_->GetAlwaysOnTopLevel(); } void BaseWindow::SetWindowButtonVisibility(bool visible) { window_->SetWindowButtonVisibility(visible); } bool BaseWindow::GetWindowButtonVisibility() const { return window_->GetWindowButtonVisibility(); } void BaseWindow::SetWindowButtonPosition(std::optional<gfx::Point> position) { window_->SetWindowButtonPosition(std::move(position)); } std::optional<gfx::Point> BaseWindow::GetWindowButtonPosition() const { return window_->GetWindowButtonPosition(); } #endif #if BUILDFLAG(IS_MAC) bool BaseWindow::IsHiddenInMissionControl() { return window_->IsHiddenInMissionControl(); } void BaseWindow::SetHiddenInMissionControl(bool hidden) { window_->SetHiddenInMissionControl(hidden); } #endif void BaseWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { window_->SetTouchBar(std::move(items)); } void BaseWindow::RefreshTouchBarItem(const std::string& item_id) { window_->RefreshTouchBarItem(item_id); } void BaseWindow::SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) { window_->SetEscapeTouchBarItem(std::move(item)); } void BaseWindow::SelectPreviousTab() { window_->SelectPreviousTab(); } void BaseWindow::SelectNextTab() { window_->SelectNextTab(); } void BaseWindow::ShowAllTabs() { window_->ShowAllTabs(); } void BaseWindow::MergeAllWindows() { window_->MergeAllWindows(); } void BaseWindow::MoveTabToNewWindow() { window_->MoveTabToNewWindow(); } void BaseWindow::ToggleTabBar() { window_->ToggleTabBar(); } void BaseWindow::AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args) { if (!window_->AddTabbedWindow(window)) args->ThrowError("AddTabbedWindow cannot be called by a window on itself."); } v8::Local<v8::Value> BaseWindow::GetTabbingIdentifier() { auto tabbing_id = window_->GetTabbingIdentifier(); if (!tabbing_id.has_value()) return v8::Undefined(isolate()); return gin::ConvertToV8(isolate(), tabbing_id.value()); } void BaseWindow::SetAutoHideMenuBar(bool auto_hide) { window_->SetAutoHideMenuBar(auto_hide); } bool BaseWindow::IsMenuBarAutoHide() const { return window_->IsMenuBarAutoHide(); } void BaseWindow::SetMenuBarVisibility(bool visible) { window_->SetMenuBarVisibility(visible); } bool BaseWindow::IsMenuBarVisible() const { return window_->IsMenuBarVisible(); } void BaseWindow::SetAspectRatio(double aspect_ratio, gin_helper::Arguments* args) { gfx::Size extra_size; args->GetNext(&extra_size); window_->SetAspectRatio(aspect_ratio, extra_size); } void BaseWindow::PreviewFile(const std::string& path, gin_helper::Arguments* args) { std::string display_name; if (!args->GetNext(&display_name)) display_name = path; window_->PreviewFile(path, display_name); } void BaseWindow::CloseFilePreview() { window_->CloseFilePreview(); } void BaseWindow::SetGTKDarkThemeEnabled(bool use_dark_theme) { window_->SetGTKDarkThemeEnabled(use_dark_theme); } v8::Local<v8::Value> BaseWindow::GetContentView() const { if (content_view_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), content_view_); } v8::Local<v8::Value> BaseWindow::GetParentWindow() const { if (parent_window_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), parent_window_); } std::vector<v8::Local<v8::Object>> BaseWindow::GetChildWindows() const { return child_windows_.Values(isolate()); } bool BaseWindow::IsModal() const { return window_->is_modal(); } bool BaseWindow::SetThumbarButtons(gin_helper::Arguments* args) { #if BUILDFLAG(IS_WIN) std::vector<TaskbarHost::ThumbarButton> buttons; if (!args->GetNext(&buttons)) { args->ThrowError(); return false; } auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbarButtons( window_->GetAcceleratedWidget(), buttons); #else return false; #endif } #if defined(TOOLKIT_VIEWS) void BaseWindow::SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kThrow); } void BaseWindow::SetIconImpl(v8::Isolate* isolate, v8::Local<v8::Value> icon, NativeImage::OnConvertError on_error) { NativeImage* native_image = nullptr; if (!NativeImage::TryConvertNativeImage(isolate, icon, &native_image, on_error)) return; #if BUILDFLAG(IS_WIN) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->GetHICON(GetSystemMetrics(SM_CXSMICON)), native_image->GetHICON(GetSystemMetrics(SM_CXICON))); #elif BUILDFLAG(IS_LINUX) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->image().AsImageSkia()); #endif } #endif #if BUILDFLAG(IS_WIN) bool BaseWindow::HookWindowMessage(UINT message, const MessageCallback& callback) { messages_callback_map_[message] = callback; return true; } void BaseWindow::UnhookWindowMessage(UINT message) { messages_callback_map_.erase(message); } bool BaseWindow::IsWindowMessageHooked(UINT message) { return base::Contains(messages_callback_map_, message); } void BaseWindow::UnhookAllWindowMessages() { messages_callback_map_.clear(); } bool BaseWindow::SetThumbnailClip(const gfx::Rect& region) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailClip( window_->GetAcceleratedWidget(), region); } bool BaseWindow::SetThumbnailToolTip(const std::string& tooltip) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailToolTip( window_->GetAcceleratedWidget(), tooltip); } void BaseWindow::SetAppDetails(const gin_helper::Dictionary& options) { std::wstring app_id; base::FilePath app_icon_path; int app_icon_index = 0; std::wstring relaunch_command; std::wstring relaunch_display_name; options.Get("appId", &app_id); options.Get("appIconPath", &app_icon_path); options.Get("appIconIndex", &app_icon_index); options.Get("relaunchCommand", &relaunch_command); options.Get("relaunchDisplayName", &relaunch_display_name); ui::win::SetAppDetailsForWindow(app_id, app_icon_path, app_icon_index, relaunch_command, relaunch_display_name, window_->GetAcceleratedWidget()); } #endif int32_t BaseWindow::GetID() const { return weak_map_id(); } void BaseWindow::RemoveFromParentChildWindows() { if (parent_window_.IsEmpty()) return; gin::Handle<BaseWindow> parent; if (!gin::ConvertFromV8(isolate(), GetParentWindow(), &parent) || parent.IsEmpty()) { return; } parent->child_windows_.Remove(weak_map_id()); } // static gin_helper::WrappableBase* BaseWindow::New(gin_helper::Arguments* args) { auto options = gin_helper::Dictionary::CreateEmpty(args->isolate()); args->GetNext(&options); return new BaseWindow(args, options); } // static void BaseWindow::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(gin::StringToV8(isolate, "BaseWindow")); gin_helper::Destroyable::MakeDestroyable(isolate, prototype); gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) .SetMethod("setContentView", &BaseWindow::SetContentView) .SetMethod("close", &BaseWindow::Close) .SetMethod("focus", &BaseWindow::Focus) .SetMethod("blur", &BaseWindow::Blur) .SetMethod("isFocused", &BaseWindow::IsFocused) .SetMethod("show", &BaseWindow::Show) .SetMethod("showInactive", &BaseWindow::ShowInactive) .SetMethod("hide", &BaseWindow::Hide) .SetMethod("isVisible", &BaseWindow::IsVisible) .SetMethod("isEnabled", &BaseWindow::IsEnabled) .SetMethod("setEnabled", &BaseWindow::SetEnabled) .SetMethod("maximize", &BaseWindow::Maximize) .SetMethod("unmaximize", &BaseWindow::Unmaximize) .SetMethod("isMaximized", &BaseWindow::IsMaximized) .SetMethod("minimize", &BaseWindow::Minimize) .SetMethod("restore", &BaseWindow::Restore) .SetMethod("isMinimized", &BaseWindow::IsMinimized) .SetMethod("setFullScreen", &BaseWindow::SetFullScreen) .SetMethod("isFullScreen", &BaseWindow::IsFullscreen) .SetMethod("setBounds", &BaseWindow::SetBounds) .SetMethod("getBounds", &BaseWindow::GetBounds) .SetMethod("isNormal", &BaseWindow::IsNormal) .SetMethod("getNormalBounds", &BaseWindow::GetNormalBounds) .SetMethod("setSize", &BaseWindow::SetSize) .SetMethod("getSize", &BaseWindow::GetSize) .SetMethod("setContentBounds", &BaseWindow::SetContentBounds) .SetMethod("getContentBounds", &BaseWindow::GetContentBounds) .SetMethod("setContentSize", &BaseWindow::SetContentSize) .SetMethod("getContentSize", &BaseWindow::GetContentSize) .SetMethod("setMinimumSize", &BaseWindow::SetMinimumSize) .SetMethod("getMinimumSize", &BaseWindow::GetMinimumSize) .SetMethod("setMaximumSize", &BaseWindow::SetMaximumSize) .SetMethod("getMaximumSize", &BaseWindow::GetMaximumSize) .SetMethod("setSheetOffset", &BaseWindow::SetSheetOffset) .SetMethod("moveAbove", &BaseWindow::MoveAbove) .SetMethod("moveTop", &BaseWindow::MoveTop) .SetMethod("setResizable", &BaseWindow::SetResizable) .SetMethod("isResizable", &BaseWindow::IsResizable) .SetMethod("setMovable", &BaseWindow::SetMovable) .SetMethod("isMovable", &BaseWindow::IsMovable) .SetMethod("setMinimizable", &BaseWindow::SetMinimizable) .SetMethod("isMinimizable", &BaseWindow::IsMinimizable) .SetMethod("setMaximizable", &BaseWindow::SetMaximizable) .SetMethod("isMaximizable", &BaseWindow::IsMaximizable) .SetMethod("setFullScreenable", &BaseWindow::SetFullScreenable) .SetMethod("isFullScreenable", &BaseWindow::IsFullScreenable) .SetMethod("setClosable", &BaseWindow::SetClosable) .SetMethod("isClosable", &BaseWindow::IsClosable) .SetMethod("setAlwaysOnTop", &BaseWindow::SetAlwaysOnTop) .SetMethod("isAlwaysOnTop", &BaseWindow::IsAlwaysOnTop) .SetMethod("center", &BaseWindow::Center) .SetMethod("setPosition", &BaseWindow::SetPosition) .SetMethod("getPosition", &BaseWindow::GetPosition) .SetMethod("setTitle", &BaseWindow::SetTitle) .SetMethod("getTitle", &BaseWindow::GetTitle) .SetProperty("accessibleTitle", &BaseWindow::GetAccessibleTitle, &BaseWindow::SetAccessibleTitle) .SetMethod("flashFrame", &BaseWindow::FlashFrame) .SetMethod("setSkipTaskbar", &BaseWindow::SetSkipTaskbar) .SetMethod("setSimpleFullScreen", &BaseWindow::SetSimpleFullScreen) .SetMethod("isSimpleFullScreen", &BaseWindow::IsSimpleFullScreen) .SetMethod("setKiosk", &BaseWindow::SetKiosk) .SetMethod("isKiosk", &BaseWindow::IsKiosk) .SetMethod("isTabletMode", &BaseWindow::IsTabletMode) .SetMethod("setBackgroundColor", &BaseWindow::SetBackgroundColor) .SetMethod("getBackgroundColor", &BaseWindow::GetBackgroundColor) .SetMethod("setHasShadow", &BaseWindow::SetHasShadow) .SetMethod("hasShadow", &BaseWindow::HasShadow) .SetMethod("setOpacity", &BaseWindow::SetOpacity) .SetMethod("getOpacity", &BaseWindow::GetOpacity) .SetMethod("setShape", &BaseWindow::SetShape) .SetMethod("setRepresentedFilename", &BaseWindow::SetRepresentedFilename) .SetMethod("getRepresentedFilename", &BaseWindow::GetRepresentedFilename) .SetMethod("setDocumentEdited", &BaseWindow::SetDocumentEdited) .SetMethod("isDocumentEdited", &BaseWindow::IsDocumentEdited) .SetMethod("setIgnoreMouseEvents", &BaseWindow::SetIgnoreMouseEvents) .SetMethod("setContentProtection", &BaseWindow::SetContentProtection) .SetMethod("setFocusable", &BaseWindow::SetFocusable) .SetMethod("isFocusable", &BaseWindow::IsFocusable) .SetMethod("setMenu", &BaseWindow::SetMenu) .SetMethod("removeMenu", &BaseWindow::RemoveMenu) .SetMethod("setParentWindow", &BaseWindow::SetParentWindow) .SetMethod("getMediaSourceId", &BaseWindow::GetMediaSourceId) .SetMethod("getNativeWindowHandle", &BaseWindow::GetNativeWindowHandle) .SetMethod("setProgressBar", &BaseWindow::SetProgressBar) .SetMethod("setOverlayIcon", &BaseWindow::SetOverlayIcon) .SetMethod("setVisibleOnAllWorkspaces", &BaseWindow::SetVisibleOnAllWorkspaces) .SetMethod("isVisibleOnAllWorkspaces", &BaseWindow::IsVisibleOnAllWorkspaces) #if BUILDFLAG(IS_MAC) .SetMethod("invalidateShadow", &BaseWindow::InvalidateShadow) .SetMethod("_getAlwaysOnTopLevel", &BaseWindow::GetAlwaysOnTopLevel) .SetMethod("setAutoHideCursor", &BaseWindow::SetAutoHideCursor) #endif .SetMethod("setVibrancy", &BaseWindow::SetVibrancy) .SetMethod("setBackgroundMaterial", &BaseWindow::SetBackgroundMaterial) #if BUILDFLAG(IS_MAC) .SetMethod("isHiddenInMissionControl", &BaseWindow::IsHiddenInMissionControl) .SetMethod("setHiddenInMissionControl", &BaseWindow::SetHiddenInMissionControl) #endif .SetMethod("_setTouchBarItems", &BaseWindow::SetTouchBar) .SetMethod("_refreshTouchBarItem", &BaseWindow::RefreshTouchBarItem) .SetMethod("_setEscapeTouchBarItem", &BaseWindow::SetEscapeTouchBarItem) #if BUILDFLAG(IS_MAC) .SetMethod("selectPreviousTab", &BaseWindow::SelectPreviousTab) .SetMethod("selectNextTab", &BaseWindow::SelectNextTab) .SetMethod("showAllTabs", &BaseWindow::ShowAllTabs) .SetMethod("mergeAllWindows", &BaseWindow::MergeAllWindows) .SetMethod("moveTabToNewWindow", &BaseWindow::MoveTabToNewWindow) .SetMethod("toggleTabBar", &BaseWindow::ToggleTabBar) .SetMethod("addTabbedWindow", &BaseWindow::AddTabbedWindow) .SetProperty("tabbingIdentifier", &BaseWindow::GetTabbingIdentifier) .SetMethod("setWindowButtonVisibility", &BaseWindow::SetWindowButtonVisibility) .SetMethod("_getWindowButtonVisibility", &BaseWindow::GetWindowButtonVisibility) .SetMethod("setWindowButtonPosition", &BaseWindow::SetWindowButtonPosition) .SetMethod("getWindowButtonPosition", &BaseWindow::GetWindowButtonPosition) .SetProperty("excludedFromShownWindowsMenu", &BaseWindow::IsExcludedFromShownWindowsMenu, &BaseWindow::SetExcludedFromShownWindowsMenu) #endif .SetMethod("setAutoHideMenuBar", &BaseWindow::SetAutoHideMenuBar) .SetMethod("isMenuBarAutoHide", &BaseWindow::IsMenuBarAutoHide) .SetMethod("setMenuBarVisibility", &BaseWindow::SetMenuBarVisibility) .SetMethod("isMenuBarVisible", &BaseWindow::IsMenuBarVisible) .SetMethod("setAspectRatio", &BaseWindow::SetAspectRatio) .SetMethod("previewFile", &BaseWindow::PreviewFile) .SetMethod("closeFilePreview", &BaseWindow::CloseFilePreview) .SetMethod("getContentView", &BaseWindow::GetContentView) .SetProperty("contentView", &BaseWindow::GetContentView, &BaseWindow::SetContentView) .SetMethod("getParentWindow", &BaseWindow::GetParentWindow) .SetMethod("getChildWindows", &BaseWindow::GetChildWindows) .SetMethod("isModal", &BaseWindow::IsModal) .SetMethod("setThumbarButtons", &BaseWindow::SetThumbarButtons) #if defined(TOOLKIT_VIEWS) .SetMethod("setIcon", &BaseWindow::SetIcon) #endif #if BUILDFLAG(IS_WIN) .SetMethod("hookWindowMessage", &BaseWindow::HookWindowMessage) .SetMethod("isWindowMessageHooked", &BaseWindow::IsWindowMessageHooked) .SetMethod("unhookWindowMessage", &BaseWindow::UnhookWindowMessage) .SetMethod("unhookAllWindowMessages", &BaseWindow::UnhookAllWindowMessages) .SetMethod("setThumbnailClip", &BaseWindow::SetThumbnailClip) .SetMethod("setThumbnailToolTip", &BaseWindow::SetThumbnailToolTip) .SetMethod("setAppDetails", &BaseWindow::SetAppDetails) #endif .SetProperty("id", &BaseWindow::GetID); } } // namespace electron::api namespace { using electron::api::BaseWindow; void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); BaseWindow::SetConstructor(isolate, base::BindRepeating(&BaseWindow::New)); gin_helper::Dictionary constructor(isolate, BaseWindow::GetConstructor(isolate) ->GetFunction(context) .ToLocalChecked()); constructor.SetMethod("fromId", &BaseWindow::FromWeakMapID); constructor.SetMethod("getAllWindows", &BaseWindow::GetAll); gin_helper::Dictionary dict(isolate, exports); dict.Set("BaseWindow", constructor); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_base_window, Initialize)
closed
electron/electron
https://github.com/electron/electron
38,955
[Bug]: `BrowserWindow.isVisible()` doesn't take into account occlusion state
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? macOS ### Operating System Version Ventura 13.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I found out that BrowserWindow on Mac started to take into account page occlusion state since this PR: https://github.com/electron/electron/pull/17463/files BrowserWindow.isVisible() should return false if window is occluded by another window. ### Actual Behavior BrowserWindow.isVisible() always returns true unless minimized. ### Testcase Gist URL https://gist.github.com/Imperat/0ecffacee8d1386258d67a91e0017644 ### Additional Information Provided fiddle is best way to reproduce the issue: move browser window to the corner (or another screen) and open another app on top of browserWindow. Observe that in fiddle console "visible true" still logged.
https://github.com/electron/electron/issues/38955
https://github.com/electron/electron/pull/38982
08236f7a9e9d664513e2b76b54b9bea003101e5d
768ece6b54f78e65efbea2c3fd39eea30e48332b
2023-06-30T00:50:25Z
c++
2024-02-06T10:30:35Z
shell/browser/api/electron_api_base_window.h
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_ #include <map> #include <memory> #include <optional> #include <string> #include <string_view> #include <vector> #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "gin/handle.h" #include "shell/browser/native_window.h" #include "shell/browser/native_window_observer.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/trackable_object.h" namespace electron::api { class View; class BaseWindow : public gin_helper::TrackableObject<BaseWindow>, public NativeWindowObserver { public: static gin_helper::WrappableBase* New(gin_helper::Arguments* args); static void BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype); base::WeakPtr<BaseWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } NativeWindow* window() const { return window_.get(); } protected: // Common constructor. BaseWindow(v8::Isolate* isolate, const gin_helper::Dictionary& options); // Creating independent BaseWindow instance. BaseWindow(gin_helper::Arguments* args, const gin_helper::Dictionary& options); ~BaseWindow() override; // TrackableObject: void InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) override; // NativeWindowObserver: void WillCloseWindow(bool* prevent_default) override; void OnWindowClosed() override; void OnWindowEndSession() override; void OnWindowBlur() override; void OnWindowFocus() override; void OnWindowShow() override; void OnWindowHide() override; void OnWindowMaximize() override; void OnWindowUnmaximize() override; void OnWindowMinimize() override; void OnWindowRestore() override; void OnWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) override; void OnWindowResize() override; void OnWindowResized() override; void OnWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) override; void OnWindowMove() override; void OnWindowMoved() override; void OnWindowSwipe(const std::string& direction) override; void OnWindowRotateGesture(float rotation) override; void OnWindowSheetBegin() override; void OnWindowSheetEnd() override; void OnWindowEnterFullScreen() override; void OnWindowLeaveFullScreen() override; void OnWindowEnterHtmlFullScreen() override; void OnWindowLeaveHtmlFullScreen() override; void OnWindowAlwaysOnTopChanged() override; void OnExecuteAppCommand(const std::string& command_name) override; void OnTouchBarItemResult(const std::string& item_id, const base::Value::Dict& details) override; void OnNewWindowForTab() override; void OnSystemContextMenu(int x, int y, bool* prevent_default) override; #if BUILDFLAG(IS_WIN) void OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) override; #endif // Public APIs of NativeWindow. void SetContentView(gin::Handle<View> view); void Close(); virtual void CloseImmediately(); virtual void Focus(); virtual void Blur(); bool IsFocused() const; void Show(); void ShowInactive(); void Hide(); bool IsVisible() const; bool IsEnabled() const; void SetEnabled(bool enable); void Maximize(); void Unmaximize(); bool IsMaximized() const; void Minimize(); void Restore(); bool IsMinimized() const; void SetFullScreen(bool fullscreen); bool IsFullscreen() const; void SetBounds(const gfx::Rect& bounds, gin_helper::Arguments* args); gfx::Rect GetBounds() const; void SetSize(int width, int height, gin_helper::Arguments* args); std::vector<int> GetSize() const; void SetContentSize(int width, int height, gin_helper::Arguments* args); std::vector<int> GetContentSize() const; void SetContentBounds(const gfx::Rect& bounds, gin_helper::Arguments* args); gfx::Rect GetContentBounds() const; bool IsNormal() const; gfx::Rect GetNormalBounds() const; void SetMinimumSize(int width, int height); std::vector<int> GetMinimumSize() const; void SetMaximumSize(int width, int height); std::vector<int> GetMaximumSize() const; void SetSheetOffset(double offsetY, gin_helper::Arguments* args); void SetResizable(bool resizable); bool IsResizable() const; void SetMovable(bool movable); void MoveAbove(const std::string& sourceId, gin_helper::Arguments* args); void MoveTop(); bool IsMovable() const; void SetMinimizable(bool minimizable); bool IsMinimizable() const; void SetMaximizable(bool maximizable); bool IsMaximizable() const; void SetFullScreenable(bool fullscreenable); bool IsFullScreenable() const; void SetClosable(bool closable); bool IsClosable() const; void SetAlwaysOnTop(bool top, gin_helper::Arguments* args); bool IsAlwaysOnTop() const; void Center(); void SetPosition(int x, int y, gin_helper::Arguments* args); std::vector<int> GetPosition() const; void SetTitle(const std::string& title); std::string GetTitle() const; void SetAccessibleTitle(const std::string& title); std::string GetAccessibleTitle() const; void FlashFrame(bool flash); void SetSkipTaskbar(bool skip); void SetExcludedFromShownWindowsMenu(bool excluded); bool IsExcludedFromShownWindowsMenu() const; void SetSimpleFullScreen(bool simple_fullscreen); bool IsSimpleFullScreen() const; void SetKiosk(bool kiosk); bool IsKiosk() const; bool IsTabletMode() const; virtual void SetBackgroundColor(const std::string& color_name); std::string GetBackgroundColor(gin_helper::Arguments* args) const; void InvalidateShadow(); void SetHasShadow(bool has_shadow); bool HasShadow() const; void SetOpacity(const double opacity); double GetOpacity() const; void SetShape(const std::vector<gfx::Rect>& rects); void SetRepresentedFilename(const std::string& filename); std::string GetRepresentedFilename() const; void SetDocumentEdited(bool edited); bool IsDocumentEdited() const; void SetIgnoreMouseEvents(bool ignore, gin_helper::Arguments* args); void SetContentProtection(bool enable); void SetFocusable(bool focusable); bool IsFocusable() const; void SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> menu); void RemoveMenu(); void SetParentWindow(v8::Local<v8::Value> value, gin_helper::Arguments* args); std::string GetMediaSourceId() const; v8::Local<v8::Value> GetNativeWindowHandle(); void SetProgressBar(double progress, gin_helper::Arguments* args); void SetOverlayIcon(const gfx::Image& overlay, const std::string& description); void SetVisibleOnAllWorkspaces(bool visible, gin_helper::Arguments* args); bool IsVisibleOnAllWorkspaces() const; void SetAutoHideCursor(bool auto_hide); virtual void SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value); void SetBackgroundMaterial(const std::string& vibrancy); #if BUILDFLAG(IS_MAC) std::string GetAlwaysOnTopLevel() const; void SetWindowButtonVisibility(bool visible); bool GetWindowButtonVisibility() const; void SetWindowButtonPosition(std::optional<gfx::Point> position); std::optional<gfx::Point> GetWindowButtonPosition() const; bool IsHiddenInMissionControl(); void SetHiddenInMissionControl(bool hidden); #endif void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items); void RefreshTouchBarItem(const std::string& item_id); void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item); void SelectPreviousTab(); void SelectNextTab(); void ShowAllTabs(); void MergeAllWindows(); void MoveTabToNewWindow(); void ToggleTabBar(); void AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args); v8::Local<v8::Value> GetTabbingIdentifier(); void SetAutoHideMenuBar(bool auto_hide); bool IsMenuBarAutoHide() const; void SetMenuBarVisibility(bool visible); bool IsMenuBarVisible() const; void SetAspectRatio(double aspect_ratio, gin_helper::Arguments* args); void PreviewFile(const std::string& path, gin_helper::Arguments* args); void CloseFilePreview(); void SetGTKDarkThemeEnabled(bool use_dark_theme); // Public getters of NativeWindow. v8::Local<v8::Value> GetContentView() const; v8::Local<v8::Value> GetParentWindow() const; std::vector<v8::Local<v8::Object>> GetChildWindows() const; bool IsModal() const; // Extra APIs added in JS. bool SetThumbarButtons(gin_helper::Arguments* args); #if defined(TOOLKIT_VIEWS) void SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon); void SetIconImpl(v8::Isolate* isolate, v8::Local<v8::Value> icon, NativeImage::OnConvertError on_error); #endif #if BUILDFLAG(IS_WIN) typedef base::RepeatingCallback<void(v8::Local<v8::Value>, v8::Local<v8::Value>)> MessageCallback; bool HookWindowMessage(UINT message, const MessageCallback& callback); bool IsWindowMessageHooked(UINT message); void UnhookWindowMessage(UINT message); void UnhookAllWindowMessages(); bool SetThumbnailClip(const gfx::Rect& region); bool SetThumbnailToolTip(const std::string& tooltip); void SetAppDetails(const gin_helper::Dictionary& options); #endif int32_t GetID() const; // Helpers. // Remove this window from parent window's |child_windows_|. void RemoveFromParentChildWindows(); template <typename... Args> void EmitEventSoon(std::string_view eventName) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(base::IgnoreResult(&BaseWindow::Emit<Args...>), weak_factory_.GetWeakPtr(), eventName)); } #if BUILDFLAG(IS_WIN) typedef std::map<UINT, MessageCallback> MessageCallbackMap; MessageCallbackMap messages_callback_map_; #endif v8::Global<v8::Value> content_view_; v8::Global<v8::Value> menu_; v8::Global<v8::Value> parent_window_; KeyWeakMap<int> child_windows_; std::unique_ptr<NativeWindow> window_; // Reference to JS wrapper to prevent garbage collection. v8::Global<v8::Value> self_ref_; base::WeakPtrFactory<BaseWindow> weak_factory_{this}; }; } // namespace electron::api #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
38,955
[Bug]: `BrowserWindow.isVisible()` doesn't take into account occlusion state
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? macOS ### Operating System Version Ventura 13.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I found out that BrowserWindow on Mac started to take into account page occlusion state since this PR: https://github.com/electron/electron/pull/17463/files BrowserWindow.isVisible() should return false if window is occluded by another window. ### Actual Behavior BrowserWindow.isVisible() always returns true unless minimized. ### Testcase Gist URL https://gist.github.com/Imperat/0ecffacee8d1386258d67a91e0017644 ### Additional Information Provided fiddle is best way to reproduce the issue: move browser window to the corner (or another screen) and open another app on top of browserWindow. Observe that in fiddle console "visible true" still logged.
https://github.com/electron/electron/issues/38955
https://github.com/electron/electron/pull/38982
08236f7a9e9d664513e2b76b54b9bea003101e5d
768ece6b54f78e65efbea2c3fd39eea30e48332b
2023-06-30T00:50:25Z
c++
2024-02-06T10:30:35Z
shell/browser/native_window.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #include <list> #include <memory> #include <optional> #include <queue> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/supports_user_data.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/web_contents_user_data.h" #include "electron/shell/common/api/api.mojom.h" #include "extensions/browser/app_window/size_constraints.h" #include "shell/browser/draggable_region_provider.h" #include "shell/browser/native_window_observer.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "ui/views/widget/widget_delegate.h" class SkRegion; namespace content { struct NativeWebKeyboardEvent; } namespace gfx { class Image; class Point; class Rect; enum class ResizeEdge; class Size; } // namespace gfx namespace gin_helper { class Dictionary; class PersistentDictionary; } // namespace gin_helper namespace electron { extern const char kElectronNativeWindowKey[]; class ElectronMenuModel; class BackgroundThrottlingSource; namespace api { class BrowserView; } #if BUILDFLAG(IS_MAC) typedef NSView* NativeWindowHandle; #else typedef gfx::AcceleratedWidget NativeWindowHandle; #endif class NativeWindow : public base::SupportsUserData, public views::WidgetDelegate { public: ~NativeWindow() override; // disable copy NativeWindow(const NativeWindow&) = delete; NativeWindow& operator=(const NativeWindow&) = delete; // Create window with existing WebContents, the caller is responsible for // managing the window's live. static NativeWindow* Create(const gin_helper::Dictionary& options, NativeWindow* parent = nullptr); void InitFromOptions(const gin_helper::Dictionary& options); virtual void SetContentView(views::View* view) = 0; virtual void Close() = 0; virtual void CloseImmediately() = 0; virtual bool IsClosed() const; virtual void Focus(bool focus) = 0; virtual bool IsFocused() const = 0; virtual void Show() = 0; virtual void ShowInactive() = 0; virtual void Hide() = 0; virtual bool IsVisible() const = 0; virtual bool IsEnabled() const = 0; virtual void SetEnabled(bool enable) = 0; virtual void Maximize() = 0; virtual void Unmaximize() = 0; virtual bool IsMaximized() const = 0; virtual void Minimize() = 0; virtual void Restore() = 0; virtual bool IsMinimized() const = 0; virtual void SetFullScreen(bool fullscreen) = 0; virtual bool IsFullscreen() const = 0; virtual void SetBounds(const gfx::Rect& bounds, bool animate = false) = 0; virtual gfx::Rect GetBounds() const = 0; virtual void SetSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetSize() const; virtual void SetPosition(const gfx::Point& position, bool animate = false); virtual gfx::Point GetPosition() const; virtual void SetContentSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetContentSize() const; virtual void SetContentBounds(const gfx::Rect& bounds, bool animate = false); virtual gfx::Rect GetContentBounds() const; virtual bool IsNormal() const; virtual gfx::Rect GetNormalBounds() const = 0; virtual void SetSizeConstraints( const extensions::SizeConstraints& window_constraints); virtual extensions::SizeConstraints GetSizeConstraints() const; virtual void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints); virtual extensions::SizeConstraints GetContentSizeConstraints() const; virtual void SetMinimumSize(const gfx::Size& size); virtual gfx::Size GetMinimumSize() const; virtual void SetMaximumSize(const gfx::Size& size); virtual gfx::Size GetMaximumSize() const; virtual gfx::Size GetContentMinimumSize() const; virtual gfx::Size GetContentMaximumSize() const; virtual void SetSheetOffset(const double offsetX, const double offsetY); virtual double GetSheetOffsetX() const; virtual double GetSheetOffsetY() const; virtual void SetResizable(bool resizable) = 0; virtual bool MoveAbove(const std::string& sourceId) = 0; virtual void MoveTop() = 0; virtual bool IsResizable() const = 0; virtual void SetMovable(bool movable) = 0; virtual bool IsMovable() const = 0; virtual void SetMinimizable(bool minimizable) = 0; virtual bool IsMinimizable() const = 0; virtual void SetMaximizable(bool maximizable) = 0; virtual bool IsMaximizable() const = 0; virtual void SetFullScreenable(bool fullscreenable) = 0; virtual bool IsFullScreenable() const = 0; virtual void SetClosable(bool closable) = 0; virtual bool IsClosable() const = 0; virtual void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level = "floating", int relativeLevel = 0) = 0; virtual ui::ZOrderLevel GetZOrderLevel() const = 0; virtual void Center() = 0; virtual void Invalidate() = 0; virtual void SetTitle(const std::string& title) = 0; virtual std::string GetTitle() const = 0; #if BUILDFLAG(IS_MAC) virtual std::string GetAlwaysOnTopLevel() const = 0; virtual void SetActive(bool is_key) = 0; virtual bool IsActive() const = 0; virtual void RemoveChildFromParentWindow() = 0; virtual void RemoveChildWindow(NativeWindow* child) = 0; virtual void AttachChildren() = 0; virtual void DetachChildren() = 0; #endif // Ability to augment the window title for the screen readers. void SetAccessibleTitle(const std::string& title); std::string GetAccessibleTitle(); virtual void FlashFrame(bool flash) = 0; virtual void SetSkipTaskbar(bool skip) = 0; virtual void SetExcludedFromShownWindowsMenu(bool excluded) = 0; virtual bool IsExcludedFromShownWindowsMenu() const = 0; virtual void SetSimpleFullScreen(bool simple_fullscreen) = 0; virtual bool IsSimpleFullScreen() const = 0; virtual void SetKiosk(bool kiosk) = 0; virtual bool IsKiosk() const = 0; virtual bool IsTabletMode() const; virtual void SetBackgroundColor(SkColor color) = 0; virtual SkColor GetBackgroundColor() const = 0; virtual void InvalidateShadow(); virtual void SetHasShadow(bool has_shadow) = 0; virtual bool HasShadow() const = 0; virtual void SetOpacity(const double opacity) = 0; virtual double GetOpacity() const = 0; virtual void SetRepresentedFilename(const std::string& filename); virtual std::string GetRepresentedFilename() const; virtual void SetDocumentEdited(bool edited); virtual bool IsDocumentEdited() const; virtual void SetIgnoreMouseEvents(bool ignore, bool forward) = 0; virtual void SetContentProtection(bool enable) = 0; virtual void SetFocusable(bool focusable); virtual bool IsFocusable() const; virtual void SetMenu(ElectronMenuModel* menu); virtual void SetParentWindow(NativeWindow* parent); virtual content::DesktopMediaID GetDesktopMediaID() const = 0; virtual gfx::NativeView GetNativeView() const = 0; virtual gfx::NativeWindow GetNativeWindow() const = 0; virtual gfx::AcceleratedWidget GetAcceleratedWidget() const = 0; virtual NativeWindowHandle GetNativeWindowHandle() const = 0; // Taskbar/Dock APIs. enum class ProgressState { kNone, // no progress, no marking kIndeterminate, // progress, indeterminate kError, // progress, errored (red) kPaused, // progress, paused (yellow) kNormal, // progress, not marked (green) }; virtual void SetProgressBar(double progress, const ProgressState state) = 0; virtual void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) = 0; // Workspace APIs. virtual void SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen = false, bool skipTransformProcessType = false) = 0; virtual bool IsVisibleOnAllWorkspaces() const = 0; virtual void SetAutoHideCursor(bool auto_hide); // Vibrancy API const std::string& vibrancy() const { return vibrancy_; } virtual void SetVibrancy(const std::string& type); const std::string& background_material() const { return background_material_; } virtual void SetBackgroundMaterial(const std::string& type); // Traffic Light API #if BUILDFLAG(IS_MAC) virtual void SetWindowButtonVisibility(bool visible) = 0; virtual bool GetWindowButtonVisibility() const = 0; virtual void SetWindowButtonPosition(std::optional<gfx::Point> position) = 0; virtual std::optional<gfx::Point> GetWindowButtonPosition() const = 0; virtual void RedrawTrafficLights() = 0; virtual void UpdateFrame() = 0; #endif // whether windows should be ignored by mission control #if BUILDFLAG(IS_MAC) virtual bool IsHiddenInMissionControl() const = 0; virtual void SetHiddenInMissionControl(bool hidden) = 0; #endif // Touchbar API virtual void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items); virtual void RefreshTouchBarItem(const std::string& item_id); virtual void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item); // Native Tab API virtual void SelectPreviousTab(); virtual void SelectNextTab(); virtual void ShowAllTabs(); virtual void MergeAllWindows(); virtual void MoveTabToNewWindow(); virtual void ToggleTabBar(); virtual bool AddTabbedWindow(NativeWindow* window); virtual std::optional<std::string> GetTabbingIdentifier() const; // Toggle the menu bar. virtual void SetAutoHideMenuBar(bool auto_hide); virtual bool IsMenuBarAutoHide() const; virtual void SetMenuBarVisibility(bool visible); virtual bool IsMenuBarVisible() const; // Set the aspect ratio when resizing window. double GetAspectRatio() const; gfx::Size GetAspectRatioExtraSize() const; virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size); // File preview APIs. virtual void PreviewFile(const std::string& path, const std::string& display_name); virtual void CloseFilePreview(); virtual void SetGTKDarkThemeEnabled(bool use_dark_theme) {} // Converts between content bounds and window bounds. virtual gfx::Rect ContentBoundsToWindowBounds( const gfx::Rect& bounds) const = 0; virtual gfx::Rect WindowBoundsToContentBounds( const gfx::Rect& bounds) const = 0; base::WeakPtr<NativeWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } virtual std::optional<gfx::Rect> GetWindowControlsOverlayRect(); virtual void SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect); // Methods called by the WebContents. virtual void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) {} // Public API used by platform-dependent delegates and observers to send UI // related notifications. void NotifyWindowRequestPreferredWidth(int* width); void NotifyWindowCloseButtonClicked(); void NotifyWindowClosed(); void NotifyWindowEndSession(); void NotifyWindowBlur(); void NotifyWindowFocus(); void NotifyWindowShow(); void NotifyWindowIsKeyChanged(bool is_key); void NotifyWindowHide(); void NotifyWindowMaximize(); void NotifyWindowUnmaximize(); void NotifyWindowMinimize(); void NotifyWindowRestore(); void NotifyWindowMove(); void NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default); void NotifyWindowResize(); void NotifyWindowResized(); void NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default); void NotifyWindowMoved(); void NotifyWindowSwipe(const std::string& direction); void NotifyWindowRotateGesture(float rotation); void NotifyWindowSheetBegin(); void NotifyWindowSheetEnd(); virtual void NotifyWindowEnterFullScreen(); virtual void NotifyWindowLeaveFullScreen(); void NotifyWindowEnterHtmlFullScreen(); void NotifyWindowLeaveHtmlFullScreen(); void NotifyWindowAlwaysOnTopChanged(); void NotifyWindowExecuteAppCommand(const std::string& command); void NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details); void NotifyNewWindowForTab(); void NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default); void NotifyLayoutWindowControlsOverlay(); #if BUILDFLAG(IS_WIN) void NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param); #endif void AddObserver(NativeWindowObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(NativeWindowObserver* obs) { observers_.RemoveObserver(obs); } // Handle fullscreen transitions. void HandlePendingFullscreenTransitions(); enum class FullScreenTransitionState { kEntering, kExiting, kNone }; void set_fullscreen_transition_state(FullScreenTransitionState state) { fullscreen_transition_state_ = state; } FullScreenTransitionState fullscreen_transition_state() const { return fullscreen_transition_state_; } enum class FullScreenTransitionType { kHTML, kNative, kNone }; void set_fullscreen_transition_type(FullScreenTransitionType type) { fullscreen_transition_type_ = type; } FullScreenTransitionType fullscreen_transition_type() const { return fullscreen_transition_type_; } views::Widget* widget() const { return widget_.get(); } views::View* content_view() const { return content_view_; } enum class TitleBarStyle { kNormal, kHidden, kHiddenInset, kCustomButtonsOnHover, }; TitleBarStyle title_bar_style() const { return title_bar_style_; } int titlebar_overlay_height() const { return titlebar_overlay_height_; } void set_titlebar_overlay_height(int height) { titlebar_overlay_height_ = height; } bool titlebar_overlay_enabled() const { return titlebar_overlay_; } bool has_frame() const { return has_frame_; } void set_has_frame(bool has_frame) { has_frame_ = has_frame; } bool has_client_frame() const { return has_client_frame_; } bool transparent() const { return transparent_; } bool enable_larger_than_screen() const { return enable_larger_than_screen_; } NativeWindow* parent() const { return parent_; } bool is_modal() const { return is_modal_; } int32_t window_id() const { return next_id_; } void add_child_window(NativeWindow* child) { child_windows_.push_back(child); } int NonClientHitTest(const gfx::Point& point); void AddDraggableRegionProvider(DraggableRegionProvider* provider); void RemoveDraggableRegionProvider(DraggableRegionProvider* provider); bool IsTranslucent() const; // Adds |source| to |background_throttling_sources_|, triggers update of // background throttling state. void AddBackgroundThrottlingSource(BackgroundThrottlingSource* source); // Removes |source| to |background_throttling_sources_|, triggers update of // background throttling state. void RemoveBackgroundThrottlingSource(BackgroundThrottlingSource* source); // Updates `ui::Compositor` background throttling state based on // |background_throttling_sources_|. If at least one of the sources disables // throttling, then throttling in the `ui::Compositor` will be disabled. void UpdateBackgroundThrottlingState(); protected: friend class api::BrowserView; NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent); // views::WidgetDelegate: views::Widget* GetWidget() override; const views::Widget* GetWidget() const override; std::u16string GetAccessibleWindowTitle() const override; void set_content_view(views::View* view) { content_view_ = view; } // The boolean parsing of the "titleBarOverlay" option bool titlebar_overlay_ = false; // The custom height parsed from the "height" option in a Object // "titleBarOverlay" int titlebar_overlay_height_ = 0; // The "titleBarStyle" option. TitleBarStyle title_bar_style_ = TitleBarStyle::kNormal; // Minimum and maximum size. std::optional<extensions::SizeConstraints> size_constraints_; // Same as above but stored as content size, we are storing 2 types of size // constraints beacause converting between them will cause rounding errors // on HiDPI displays on some environments. std::optional<extensions::SizeConstraints> content_size_constraints_; std::queue<bool> pending_transitions_; FullScreenTransitionState fullscreen_transition_state_ = FullScreenTransitionState::kNone; FullScreenTransitionType fullscreen_transition_type_ = FullScreenTransitionType::kNone; std::list<NativeWindow*> child_windows_; private: std::unique_ptr<views::Widget> widget_; static int32_t next_id_; // The content view, weak ref. raw_ptr<views::View> content_view_ = nullptr; // Whether window has standard frame. bool has_frame_ = true; // Whether window has standard frame, but it's drawn by Electron (the client // application) instead of the OS. Currently only has meaning on Linux for // Wayland hosts. bool has_client_frame_ = false; // Whether window is transparent. bool transparent_ = false; // Whether window can be resized larger than screen. bool enable_larger_than_screen_ = false; // The windows has been closed. bool is_closed_ = false; // Used to display sheets at the appropriate horizontal and vertical offsets // on macOS. double sheet_offset_x_ = 0.0; double sheet_offset_y_ = 0.0; // Used to maintain the aspect ratio of a view which is inside of the // content view. double aspect_ratio_ = 0.0; gfx::Size aspect_ratio_extraSize_; // The parent window, it is guaranteed to be valid during this window's life. raw_ptr<NativeWindow> parent_ = nullptr; // Is this a modal window. bool is_modal_ = false; std::list<DraggableRegionProvider*> draggable_region_providers_; // Observers of this window. base::ObserverList<NativeWindowObserver> observers_; std::set<BackgroundThrottlingSource*> background_throttling_sources_; // Accessible title. std::u16string accessible_title_; std::string vibrancy_; std::string background_material_; gfx::Rect overlay_rect_; base::WeakPtrFactory<NativeWindow> weak_factory_{this}; }; // This class provides a hook to get a NativeWindow from a WebContents. class NativeWindowRelay : public content::WebContentsUserData<NativeWindowRelay> { public: static void CreateForWebContents(content::WebContents*, base::WeakPtr<NativeWindow>); ~NativeWindowRelay() override; NativeWindow* GetNativeWindow() const { return native_window_.get(); } WEB_CONTENTS_USER_DATA_KEY_DECL(); private: friend class content::WebContentsUserData<NativeWindow>; explicit NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window); base::WeakPtr<NativeWindow> native_window_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
38,955
[Bug]: `BrowserWindow.isVisible()` doesn't take into account occlusion state
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? macOS ### Operating System Version Ventura 13.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I found out that BrowserWindow on Mac started to take into account page occlusion state since this PR: https://github.com/electron/electron/pull/17463/files BrowserWindow.isVisible() should return false if window is occluded by another window. ### Actual Behavior BrowserWindow.isVisible() always returns true unless minimized. ### Testcase Gist URL https://gist.github.com/Imperat/0ecffacee8d1386258d67a91e0017644 ### Additional Information Provided fiddle is best way to reproduce the issue: move browser window to the corner (or another screen) and open another app on top of browserWindow. Observe that in fiddle console "visible true" still logged.
https://github.com/electron/electron/issues/38955
https://github.com/electron/electron/pull/38982
08236f7a9e9d664513e2b76b54b9bea003101e5d
768ece6b54f78e65efbea2c3fd39eea30e48332b
2023-06-30T00:50:25Z
c++
2024-02-06T10:30:35Z
shell/browser/native_window_mac.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #import <Cocoa/Cocoa.h> #include <memory> #include <optional> #include <string> #include <vector> #include "electron/shell/common/api/api.mojom.h" #include "shell/browser/native_window.h" #include "ui/display/display_observer.h" #include "ui/native_theme/native_theme_observer.h" #include "ui/views/controls/native/native_view_host.h" @class ElectronNSWindow; @class ElectronNSWindowDelegate; @class ElectronPreviewItem; @class ElectronTouchBar; @class WindowButtonsProxy; namespace electron { class RootViewMac; class NativeWindowMac : public NativeWindow, public ui::NativeThemeObserver, public display::DisplayObserver { public: NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent); ~NativeWindowMac() override; // NativeWindow: void SetContentView(views::View* view) override; void Close() override; void CloseImmediately() override; void Focus(bool focus) override; bool IsFocused() const override; void Show() override; void ShowInactive() override; void Hide() override; bool IsVisible() const override; bool IsEnabled() const override; void SetEnabled(bool enable) override; void Maximize() override; void Unmaximize() override; bool IsMaximized() const override; void Minimize() override; void Restore() override; bool IsMinimized() const override; void SetFullScreen(bool fullscreen) override; bool IsFullscreen() const override; void SetBounds(const gfx::Rect& bounds, bool animate = false) override; gfx::Rect GetBounds() const override; bool IsNormal() const override; gfx::Rect GetNormalBounds() const override; void SetSizeConstraints( const extensions::SizeConstraints& window_constraints) override; void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) override; void SetResizable(bool resizable) override; bool MoveAbove(const std::string& sourceId) override; void MoveTop() override; bool IsResizable() const override; void SetMovable(bool movable) override; bool IsMovable() const override; void SetMinimizable(bool minimizable) override; bool IsMinimizable() const override; void SetMaximizable(bool maximizable) override; bool IsMaximizable() const override; void SetFullScreenable(bool fullscreenable) override; bool IsFullScreenable() const override; void SetClosable(bool closable) override; bool IsClosable() const override; void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relative_level) override; std::string GetAlwaysOnTopLevel() const override; ui::ZOrderLevel GetZOrderLevel() const override; void Center() override; void Invalidate() override; void SetTitle(const std::string& title) override; std::string GetTitle() const override; void FlashFrame(bool flash) override; void SetSkipTaskbar(bool skip) override; void SetExcludedFromShownWindowsMenu(bool excluded) override; bool IsExcludedFromShownWindowsMenu() const override; void SetSimpleFullScreen(bool simple_fullscreen) override; bool IsSimpleFullScreen() const override; void SetKiosk(bool kiosk) override; bool IsKiosk() const override; void SetBackgroundColor(SkColor color) override; SkColor GetBackgroundColor() const override; void InvalidateShadow() override; void SetHasShadow(bool has_shadow) override; bool HasShadow() const override; void SetOpacity(const double opacity) override; double GetOpacity() const override; void SetRepresentedFilename(const std::string& filename) override; std::string GetRepresentedFilename() const override; void SetDocumentEdited(bool edited) override; bool IsDocumentEdited() const override; void SetIgnoreMouseEvents(bool ignore, bool forward) override; bool IsHiddenInMissionControl() const override; void SetHiddenInMissionControl(bool hidden) override; void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; bool IsFocusable() const override; void SetParentWindow(NativeWindow* parent) override; content::DesktopMediaID GetDesktopMediaID() const override; gfx::NativeView GetNativeView() const override; gfx::NativeWindow GetNativeWindow() const override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; NativeWindowHandle GetNativeWindowHandle() const override; void SetProgressBar(double progress, const ProgressState state) override; void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) override; void SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) override; bool IsVisibleOnAllWorkspaces() const override; void SetAutoHideCursor(bool auto_hide) override; void SetVibrancy(const std::string& type) override; void SetWindowButtonVisibility(bool visible) override; bool GetWindowButtonVisibility() const override; void SetWindowButtonPosition(std::optional<gfx::Point> position) override; std::optional<gfx::Point> GetWindowButtonPosition() const override; void RedrawTrafficLights() override; void UpdateFrame() override; void SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) override; void RefreshTouchBarItem(const std::string& item_id) override; void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) override; void SelectPreviousTab() override; void SelectNextTab() override; void ShowAllTabs() override; void MergeAllWindows() override; void MoveTabToNewWindow() override; void ToggleTabBar() override; bool AddTabbedWindow(NativeWindow* window) override; std::optional<std::string> GetTabbingIdentifier() const override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void PreviewFile(const std::string& path, const std::string& display_name) override; void CloseFilePreview() override; gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override; gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override; std::optional<gfx::Rect> GetWindowControlsOverlayRect() override; void NotifyWindowEnterFullScreen() override; void NotifyWindowLeaveFullScreen() override; void SetActive(bool is_key) override; bool IsActive() const override; // Remove the specified child window without closing it. void RemoveChildWindow(NativeWindow* child) override; void RemoveChildFromParentWindow() override; // Attach child windows, if the window is visible. void AttachChildren() override; // Detach window from parent without destroying it. void DetachChildren() override; void NotifyWindowWillEnterFullScreen(); void NotifyWindowWillLeaveFullScreen(); // Cleanup observers when window is getting closed. Note that the destructor // can be called much later after window gets closed, so we should not do // cleanup in destructor. void Cleanup(); void UpdateVibrancyRadii(bool fullscreen); void UpdateWindowOriginalFrame(); // Set the attribute of NSWindow while work around a bug of zoom button. bool HasStyleMask(NSUInteger flag) const; void SetStyleMask(bool on, NSUInteger flag); void SetCollectionBehavior(bool on, NSUInteger flag); void SetWindowLevel(int level); bool HandleDeferredClose(); void SetHasDeferredWindowClose(bool defer_close) { has_deferred_window_close_ = defer_close; } void set_wants_to_be_visible(bool visible) { wants_to_be_visible_ = visible; } bool wants_to_be_visible() const { return wants_to_be_visible_; } enum class VisualEffectState { kFollowWindow, kActive, kInactive, }; ElectronPreviewItem* preview_item() const { return preview_item_; } ElectronTouchBar* touch_bar() const { return touch_bar_; } bool zoom_to_page_width() const { return zoom_to_page_width_; } bool always_simple_fullscreen() const { return always_simple_fullscreen_; } // We need to save the result of windowWillUseStandardFrame:defaultFrame // because macOS calls it with what it refers to as the "best fit" frame for a // zoom. This means that even if an aspect ratio is set, macOS might adjust it // to better fit the screen. // // Thus, we can't just calculate the maximized aspect ratio'd sizing from // the current visible screen and compare that to the current window's frame // to determine whether a window is maximized. NSRect default_frame_for_zoom() const { return default_frame_for_zoom_; } void set_default_frame_for_zoom(NSRect frame) { default_frame_for_zoom_ = frame; } protected: // views::WidgetDelegate: views::View* GetContentsView() override; bool CanMaximize() const override; std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView( views::Widget* widget) override; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; // display::DisplayObserver: void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; private: // Add custom layers to the content view. void AddContentViewLayers(); void InternalSetWindowButtonVisibility(bool visible); void InternalSetParentWindow(NativeWindow* parent, bool attach); void SetForwardMouseMessages(bool forward); void UpdateZoomButton(); ElectronNSWindow* window_; // Weak ref, managed by widget_. ElectronNSWindowDelegate* __strong window_delegate_; ElectronPreviewItem* __strong preview_item_; ElectronTouchBar* __strong touch_bar_; // The views::View that fills the client area. std::unique_ptr<RootViewMac> root_view_; bool fullscreen_before_kiosk_ = false; bool is_kiosk_ = false; bool zoom_to_page_width_ = false; std::optional<gfx::Point> traffic_light_position_; // Trying to close an NSWindow during a fullscreen transition will cause the // window to lock up. Use this to track if CloseWindow was called during a // fullscreen transition, to defer the -[NSWindow close] call until the // transition is complete. bool has_deferred_window_close_ = false; // If true, the window is either visible, or wants to be visible but is // currently hidden due to having a hidden parent. bool wants_to_be_visible_ = false; NSInteger attention_request_id_ = 0; // identifier from requestUserAttention // The presentation options before entering kiosk mode. NSApplicationPresentationOptions kiosk_options_; // The "visualEffectState" option. VisualEffectState visual_effect_state_ = VisualEffectState::kFollowWindow; // The visibility mode of window button controls when explicitly set through // setWindowButtonVisibility(). std::optional<bool> window_button_visibility_; // Controls the position and visibility of window buttons. WindowButtonsProxy* __strong buttons_proxy_; std::unique_ptr<SkRegion> draggable_region_; // Maximizable window state; necessary for persistence through redraws. bool maximizable_ = true; bool user_set_bounds_maximized_ = false; // Simple (pre-Lion) Fullscreen Settings bool always_simple_fullscreen_ = false; bool is_simple_fullscreen_ = false; bool was_maximizable_ = false; bool was_movable_ = false; bool is_active_ = false; NSRect original_frame_; NSInteger original_level_; NSUInteger simple_fullscreen_mask_; NSRect default_frame_for_zoom_; std::string vibrancy_type_; // The presentation options before entering simple fullscreen mode. NSApplicationPresentationOptions simple_fullscreen_options_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
closed
electron/electron
https://github.com/electron/electron
38,955
[Bug]: `BrowserWindow.isVisible()` doesn't take into account occlusion state
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? macOS ### Operating System Version Ventura 13.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I found out that BrowserWindow on Mac started to take into account page occlusion state since this PR: https://github.com/electron/electron/pull/17463/files BrowserWindow.isVisible() should return false if window is occluded by another window. ### Actual Behavior BrowserWindow.isVisible() always returns true unless minimized. ### Testcase Gist URL https://gist.github.com/Imperat/0ecffacee8d1386258d67a91e0017644 ### Additional Information Provided fiddle is best way to reproduce the issue: move browser window to the corner (or another screen) and open another app on top of browserWindow. Observe that in fiddle console "visible true" still logged.
https://github.com/electron/electron/issues/38955
https://github.com/electron/electron/pull/38982
08236f7a9e9d664513e2b76b54b9bea003101e5d
768ece6b54f78e65efbea2c3fd39eea30e48332b
2023-06-30T00:50:25Z
c++
2024-02-06T10:30:35Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/apple/scoped_cftyperef.h" #include "base/mac/mac_util.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } bool IsPanel(NSWindow* window) { return [window isKindOfClass:[NSPanel class]]; } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); widget()->SetNativeWindowProperty(kElectronNativeWindowKey, this); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this]; [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_]; [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { // If we're a panel window, we do not want to activate the app, // which enables Electron-apps to build Spotlight-like experiences. // // On macOS < Sonoma, "activateIgnoringOtherApps:NO" would not // activate apps if focusing a window that is inActive. That // changed with macOS Sonoma, which also deprecated // "activateIgnoringOtherApps". For the panel-specific usecase, // we can simply replace "activateIgnoringOtherApps:NO" with // "activate". For details on why we cannot replace all calls 1:1, // please see // https://github.com/electron/electron/pull/40307#issuecomment-1801976591. // // There's a slim chance we should have never called // activateIgnoringOtherApps, but we tried that many years ago // and saw weird focus bugs on other macOS versions. So, to make // this safe, we're gating by versions. if (@available(macOS 14.0, *)) { if (!IsPanel(window_)) { [[NSApplication sharedApplication] activate]; } else { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; } } else { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; } [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() const { 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; } set_wants_to_be_visible(true); // 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() { set_wants_to_be_visible(true); // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // If the window wants to be visible and has a parent, then the parent may // order it back in (in the period between orderOut: and close). set_wants_to_be_visible(false); DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() const { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() const { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() const { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() const { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow() { if (parent() && !is_modal()) { parent()->RemoveChildWindow(this); NativeWindow::SetParentWindow(nullptr); } } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { if (!static_cast<NativeWindowMac*>(child)->wants_to_be_visible()) continue; auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } void NativeWindowMac::SetFullScreen(bool fullscreen) { // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; if (![window_ toggleFullScreenMode:nil]) fullscreen_transition_state_ = FullScreenTransitionState::kNone; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() const { 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() const { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() const { 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::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { // Apply the size constraints to NSWindow. if (window_constraints.HasMinimumSize()) [window_ setMinSize:window_constraints.GetMinimumSize().ToCGSize()]; if (window_constraints.HasMaximumSize()) [window_ setMaxSize:window_constraints.GetMaximumSize().ToCGSize()]; NativeWindow::SetSizeConstraints(window_constraints); } 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()); } }; // Apply the size constraints to NSWindow. NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:0]; } else { ReorderChildWindowAbove(window_, nullptr); } } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); bool was_fullscreenable = IsFullScreenable(); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreen collection behavior as well as the maximize traffic // light in SetCanResize if resizability is false on macOS unless // the window is both resizable and maximizable. We want consistent // cross-platform behavior, so if resizability is disabled we disable // the maximize button and ensure fullscreenability matches user setting. SetCanResize(resizable); SetFullScreenable(was_fullscreenable); UpdateZoomButton(); } bool NativeWindowMac::IsResizable() const { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() const { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() const { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; UpdateZoomButton(); } bool NativeWindowMac::IsMaximizable() const { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::UpdateZoomButton() { [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:HasStyleMask(NSWindowStyleMaskResizable) && (CanMaximize() || IsFullScreenable())]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); UpdateZoomButton(); } bool NativeWindowMac::IsFullScreenable() const { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() const { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() const { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() const { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() const { 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() const { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() const { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() const { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::apple::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor.get()]; } SkColor NativeWindowMac::GetBackgroundColor() const { 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() const { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() const { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() const { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() const { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() const { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() const { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[NSImageView alloc] init]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[ElectronProgressBar alloc] initWithFrame:frame]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() const { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); const int macos_version = base::mac::MacOSMajorVersion(); const bool modal = is_modal(); // If the window is modal, its corners are rounded on macOS >= 11 or higher // unless the user has explicitly passed noRoundedCorners. bool should_round_modal = !no_rounded_corner && macos_version >= 11 && modal; // If the window is nonmodal, its corners are rounded if it is frameless and // the user hasn't passed noRoundedCorners. bool should_round_nonmodal = !no_rounded_corner && !modal && !has_frame(); if (should_round_nonmodal || should_round_modal) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (macos_version >= 11) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NativeWindow::SetVibrancy(type); NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( std::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } std::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ window:this settings:std::move(items)]; [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::ShowAllTabs() { [window_ toggleTabOverview:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } std::optional<std::string> NativeWindowMac::GetTabbingIdentifier() const { if ([window_ tabbingMode] == NSWindowTabbingModeDisallowed) return std::nullopt; return base::SysNSStringToUTF8([window_ tabbingIdentifier]); } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_ = [[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]; [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:NO]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:YES]; } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { CALayer* background_layer = [[CALayer alloc] init]; [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(); // Set new parent window. if (new_parent) { new_parent->add_child_window(this); if (attach) new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } std::optional<gfx::Rect> NativeWindowMac::GetWindowControlsOverlayRect() { if (!titlebar_overlay_) return std::nullopt; // On macOS, when in fullscreen mode, window controls (the menu bar, title // bar, and toolbar) are attached to a separate NSView that slides down from // the top of the screen, independent of, and overlapping the WebContents. // Disable WCO when in fullscreen, because this space is inaccessible to // WebContents. https://crbug.com/915110. if (IsFullscreen()) return gfx::Rect(); if (buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); overlay.set_height([buttons_proxy_ useCustomHeight] ? titlebar_overlay_height() : NSHeight(buttons)); if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return std::nullopt; } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,955
[Bug]: `BrowserWindow.isVisible()` doesn't take into account occlusion state
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? macOS ### Operating System Version Ventura 13.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I found out that BrowserWindow on Mac started to take into account page occlusion state since this PR: https://github.com/electron/electron/pull/17463/files BrowserWindow.isVisible() should return false if window is occluded by another window. ### Actual Behavior BrowserWindow.isVisible() always returns true unless minimized. ### Testcase Gist URL https://gist.github.com/Imperat/0ecffacee8d1386258d67a91e0017644 ### Additional Information Provided fiddle is best way to reproduce the issue: move browser window to the corner (or another screen) and open another app on top of browserWindow. Observe that in fiddle console "visible true" still logged.
https://github.com/electron/electron/issues/38955
https://github.com/electron/electron/pull/38982
08236f7a9e9d664513e2b76b54b9bea003101e5d
768ece6b54f78e65efbea2c3fd39eea30e48332b
2023-06-30T00:50:25Z
c++
2024-02-06T10:30:35Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. // FIXME(ckerr) this incorrect #include order is a temporary // fix to unblock the roll. Will fix in an upgrade followup. #include "ui/base/ozone_buildflags.h" #if BUILDFLAG(IS_OZONE_X11) #include "ui/base/x/x11_util.h" #endif #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <dwmapi.h> #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/containers/contains.h" #include "base/memory/raw_ptr.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/views/inspectable_web_contents_view_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/ozone/public/ozone_platform.h" #include "ui/views/background.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "shell/common/platform_util.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if BUILDFLAG(IS_OZONE_X11) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/gfx/x/atom_cache.h" #include "ui/gfx/x/connection.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/xproto.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "base/win/windows_version.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/win/msg_util.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) DWM_SYSTEMBACKDROP_TYPE GetBackdropFromString(const std::string& material) { if (material == "none") { return DWMSBT_NONE; } else if (material == "acrylic") { return DWMSBT_TRANSIENTWINDOW; } else if (material == "mica") { return DWMSBT_MAINWINDOW; } else if (material == "tabbed") { return DWMSBT_TABBEDWINDOW; } return DWMSBT_AUTO; } // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } // Chromium uses a buggy implementation that converts content rect to window // rect when calculating min/max size, we should use the same implementation // when passing min/max size so we can get correct results. gfx::Size WindowSizeToContentSizeBuggy(HWND hwnd, const gfx::Size& size) { // Calculate the size of window frame, using same code with the // HWNDMessageHandler::OnGetMinMaxInfo method. // The pitfall is, when window is minimized the calculated window frame size // will be different from other states. RECT client_rect, rect; GetClientRect(hwnd, &client_rect); GetWindowRect(hwnd, &rect); CR_DEFLATE_RECT(&rect, &client_rect); // Convert DIP size to pixel size, do calculation and then return DIP size. gfx::Rect screen_rect = DIPToScreenRect(hwnd, gfx::Rect(size)); gfx::Size screen_client_size(screen_rect.width() - (rect.right - rect.left), screen_rect.height() - (rect.bottom - rect.top)); return ScreenToDIPRect(hwnd, gfx::Rect(screen_client_size)).size(); } #endif [[maybe_unused]] bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView{widget, root_view}, window_{raw_ref<NativeWindowViews>::from_ptr(window)} {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: const raw_ref<NativeWindowViews> window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_.SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { auto titlebar_overlay_obj = gin_helper::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); // If the taskbar is re-created after we start up, we have to rebuild all of // our buttons. taskbar_created_message_ = RegisterWindowMessage(TEXT("TaskbarCreated")); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (IsTranslucent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it is translucent and // has no standard frame, don't show a shadow for it. if (IsTranslucent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; // Set Wayland application ID. params.wayland_app_id = platform_util::GetXdgAppId(); auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); widget()->SetNativeWindowProperty(kElectronNativeWindowKey, this); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); if (IsX11()) { // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) { auto* connection = x11::Connection::Get(); connection->SetArrayProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); } // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if BUILDFLAG(IS_LINUX) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; auto* connection = x11::Connection::Get(); connection->SetStringProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_.RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_.AddChildView(content_view()); root_view_.Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() const { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if BUILDFLAG(IS_LINUX) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); // On X11, setting Z order before showing the window doesn't take effect, // so we have to call it again. if (IsX11()) widget()->SetZOrderLevel(widget()->GetZOrderLevel()); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if BUILDFLAG(IS_LINUX) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if BUILDFLAG(IS_LINUX) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() const { #if BUILDFLAG(IS_WIN) // widget()->IsVisible() calls ::IsWindowVisible, which returns non-zero if a // window or any of its parent windows are visible. We want to only check the // current window. bool visible = ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_VISIBLE; // WS_VISIBLE is true even if a window is miminized - explicitly check that. return visible && !IsMinimized(); #else return widget()->IsVisible(); #endif } bool NativeWindowViews::IsEnabled() const { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) if (IsX11()) return !event_disabler_.get(); NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() const { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #else if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); UpdateThickFrame(); return; } #endif widget()->Restore(); #if BUILDFLAG(IS_WIN) UpdateThickFrame(); #endif } } bool NativeWindowViews::IsMaximized() const { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent() && !IsMinimized()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); #if BUILDFLAG(IS_WIN) UpdateThickFrame(); #endif } bool NativeWindowViews::IsMinimized() const { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) { menu_bar_visible_before_fullscreen_ = IsMenuBarVisible(); SetMenuBarVisibility(false); } else { SetMenuBarVisibility(!IsMenuBarAutoHide() && menu_bar_visible_before_fullscreen_); menu_bar_visible_before_fullscreen_ = false; } #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() const { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() const { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() const { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() const { #if BUILDFLAG(IS_WIN) if (IsMaximized() && transparent()) return restore_bounds_; #endif return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } #if BUILDFLAG(IS_WIN) // This override does almost the same with its parent, except that it uses // the WindowSizeToContentSizeBuggy method to convert window size to content // size. See the comment of the method for the reason behind this. extensions::SizeConstraints NativeWindowViews::GetContentSizeConstraints() const { if (content_size_constraints_) return *content_size_constraints_; if (!size_constraints_) return extensions::SizeConstraints(); extensions::SizeConstraints constraints; if (size_constraints_->HasMaximumSize()) { constraints.set_maximum_size(WindowSizeToContentSizeBuggy( GetAcceleratedWidget(), size_constraints_->GetMaximumSize())); } if (size_constraints_->HasMinimumSize()) { constraints.set_minimum_size(WindowSizeToContentSizeBuggy( GetAcceleratedWidget(), size_constraints_->GetMinimumSize())); } return constraints; } #endif void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } resizable_ = resizable; SetCanResize(resizable_); #if BUILDFLAG(IS_WIN) UpdateThickFrame(); #endif } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #else if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #else if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() const { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() const { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() const { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() const { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() const { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() const { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() const { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() const { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() const { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() const { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() const { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() const { auto* background = root_view_.background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_.SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), nullptr, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() const { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() const { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #else if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() const { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if BUILDFLAG(IS_LINUX) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_.UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. bool can_use_global_menus = ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; if (can_use_global_menus && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_.RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_.HasMenu()); root_view_.SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_.GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if BUILDFLAG(IS_LINUX) if (IsX11()) { auto* connection = x11::Connection::Get(); connection->SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); } #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : nullptr; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_.SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() const { return root_view_.is_menu_bar_auto_hide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_.SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() const { return root_view_.is_menu_bar_visible(); } void NativeWindowViews::SetBackgroundMaterial(const std::string& material) { NativeWindow::SetBackgroundMaterial(material); #if BUILDFLAG(IS_WIN) // DWMWA_USE_HOSTBACKDROPBRUSH is only supported on Windows 11 22H2 and up. if (base::win::GetVersion() < base::win::Version::WIN11_22H2) return; DWM_SYSTEMBACKDROP_TYPE backdrop_type = GetBackdropFromString(material); HRESULT result = DwmSetWindowAttribute(GetAcceleratedWidget(), DWMWA_SYSTEMBACKDROP_TYPE, &backdrop_type, sizeof(backdrop_type)); if (FAILED(result)) LOG(WARNING) << "Failed to set background material to " << material; // For frameless windows with a background material set, we also need to // remove the caption color so it doesn't render a caption bar (since the // window is frameless) COLORREF caption_color = DWMWA_COLOR_DEFAULT; if (backdrop_type != DWMSBT_NONE && backdrop_type != DWMSBT_AUTO && !has_frame()) { caption_color = DWMWA_COLOR_NONE; } result = DwmSetWindowAttribute(GetAcceleratedWidget(), DWMWA_CAPTION_COLOR, &caption_color, sizeof(caption_color)); if (FAILED(result)) LOG(WARNING) << "Failed to set caption color to transparent"; #endif } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() const { #if BUILDFLAG(IS_LINUX) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; auto* connection = x11::Connection::Get(); connection->GetArrayProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return base::Contains(wm_states, sticky_atom); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_.HasMenu() && root_view_.is_menu_bar_visible()) { int menu_bar_height = root_view_.GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_.HasMenu() && root_view_.is_menu_bar_visible()) { int menu_bar_height = root_view_.GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif #if BUILDFLAG(IS_WIN) void NativeWindowViews::UpdateThickFrame() { if (!thick_frame_) return; if (IsMaximized() && !transparent()) { // For maximized window add thick frame always, otherwise it will be removed // in HWNDMessageHandler::SizeConstraintsChanged() which will result in // maximized window bounds change. FlipWindowStyle(GetAcceleratedWidget(), true, WS_THICKFRAME); } else if (has_frame()) { FlipWindowStyle(GetAcceleratedWidget(), resizable_, WS_THICKFRAME); } } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_.ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return &root_view_; } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { return NonClientHitTest(location) == HTNOWHERE; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView{widget, GetContentsView(), this}; } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_.HandleKeyboardEvent(event, root_view_.GetFocusManager()); root_view_.HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_.ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,955
[Bug]: `BrowserWindow.isVisible()` doesn't take into account occlusion state
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? macOS ### Operating System Version Ventura 13.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I found out that BrowserWindow on Mac started to take into account page occlusion state since this PR: https://github.com/electron/electron/pull/17463/files BrowserWindow.isVisible() should return false if window is occluded by another window. ### Actual Behavior BrowserWindow.isVisible() always returns true unless minimized. ### Testcase Gist URL https://gist.github.com/Imperat/0ecffacee8d1386258d67a91e0017644 ### Additional Information Provided fiddle is best way to reproduce the issue: move browser window to the corner (or another screen) and open another app on top of browserWindow. Observe that in fiddle console "visible true" still logged.
https://github.com/electron/electron/issues/38955
https://github.com/electron/electron/pull/38982
08236f7a9e9d664513e2b76b54b9bea003101e5d
768ece6b54f78e65efbea2c3fd39eea30e48332b
2023-06-30T00:50:25Z
c++
2024-02-06T10:30:35Z
shell/browser/native_window_views.h
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_ #include "shell/browser/native_window.h" #include <memory> #include <optional> #include <set> #include <string> #include "base/memory/raw_ptr.h" #include "shell/browser/ui/views/root_view.h" #include "ui/base/ozone_buildflags.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/widget/widget_observer.h" #if BUILDFLAG(IS_WIN) #include "base/win/scoped_gdi_object.h" #include "shell/browser/ui/win/taskbar_host.h" #endif namespace electron { #if BUILDFLAG(IS_LINUX) class GlobalMenuBarX11; #endif #if BUILDFLAG(IS_OZONE_X11) class EventDisabler; #endif #if BUILDFLAG(IS_WIN) gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds); #endif class NativeWindowViews : public NativeWindow, public views::WidgetObserver, public ui::EventHandler { public: NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent); ~NativeWindowViews() override; // NativeWindow: void SetContentView(views::View* view) override; void Close() override; void CloseImmediately() override; void Focus(bool focus) override; bool IsFocused() const override; void Show() override; void ShowInactive() override; void Hide() override; bool IsVisible() const override; bool IsEnabled() const override; void SetEnabled(bool enable) override; void Maximize() override; void Unmaximize() override; bool IsMaximized() const override; void Minimize() override; void Restore() override; bool IsMinimized() const override; void SetFullScreen(bool fullscreen) override; bool IsFullscreen() const override; void SetBounds(const gfx::Rect& bounds, bool animate) override; gfx::Rect GetBounds() const override; gfx::Rect GetContentBounds() const override; gfx::Size GetContentSize() const override; gfx::Rect GetNormalBounds() const override; SkColor GetBackgroundColor() const override; void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) override; #if BUILDFLAG(IS_WIN) extensions::SizeConstraints GetContentSizeConstraints() const override; #endif void SetResizable(bool resizable) override; bool MoveAbove(const std::string& sourceId) override; void MoveTop() override; bool IsResizable() const override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void SetMovable(bool movable) override; bool IsMovable() const override; void SetMinimizable(bool minimizable) override; bool IsMinimizable() const override; void SetMaximizable(bool maximizable) override; bool IsMaximizable() const override; void SetFullScreenable(bool fullscreenable) override; bool IsFullScreenable() const override; void SetClosable(bool closable) override; bool IsClosable() const override; void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) override; ui::ZOrderLevel GetZOrderLevel() const override; void Center() override; void Invalidate() override; void SetTitle(const std::string& title) override; std::string GetTitle() const override; void FlashFrame(bool flash) override; void SetSkipTaskbar(bool skip) override; void SetExcludedFromShownWindowsMenu(bool excluded) override; bool IsExcludedFromShownWindowsMenu() const override; void SetSimpleFullScreen(bool simple_fullscreen) override; bool IsSimpleFullScreen() const override; void SetKiosk(bool kiosk) override; bool IsKiosk() const override; bool IsTabletMode() const override; void SetBackgroundColor(SkColor color) override; void SetHasShadow(bool has_shadow) override; bool HasShadow() const override; void SetOpacity(const double opacity) override; double GetOpacity() const override; void SetIgnoreMouseEvents(bool ignore, bool forward) override; void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; bool IsFocusable() const override; void SetMenu(ElectronMenuModel* menu_model) override; void SetParentWindow(NativeWindow* parent) override; gfx::NativeView GetNativeView() const override; gfx::NativeWindow GetNativeWindow() const override; void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) override; void SetProgressBar(double progress, const ProgressState state) override; void SetAutoHideMenuBar(bool auto_hide) override; bool IsMenuBarAutoHide() const override; void SetMenuBarVisibility(bool visible) override; bool IsMenuBarVisible() const override; void SetBackgroundMaterial(const std::string& type) override; void SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) override; bool IsVisibleOnAllWorkspaces() const override; void SetGTKDarkThemeEnabled(bool use_dark_theme) override; content::DesktopMediaID GetDesktopMediaID() const override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; NativeWindowHandle GetNativeWindowHandle() const override; gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override; gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override; void IncrementChildModals(); void DecrementChildModals(); #if BUILDFLAG(IS_WIN) // Catch-all message handling and filtering. Called before // HWNDMessageHandler's built-in handling, which may pre-empt some // expectations in Views/Aura if messages are consumed. Returns true if the // message was consumed by the delegate and should not be processed further // by the HWNDMessageHandler. In this case, |result| is returned. |result| is // not modified otherwise. bool PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result); void SetIcon(HICON small_icon, HICON app_icon); #elif BUILDFLAG(IS_LINUX) void SetIcon(const gfx::ImageSkia& icon); #endif #if BUILDFLAG(IS_WIN) TaskbarHost& taskbar_host() { return taskbar_host_; } #endif #if BUILDFLAG(IS_WIN) bool IsWindowControlsOverlayEnabled() const { return (title_bar_style_ == NativeWindowViews::TitleBarStyle::kHidden) && titlebar_overlay_; } SkColor overlay_button_color() const { return overlay_button_color_; } void set_overlay_button_color(SkColor color) { overlay_button_color_ = color; } SkColor overlay_symbol_color() const { return overlay_symbol_color_; } void set_overlay_symbol_color(SkColor color) { overlay_symbol_color_ = color; } void UpdateThickFrame(); #endif private: // views::WidgetObserver: void OnWidgetActivationChanged(views::Widget* widget, bool active) override; void OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& bounds) override; void OnWidgetDestroying(views::Widget* widget) override; void OnWidgetDestroyed(views::Widget* widget) override; // views::WidgetDelegate: views::View* GetInitiallyFocusedView() override; bool CanMaximize() const override; bool CanMinimize() const override; std::u16string GetWindowTitle() const override; views::View* GetContentsView() override; bool ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) override; views::ClientView* CreateClientView(views::Widget* widget) override; std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView( views::Widget* widget) override; void OnWidgetMove() override; #if BUILDFLAG(IS_WIN) bool ExecuteWindowsCommand(int command_id) override; #endif #if BUILDFLAG(IS_WIN) void HandleSizeEvent(WPARAM w_param, LPARAM l_param); void ResetWindowControls(); void SetForwardMouseMessages(bool forward); static LRESULT CALLBACK SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data); static LRESULT CALLBACK MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param); #endif // Enable/disable: bool ShouldBeEnabled() const; void SetEnabledInternal(bool enabled); // NativeWindow: void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) override; // ui::EventHandler: void OnMouseEvent(ui::MouseEvent* event) override; // Returns the restore state for the window. ui::WindowShowState GetRestoredState(); // Maintain window placement. void MoveBehindTaskBarIfNeeded(); RootView root_view_{this}; // The view should be focused by default. raw_ptr<views::View> focused_view_ = nullptr; // The "resizable" flag on Linux is implemented by setting size constraints, // we need to make sure size constraints are restored when window becomes // resizable again. This is also used on Windows, to keep taskbar resize // events from resizing the window. extensions::SizeConstraints old_size_constraints_; #if BUILDFLAG(IS_LINUX) std::unique_ptr<GlobalMenuBarX11> global_menu_bar_; #endif #if BUILDFLAG(IS_OZONE_X11) // To disable the mouse events. std::unique_ptr<EventDisabler> event_disabler_; #endif #if BUILDFLAG(IS_WIN) ui::WindowShowState last_window_state_; gfx::Rect last_normal_placement_bounds_; // In charge of running taskbar related APIs. TaskbarHost taskbar_host_; // Memoized version of a11y check bool checked_for_a11y_support_ = false; // Whether to show the WS_THICKFRAME style. bool thick_frame_ = true; // The bounds of window before maximize/fullscreen. gfx::Rect restore_bounds_; // The icons of window and taskbar. base::win::ScopedHICON window_icon_; base::win::ScopedHICON app_icon_; // The set of windows currently forwarding mouse messages. static std::set<NativeWindowViews*> forwarding_windows_; static HHOOK mouse_hook_; bool forwarding_mouse_messages_ = false; HWND legacy_window_ = nullptr; bool layered_ = false; // Set to true if the window is always on top and behind the task bar. bool behind_task_bar_ = false; // Whether we want to set window placement without side effect. bool is_setting_window_placement_ = false; // Whether the window is currently being resized. bool is_resizing_ = false; // Whether the window is currently being moved. bool is_moving_ = false; std::optional<gfx::Rect> pending_bounds_change_; // The color to use as the theme and symbol colors respectively for Window // Controls Overlay if enabled on Windows. SkColor overlay_button_color_; SkColor overlay_symbol_color_; // The message ID of the "TaskbarCreated" message, sent to us when we need to // reset our thumbar buttons. UINT taskbar_created_message_ = 0; #endif // Handles unhandled keyboard messages coming back from the renderer process. views::UnhandledKeyboardEventHandler keyboard_event_handler_; // Whether the menubar is visible before the window enters fullscreen bool menu_bar_visible_before_fullscreen_ = false; // Whether the window should be enabled based on user calls to SetEnabled() bool is_enabled_ = true; // How many modal children this window has; // used to determine enabled state unsigned int num_modal_children_ = 0; bool use_content_size_ = false; bool movable_ = true; bool resizable_ = true; bool maximizable_ = true; bool minimizable_ = true; bool fullscreenable_ = true; std::string title_; gfx::Size widget_size_; double opacity_ = 1.0; bool widget_destroyed_ = false; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
closed
electron/electron
https://github.com/electron/electron
38,955
[Bug]: `BrowserWindow.isVisible()` doesn't take into account occlusion state
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? macOS ### Operating System Version Ventura 13.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I found out that BrowserWindow on Mac started to take into account page occlusion state since this PR: https://github.com/electron/electron/pull/17463/files BrowserWindow.isVisible() should return false if window is occluded by another window. ### Actual Behavior BrowserWindow.isVisible() always returns true unless minimized. ### Testcase Gist URL https://gist.github.com/Imperat/0ecffacee8d1386258d67a91e0017644 ### Additional Information Provided fiddle is best way to reproduce the issue: move browser window to the corner (or another screen) and open another app on top of browserWindow. Observe that in fiddle console "visible true" still logged.
https://github.com/electron/electron/issues/38955
https://github.com/electron/electron/pull/38982
08236f7a9e9d664513e2b76b54b9bea003101e5d
768ece6b54f78e65efbea2c3fd39eea30e48332b
2023-06-30T00:50:25Z
c++
2024-02-06T10:30:35Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as http from 'node:http'; import * as os from 'node:os'; import { AddressInfo } from 'node:net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor, hasCapturableScreen } from './lib/screen-helpers'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; import { setTimeout as syncSetTimeout } from 'node:timers'; const fixtures = path.resolve(__dirname, 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { it('sets the correct class name on the prototype', () => { expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow'); }); describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. const wr = new WeakRef(w); await setTimeout(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = once(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = once(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, '-before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await once(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await once(w.webContents, '-before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); for (const win of windows) win.show(); for (const win of windows) win.focus(); for (const win of windows) win.destroy(); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w: BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server: http.Server; let url: string; let postData = null as any; before(async () => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); it('is triggered when navigating from chrome: to http:', async () => { let hasEmittedWillNavigate = false; const willNavigatePromise = new Promise((resolve) => { w.webContents.once('will-navigate', e => { e.preventDefault(); hasEmittedWillNavigate = true; resolve(e.url); }); }); await w.loadURL('chrome://gpu'); // shouldn't emit for browser-initiated request via loadURL expect(hasEmittedWillNavigate).to.equal(false); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await willNavigatePromise; expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('chrome://gpu/'); }); }); describe('will-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); describe('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); url = (await listen(server)).url; }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(url + '/navigate'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(url + '/redirect'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(url + '/in-page'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = once(w, 'maximize'); const shown = once(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await setTimeout(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); ifit(process.platform === 'darwin')('should attach child window to parent', async () => { const wShow = once(w, 'show'); w.show(); await wShow; const c = new BrowserWindow({ show: false, parent: w }); const cShow = once(c, 'show'); c.showInactive(); await cShow; // verifying by checking that the child tracks the parent's visibility const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); closeWindow(c); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); ifit(process.platform === 'darwin')('it does not activate the app if focusing an inactive panel', async () => { // Show to focus app, then remove existing window w.show(); w.destroy(); // We first need to resign app focus for this test to work const isInactive = once(app, 'did-resign-active'); childProcess.execSync('osascript -e \'tell application "Finder" to activate\''); await isInactive; // Create new window w = new BrowserWindow({ type: 'panel', height: 200, width: 200, center: true, show: false }); const isShow = once(w, 'show'); const isFocus = once(w, 'focus'); w.showInactive(); w.focus(); await isShow; await isFocus; const getActiveAppOsa = 'tell application "System Events" to get the name of the first process whose frontmost is true'; const activeApp = childProcess.execSync(`osascript -e '${getActiveAppOsa}'`).toString().trim(); expect(activeApp).to.equal('Finder'); }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { afterEach(closeAllWindows); it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); it('should not crash when called on a modal child window', async () => { const shown = once(w, 'show'); w.show(); await shown; const child = new BrowserWindow({ modal: true, parent: w }); expect(() => { child.moveTop(); }).to.not.throw(); }); }); describe('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; for (const sourceId of fakeSourceIds) { 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]; for (const sourceId of fakeSourceIds) { 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']; for (const sourceId of fakeSourceIds) { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); } }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = once(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = once(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('does not crash if maximized, minimized, then restored to maximized state', (done) => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); let count = 0; w.on('maximize', () => { if (count === 0) syncSetTimeout(() => { w.minimize(); }); count++; }); w.on('minimize', () => { if (count === 1) syncSetTimeout(() => { w.restore(); }); count++; }); w.on('restore', () => { try { throw new Error('hey!'); } catch (e: any) { expect(e.message).to.equal('hey!'); done(); } }); w.maximize(); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.showAllTabs()', () => { it('does not throw', () => { expect(() => { w.showAllTabs(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); describe('BrowserWindow.tabbingIdentifier', () => { it('is undefined if no tabbingIdentifier was set', () => { const w = new BrowserWindow({ show: false }); expect(w.tabbingIdentifier).to.be.undefined('tabbingIdentifier'); }); it('returns the window tabbingIdentifier', () => { const w = new BrowserWindow({ show: false, tabbingIdentifier: 'group1' }); expect(w.tabbingIdentifier).to.equal('group1'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves when the window is occluded', async () => { const w1 = new BrowserWindow({ show: false }); w1.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w1, 'ready-to-show'); w1.show(); const w2 = new BrowserWindow({ show: false }); w2.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w2, 'ready-to-show'); w2.show(); const visibleImage = await w1.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); }); it('resolves when the window is not visible', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.minimize(); const hiddenImage = await w.capturePage(); expect(hiddenImage.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w: BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w: BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = once(w, 'always-on-top-changed') as Promise<[any, boolean]>; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect(c._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w: BrowserWindow; let server: http.Server; let url: string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); url = (await listen(server)).url; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = once(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('titlebar'); w.setVibrancy('selection'); w.setVibrancy(null); w.setVibrancy('menu'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created') as [any, WebContents]; expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); bv1.webContents.destroy(); bv2.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await once(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await once(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await once(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await once(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await once(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replaceAll('\\', '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('node:events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window') as [BrowserWindow, Electron.DidCreateWindowDetails]; const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replaceAll('\\', '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await once(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await once(app, 'browser-window-created') as [any, BrowserWindow]; // Ask the popup window for details. const detailsAnswer = once(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); const errorPattern = /Failed to read a named property 'document' from 'Window': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./; expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(errorPattern); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(errorPattern); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences!.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => once(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); expect(test.nodeEvents).to.equal(true); expect(test.nodeTimers).to.equal(true); expect(test.nodeUrl).to.equal(true); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Failed to read a named property \'toString\' from \'Location\': Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences!.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await once(w.webContents, '-before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await once(w.webContents, '-before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.close(); await once(w.webContents, '-before-unload-fired'); w.close(); await once(w.webContents, '-before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.reload(); // Chromium does not emit '-before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await once(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit '-before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); // TODO(codebytere): figure out how to make these pass in CI on Windows. ifdescribe(process.platform !== 'win32')('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); it('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); it('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = once(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = once(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('can handle child window close and reparent multiple times', async () => { const w = new BrowserWindow({ show: false }); let c: BrowserWindow | null; for (let i = 0; i < 5; i++) { c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; } await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('only shows the intended window when a child with siblings is shown', async () => { const w = new BrowserWindow({ show: false }); const childOne = new BrowserWindow({ show: false, parent: w }); const childTwo = new BrowserWindow({ show: false, parent: w }); const parentShown = once(w, 'show'); w.show(); await parentShown; expect(childOne.isVisible()).to.be.false('childOne is visible'); expect(childTwo.isVisible()).to.be.false('childTwo is visible'); const childOneShown = once(childOne, 'show'); childOne.show(); await childOneShown; expect(childOne.isVisible()).to.be.true('childOne is not visible'); expect(childTwo.isVisible()).to.be.false('childTwo is visible'); }); ifit(process.platform === 'darwin')('child matches parent visibility when parent visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); ifit(process.platform === 'darwin')('parent matches child visibility when child visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(c, 'minimize'); c.minimize(); await minimized; expect(c.isVisible()).to.be.false('child is visible'); const restored = once(c, 'restore'); c.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); it('closes a grandchild window when a middle child window is destroyed', async () => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); const closed = once(childWindow, 'closed'); window.close(); await closed; expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = once(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('can reparent when the first parent is destroyed', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); c.setParentWindow(w1); expect(w1.getChildWindows().length).to.equal(1); const closed = once(w1, 'closed'); w1.destroy(); await closed; c.setParentWindow(w2); await setTimeout(); const children = w2.getChildWindows(); expect(children[0]).to.equal(c); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); ifit(process.platform === 'win32')('do not change window with frame bounds when maximized', () => { const w = new BrowserWindow({ show: true, frame: true, thickFrame: true }); expect(w.isResizable()).to.be.true('resizable'); w.maximize(); expect(w.isMaximized()).to.be.true('maximized'); const bounds = w.getBounds(); w.setResizable(false); expectBoundsEqual(w.getBounds(), bounds); w.setResizable(true); expectBoundsEqual(w.getBounds(), bounds); }); ifit(process.platform === 'win32')('do not change window without frame bounds when maximized', () => { const w = new BrowserWindow({ show: true, frame: false, thickFrame: true }); expect(w.isResizable()).to.be.true('resizable'); w.maximize(); expect(w.isMaximized()).to.be.true('maximized'); const bounds = w.getBounds(); w.setResizable(false); expectBoundsEqual(w.getBounds(), bounds); w.setResizable(true); expectBoundsEqual(w.getBounds(), bounds); }); ifit(process.platform === 'win32')('do not change window transparent without frame bounds when maximized', () => { const w = new BrowserWindow({ show: true, frame: false, thickFrame: true, transparent: true }); expect(w.isResizable()).to.be.true('resizable'); w.maximize(); expect(w.isMaximized()).to.be.true('maximized'); const bounds = w.getBounds(); w.setResizable(false); expectBoundsEqual(w.getBounds(), bounds); w.setResizable(true); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('loading main frame state', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform !== 'darwin')('when fullscreen state is changed', () => { it('correctly remembers state prior to fullscreen change', async () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); it('correctly remembers state prior to fullscreen change with autoHide', async () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); it('does not open non-fullscreenable child windows in fullscreen if parent is fullscreen', async () => { const w = new BrowserWindow(); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const child = new BrowserWindow({ parent: w, resizable: false, fullscreenable: false }); const shown = once(child, 'show'); await shown; expect(child.resizable).to.be.false('resizable'); expect(child.fullScreen).to.be.false('fullscreen'); expect(child.fullScreenable).to.be.false('fullscreenable'); }); it('is set correctly with different resizable values', async () => { const w1 = new BrowserWindow({ resizable: false, fullscreenable: false }); const w2 = new BrowserWindow({ resizable: true, fullscreenable: false }); const w3 = new BrowserWindow({ fullscreenable: false }); expect(w1.isFullScreenable()).to.be.false('isFullScreenable'); expect(w2.isFullScreenable()).to.be.false('isFullScreenable'); expect(w3.isFullScreenable()).to.be.false('isFullScreenable'); }); it('does not disable maximize button if window is resizable', () => { const w = new BrowserWindow({ resizable: true, fullscreenable: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setResizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); const isValidWindow = require('@electron-ci/is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences()!.contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = once(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = once(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); describe('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(1000); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(1000); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); await setTimeout(1000); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true(); }); }); describe('draggable regions', () => { afterEach(closeAllWindows); ifit(hasCapturableScreen())('should allow the window to be dragged when enabled', async () => { // WOA fails to load libnut so we're using require to defer loading only // on supported platforms. // "@nut-tree\libnut-win32\build\Release\libnut.node is not a valid Win32 application." // @ts-ignore: nut-js is an optional dependency so it may not be installed const { mouse, straightTo, centerOf, Region, Button } = require('@nut-tree/nut-js') as typeof import('@nut-tree/nut-js'); const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ x: 0, y: 0, width: display.bounds.width / 2, height: display.bounds.height / 2, frame: false, titleBarStyle: 'hidden' }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); w.loadFile(overlayHTML); await once(w, 'ready-to-show'); const winBounds = w.getBounds(); const titleBarHeight = 30; const titleBarRegion = new Region(winBounds.x, winBounds.y, winBounds.width, titleBarHeight); const screenRegion = new Region(display.bounds.x, display.bounds.y, display.bounds.width, display.bounds.height); const startPos = w.getPosition(); await mouse.setPosition(await centerOf(titleBarRegion)); await mouse.pressButton(Button.LEFT); await mouse.drag(straightTo(centerOf(screenRegion))); // Wait for move to complete await Promise.race([ once(w, 'move'), setTimeout(100) // fallback for possible race condition ]); const endPos = w.getPosition(); expect(startPos).to.not.deep.equal(endPos); }); }); });
closed
electron/electron
https://github.com/electron/electron
41,189
[Bug]: nativeImage visually rotates some JPEGs (discards JPEG orientation EXIF metadata)
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 28.2.0 ### What operating system are you using? Ubuntu ### Operating System Version `Ubuntu 23.10; Linux 6.5.0-15-generic #15-Ubuntu x86_64 x86_64 x86_64 GNU/Linux` ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior EXIF orientation metadata should be preserved when loading then saving a JPEG with the `nativeImage` API. > [!NOTE] > > See also [the downstream issue](https://github.com/laurent22/joplin/issues/9597). > ### Actual Behavior Currently, when a user uploads a JPEG image with orientation metadata (as is the case from some phone cameras), the image appears rotated after processed by `nativeImage`. ![screenshot, processed image is flipped 180 degrees from the original](https://github.com/electron/electron/assets/46334387/39f8b9cd-b977-4396-871c-89717e762900) ### Testcase Gist URL https://gist.github.com/personalizedrefrigerator/37faf57d2a511ba3f3f7ce3e8f5b10ef ### Additional Information - This may be more of a feature request than a bug report. If supporting EXIF orientation metadata for JPEGs isn't planned, [updating the documentation](https://www.electronjs.org/docs/latest/api/native-image) to explain that EXIF orientation isn't supported may be helpful. - This [downstream bug report](https://github.com/laurent22/joplin/issues/9597) is in an application [that uses `createFromPath` -> `resize` -> `writeImageToFile`](https://github.com/laurent22/joplin/blob/582f0853bb4a7e389daec03bce1682d910da267b/packages/lib/shim-init-node.ts#L215). - The above Gist uses `createFromBuffer` -> `toDataURL` and `createFromBuffer` -> `resize` -> `toDataURL`.
https://github.com/electron/electron/issues/41189
https://github.com/electron/electron/pull/41261
42087e306c31044d22cd39b48ffb76487c315978
8eb580e79a55b0b96c6177584ee4ef8a8222b57d
2024-01-31T01:12:45Z
c++
2024-02-08T13:59:46Z
docs/api/native-image.md
# nativeImage > Create tray, dock, and application icons using PNG or JPG files. Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-process) In Electron, for the APIs that take images, you can pass either file paths or `NativeImage` instances. An empty image will be used when `null` is passed. For example, when creating a tray or setting a window's icon, you can pass an image file path as a `string`: ```js const { BrowserWindow, Tray } = require('electron') const appIcon = new Tray('/Users/somebody/images/icon.png') const win = new BrowserWindow({ icon: '/Users/somebody/images/window.png' }) console.log(appIcon, win) ``` Or read the image from the clipboard, which returns a `NativeImage`: ```js const { clipboard, Tray } = require('electron') const image = clipboard.readImage() const appIcon = new Tray(image) console.log(appIcon) ``` ## Supported Formats Currently `PNG` and `JPEG` image formats are supported. `PNG` is recommended because of its support for transparency and lossless compression. On Windows, you can also load `ICO` icons from file paths. For best visual quality, it is recommended to include at least the following sizes in the: * Small icon * 16x16 (100% DPI scale) * 20x20 (125% DPI scale) * 24x24 (150% DPI scale) * 32x32 (200% DPI scale) * Large icon * 32x32 (100% DPI scale) * 40x40 (125% DPI scale) * 48x48 (150% DPI scale) * 64x64 (200% DPI scale) * 256x256 Check the _Size requirements_ section in [this article][icons]. [icons]: https://learn.microsoft.com/en-us/windows/win32/uxguide/vis-icons ## High Resolution Image On platforms that have high-DPI support such as Apple Retina displays, you can append `@2x` after image's base filename to mark it as a high resolution image. For example, if `icon.png` is a normal image that has standard resolution, then `[email protected]` will be treated as a high resolution image that has double DPI density. If you want to support displays with different DPI densities at the same time, you can put images with different sizes in the same folder and use the filename without DPI suffixes. For example: ```plaintext images/ ├── icon.png ├── [email protected] └── [email protected] ``` ```js const { Tray } = require('electron') const appIcon = new Tray('/Users/somebody/images/icon.png') console.log(appIcon) ``` The following suffixes for DPI are also supported: * `@1x` * `@1.25x` * `@1.33x` * `@1.4x` * `@1.5x` * `@1.8x` * `@2x` * `@2.5x` * `@3x` * `@4x` * `@5x` ## Template Image Template images consist of black and an alpha channel. Template images are not intended to be used as standalone images and are usually mixed with other content to create the desired final appearance. The most common case is to use template images for a menu bar icon, so it can adapt to both light and dark menu bars. **Note:** Template image is only supported on macOS. To mark an image as a template image, its filename should end with the word `Template`. For example: * `xxxTemplate.png` * `[email protected]` ## Methods The `nativeImage` module has the following methods, all of which return an instance of the `NativeImage` class: ### `nativeImage.createEmpty()` Returns `NativeImage` Creates an empty `NativeImage` instance. ### `nativeImage.createThumbnailFromPath(path, size)` _macOS_ _Windows_ * `path` string - path to a file that we intend to construct a thumbnail out of. * `size` [Size](structures/size.md) - the desired width and height (positive numbers) of the thumbnail. Returns `Promise<NativeImage>` - fulfilled with the file's thumbnail preview image, which is a [NativeImage](native-image.md). Note: The Windows implementation will ignore `size.height` and scale the height according to `size.width`. ### `nativeImage.createFromPath(path)` * `path` string Returns `NativeImage` Creates a new `NativeImage` instance from a file located at `path`. This method returns an empty image if the `path` does not exist, cannot be read, or is not a valid image. ```js const nativeImage = require('electron').nativeImage const image = nativeImage.createFromPath('/Users/somebody/images/icon.png') console.log(image) ``` ### `nativeImage.createFromBitmap(buffer, options)` * `buffer` [Buffer][buffer] * `options` Object * `width` Integer * `height` Integer * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `NativeImage` Creates a new `NativeImage` instance from `buffer` that contains the raw bitmap pixel data returned by `toBitmap()`. The specific format is platform-dependent. ### `nativeImage.createFromBuffer(buffer[, options])` * `buffer` [Buffer][buffer] * `options` Object (optional) * `width` Integer (optional) - Required for bitmap buffers. * `height` Integer (optional) - Required for bitmap buffers. * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `NativeImage` Creates a new `NativeImage` instance from `buffer`. Tries to decode as PNG or JPEG first. ### `nativeImage.createFromDataURL(dataURL)` * `dataURL` string Returns `NativeImage` Creates a new `NativeImage` instance from `dataURL`. ### `nativeImage.createFromNamedImage(imageName[, hslShift])` _macOS_ * `imageName` string * `hslShift` number[] (optional) Returns `NativeImage` Creates a new `NativeImage` instance from the NSImage that maps to the given image name. See [`System Icons`](https://developer.apple.com/design/human-interface-guidelines/macos/icons-and-images/system-icons/) for a list of possible values. The `hslShift` is applied to the image with the following rules: * `hsl_shift[0]` (hue): The absolute hue value for the image - 0 and 1 map to 0 and 360 on the hue color wheel (red). * `hsl_shift[1]` (saturation): A saturation shift for the image, with the following key values: 0 = remove all color. 0.5 = leave unchanged. 1 = fully saturate the image. * `hsl_shift[2]` (lightness): A lightness shift for the image, with the following key values: 0 = remove all lightness (make all pixels black). 0.5 = leave unchanged. 1 = full lightness (make all pixels white). This means that `[-1, 0, 1]` will make the image completely white and `[-1, 1, 0]` will make the image completely black. In some cases, the `NSImageName` doesn't match its string representation; one example of this is `NSFolderImageName`, whose string representation would actually be `NSFolder`. Therefore, you'll need to determine the correct string representation for your image before passing it in. This can be done with the following: `echo -e '#import <Cocoa/Cocoa.h>\nint main() { NSLog(@"%@", SYSTEM_IMAGE_NAME); }' | clang -otest -x objective-c -framework Cocoa - && ./test` where `SYSTEM_IMAGE_NAME` should be replaced with any value from [this list](https://developer.apple.com/documentation/appkit/nsimagename?language=objc). ## Class: NativeImage > Natively wrap images such as tray, dock, and application icons. Process: [Main](../glossary.md#main-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._ ### Instance Methods The following methods are available on instances of the `NativeImage` class: #### `image.toPNG([options])` * `options` Object (optional) * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `Buffer` - A [Buffer][buffer] that contains the image's `PNG` encoded data. #### `image.toJPEG(quality)` * `quality` Integer - Between 0 - 100. Returns `Buffer` - A [Buffer][buffer] that contains the image's `JPEG` encoded data. #### `image.toBitmap([options])` * `options` Object (optional) * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `Buffer` - A [Buffer][buffer] that contains a copy of the image's raw bitmap pixel data. #### `image.toDataURL([options])` * `options` Object (optional) * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `string` - The data URL of the image. #### `image.getBitmap([options])` * `options` Object (optional) * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `Buffer` - A [Buffer][buffer] that contains the image's raw bitmap pixel data. The difference between `getBitmap()` and `toBitmap()` is that `getBitmap()` does not copy the bitmap data, so you have to use the returned Buffer immediately in current event loop tick; otherwise the data might be changed or destroyed. #### `image.getNativeHandle()` _macOS_ Returns `Buffer` - A [Buffer][buffer] that stores C pointer to underlying native handle of the image. On macOS, a pointer to `NSImage` instance would be returned. Notice that the returned pointer is a weak pointer to the underlying native image instead of a copy, so you _must_ ensure that the associated `nativeImage` instance is kept around. #### `image.isEmpty()` Returns `boolean` - Whether the image is empty. #### `image.getSize([scaleFactor])` * `scaleFactor` Number (optional) - Defaults to 1.0. Returns [`Size`](structures/size.md). If `scaleFactor` is passed, this will return the size corresponding to the image representation most closely matching the passed value. #### `image.setTemplateImage(option)` * `option` boolean Marks the image as a template image. #### `image.isTemplateImage()` Returns `boolean` - Whether the image is a template image. #### `image.crop(rect)` * `rect` [Rectangle](structures/rectangle.md) - The area of the image to crop. Returns `NativeImage` - The cropped image. #### `image.resize(options)` * `options` Object * `width` Integer (optional) - Defaults to the image's width. * `height` Integer (optional) - Defaults to the image's height. * `quality` string (optional) - The desired quality of the resize image. Possible values include `good`, `better`, or `best`. The default is `best`. These values express a desired quality/speed tradeoff. They are translated into an algorithm-specific method that depends on the capabilities (CPU, GPU) of the underlying platform. It is possible for all three methods to be mapped to the same algorithm on a given platform. Returns `NativeImage` - The resized image. If only the `height` or the `width` are specified then the current aspect ratio will be preserved in the resized image. #### `image.getAspectRatio([scaleFactor])` * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `Number` - The image's aspect ratio. If `scaleFactor` is passed, this will return the aspect ratio corresponding to the image representation most closely matching the passed value. #### `image.getScaleFactors()` Returns `Number[]` - An array of all scale factors corresponding to representations for a given nativeImage. #### `image.addRepresentation(options)` * `options` Object * `scaleFactor` Number (optional) - The scale factor to add the image representation for. * `width` Integer (optional) - Defaults to 0. Required if a bitmap buffer is specified as `buffer`. * `height` Integer (optional) - Defaults to 0. Required if a bitmap buffer is specified as `buffer`. * `buffer` Buffer (optional) - The buffer containing the raw image data. * `dataURL` string (optional) - The data URL containing either a base 64 encoded PNG or JPEG image. Add an image representation for a specific scale factor. This can be used to explicitly add different scale factor representations to an image. This can be called on empty images. [buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer ### Instance Properties #### `nativeImage.isMacTemplateImage` _macOS_ A `boolean` property that determines whether the image is considered a [template image](https://developer.apple.com/documentation/appkit/nsimage/1520017-template). Please note that this property only has an effect on macOS.
closed
electron/electron
https://github.com/electron/electron
41,143
[Bug]: context menu on Ubuntu/x11 in the top left of the screen on 29.0.0-beta.3
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 29.0.0-beta.3 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 23.04 ### What arch are you using? x64 ### Last Known Working Electron version 29.0.0-beta.2 ### Expected Behavior The context menu is located next to the pointer cursor, screenshot from 29.0.0-beta.2 ![Screenshot from 2024-01-26 16-12-40](https://github.com/electron/electron/assets/41970/c46af8ab-7242-4272-971f-dc47c1b3d89a) ### Actual Behavior The context menu appears in the top left of the screen when using 29.0.0-beta.3 ![Screenshot from 2024-01-26 16-13-01](https://github.com/electron/electron/assets/41970/abe2d5dc-7f91-40a3-b105-59553badd1ad) ### Testcase Gist URL https://gist.github.com/ad3013a440b58351f3c496923a0ea2d6 ### Additional Information This is using X11
https://github.com/electron/electron/issues/41143
https://github.com/electron/electron/pull/41275
cee51785e1ed057fa5c78b2fc7bb1e8a5b91053d
9655ae7d6ae9de4b467d197957bb3c7a152e3ddd
2024-01-26T15:14:26Z
c++
2024-02-09T15:44:46Z
patches/chromium/.patches
build_gn.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_avoid_private_macos_api_usage.patch.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch upload_list_add_loadsync_method.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch process_singleton.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch add_maximized_parameter_to_linuxui_getwindowframeprovider.patch add_electron_deps_to_license_credits_file.patch fix_crash_loading_non-standard_schemes_in_iframes.patch create_browser_v8_snapshot_file_name_fuse.patch feat_configure_launch_options_for_service_process.patch feat_ensure_mas_builds_of_the_same_application_can_use_safestorage.patch fix_on-screen-keyboard_hides_on_input_blur_in_webview.patch preconnect_manager.patch fix_remove_caption-removing_style_call.patch build_allow_electron_to_use_exec_script.patch chore_introduce_blocking_api_for_electron.patch chore_patch_out_partition_attribute_dcheck_for_webviews.patch chore_patch_out_profile_methods_in_profile_selections_cc.patch add_gin_converter_support_for_arraybufferview.patch chore_defer_usb_service_getdevices_request_until_usb_service_is.patch refactor_expose_hostimportmoduledynamically_and.patch feat_expose_documentloader_setdefersloading_on_webdocumentloader.patch fix_remove_profiles_from_spellcheck_service.patch chore_patch_out_profile_methods_in_chrome_browser_pdf.patch chore_patch_out_profile_methods_in_titlebar_config.patch fix_disabling_background_throttling_in_compositor.patch fix_select_the_first_menu_item_when_opened_via_keyboard.patch fix_return_v8_value_from_localframe_requestexecutescript.patch fix_harden_blink_scriptstate_maybefrom.patch chore_add_buildflag_guard_around_new_include.patch fix_use_delegated_generic_capturer_when_available.patch build_remove_ent_content_analysis_assert.patch expose_webblob_path_to_allow_embedders_to_get_file_paths.patch fix_move_autopipsettingshelper_behind_branding_buildflag.patch revert_remove_the_allowaggressivethrottlingwithwebsocket_feature.patch fix_activate_background_material_on_windows.patch feat_allow_passing_of_objecttemplate_to_objecttemplatebuilder.patch chore_remove_check_is_test_on_script_injection_tracker.patch fix_restore_original_resize_performance_on_macos.patch feat_allow_code_cache_in_custom_schemes.patch build_run_reclient_cfg_generator_after_chrome.patch fix_suppress_clang_-wimplicit-const-int-float-conversion_in.patch
closed
electron/electron
https://github.com/electron/electron
41,143
[Bug]: context menu on Ubuntu/x11 in the top left of the screen on 29.0.0-beta.3
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 29.0.0-beta.3 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 23.04 ### What arch are you using? x64 ### Last Known Working Electron version 29.0.0-beta.2 ### Expected Behavior The context menu is located next to the pointer cursor, screenshot from 29.0.0-beta.2 ![Screenshot from 2024-01-26 16-12-40](https://github.com/electron/electron/assets/41970/c46af8ab-7242-4272-971f-dc47c1b3d89a) ### Actual Behavior The context menu appears in the top left of the screen when using 29.0.0-beta.3 ![Screenshot from 2024-01-26 16-13-01](https://github.com/electron/electron/assets/41970/abe2d5dc-7f91-40a3-b105-59553badd1ad) ### Testcase Gist URL https://gist.github.com/ad3013a440b58351f3c496923a0ea2d6 ### Additional Information This is using X11
https://github.com/electron/electron/issues/41143
https://github.com/electron/electron/pull/41275
cee51785e1ed057fa5c78b2fc7bb1e8a5b91053d
9655ae7d6ae9de4b467d197957bb3c7a152e3ddd
2024-01-26T15:14:26Z
c++
2024-02-09T15:44:46Z
patches/chromium/fix_getcursorscreenpoint_wrongly_returns_0_0.patch
closed
electron/electron
https://github.com/electron/electron
40,798
[Bug]: Segfault when closing the app on macOS (v28)
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 28.0.0, 28.1.3 ### What operating system are you using? macOS ### Operating System Version Sonoma 14.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 27.2.2 ### Expected Behavior The app does not segfault when I close its last window. ### Actual Behavior The app sometimes segfaults when I close its last (and only) window. ### Testcase Gist URL _No response_ ### Additional Information This happens when the app is closed by selecting it with Cmd + Tab, holding Cmd (so that the app switcher is still visible) and hitting Cmd + Q. Both in the dev version and the packaged version. Here's [an Electron Fiddle repro](https://gist.github.com/ravicious/78f18b9114b479e334e623be669329c5) which is just the default code. Let me know if I should post more of the macOS crash report. <details> <summary>Dev version</summary> ``` ------------------------------------- Translated Report (Full Report Below) ------------------------------------- Process: Electron [83797] Path: /Users/USER/*/Electron.app/Contents/MacOS/Electron Identifier: com.github.Electron Version: 28.0.0 (28.0.0) Code Type: ARM-64 (Native) Parent Process: Exited process [83778] Responsible: iTerm2 [7689] User ID: 501 Date/Time: 2023-12-20 10:04:45.6935 +0100 OS Version: macOS 14.2 (23C64) Report Version: 12 Anonymous UUID: CEED24F1-A75C-89A9-E06E-1B0451613C4D Sleep/Wake UUID: B0F9B326-CDC2-4DAA-AEBE-E46673A3543D Time Awake Since Boot: 490000 seconds Time Since Wake: 102 seconds System Integrity Protection: enabled Crashed Thread: 0 CrBrowserMain Dispatch queue: com.apple.main-thread Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000010 Exception Codes: 0x0000000000000001, 0x0000000000000010 Termination Reason: Namespace SIGNAL, Code 11 Segmentation fault: 11 Terminating Process: exc handler [83797] VM Region Info: 0x10 is not in any region. Bytes before following region: 4374380528 REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL UNUSED SPACE AT START ---> __TEXT 104bbc000-104bc0000 [ 16K] r-x/r-x SM=COW ...acOS/Electron Kernel Triage: VM - (arg = 0x0) Fault was interrupted VM - (arg = 0x0) Fault was interrupted Thread 0 Crashed:: CrBrowserMain Dispatch queue: com.apple.main-thread 0 libobjc.A.dylib 0x180b85420 objc_msgSend + 32 1 Electron Framework 0x10e32b650 node::FreeArrayBufferAllocator(node::ArrayBufferAllocator*) + 275124 2 Electron Framework 0x10e32b09c node::FreeArrayBufferAllocator(node::ArrayBufferAllocator*) + 273664 3 Electron Framework 0x10e2b79fc v8::CodeEvent::GetScriptName() + 6308 4 AppKit 0x184b405e4 -[NSApplication _terminateFromSender:askIfShouldTerminate:saveWindows:] + 124 5 AppKit 0x184b404dc __52-[NSApplication(NSAppleEventHandling) _handleAEQuit]_block_invoke + 52 6 AppKit 0x184c45764 ___NSMainRunLoopPerformBlockInModes_block_invoke + 44 7 CoreFoundation 0x18102f5e4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28 8 CoreFoundation 0x18102f4f8 __CFRunLoopDoBlocks + 356 9 CoreFoundation 0x18102e330 __CFRunLoopRun + 812 10 CoreFoundation 0x18102d9ac CFRunLoopRunSpecific + 608 11 HIToolbox 0x18b5dc448 RunCurrentEventLoopInMode + 292 12 HIToolbox 0x18b5dc0d8 ReceiveNextEventCommon + 220 13 HIToolbox 0x18b5dbfdc _BlockUntilNextEventMatchingListInModeWithFilter + 76 14 AppKit 0x18480a8a4 _DPSNextEvent + 660 15 AppKit 0x184fe4980 -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716 16 AppKit 0x1847fdd50 -[NSApplication run] + 476 17 Electron Framework 0x1114dde20 node::GetArrayBufferAllocator(node::IsolateData*) + 17970108 18 Electron Framework 0x1114dbc8c node::GetArrayBufferAllocator(node::IsolateData*) + 17961512 19 Electron Framework 0x1114949dc node::GetArrayBufferAllocator(node::IsolateData*) + 17670008 20 Electron Framework 0x11145b5c4 node::GetArrayBufferAllocator(node::IsolateData*) + 17435488 21 Electron Framework 0x1105eeb6c node::GetArrayBufferAllocator(node::IsolateData*) + 2310408 22 Electron Framework 0x1105f0604 node::GetArrayBufferAllocator(node::IsolateData*) + 2317216 23 Electron Framework 0x1105ec4dc node::GetArrayBufferAllocator(node::IsolateData*) + 2300536 24 Electron Framework 0x10e488c78 v8::internal::compiler::BasicBlock::set_loop_header(v8::internal::compiler::BasicBlock*) + 13948 25 Electron Framework 0x10e489de0 v8::internal::compiler::BasicBlock::set_loop_header(v8::internal::compiler::BasicBlock*) + 18404 26 Electron Framework 0x10e489c10 v8::internal::compiler::BasicBlock::set_loop_header(v8::internal::compiler::BasicBlock*) + 17940 27 Electron Framework 0x10e4884bc v8::internal::compiler::BasicBlock::set_loop_header(v8::internal::compiler::BasicBlock*) + 11968 28 Electron Framework 0x10e48865c v8::internal::compiler::BasicBlock::set_loop_header(v8::internal::compiler::BasicBlock*) + 12384 29 Electron Framework 0x10e15a2f0 ElectronMain + 128 30 dyld 0x180bd10e0 start + 2360 ``` </details> <details> <summary>Packaged version</summary> ``` ------------------------------------- Translated Report (Full Report Below) ------------------------------------- Process: Teleport Connect [19388] Path: /Applications/Teleport Connect.app/Contents/MacOS/Teleport Connect Identifier: gravitational.teleport.connect Version: 15.0.0-dev.ravicious.5 (15.0.0-dev.ravicious.5.2252) Code Type: ARM-64 (Native) Parent Process: launchd [1] User ID: 501 Date/Time: 2023-12-19 13:18:01.1922 +0100 OS Version: macOS 14.2 (23C64) Report Version: 12 Anonymous UUID: CEED24F1-A75C-89A9-E06E-1B0451613C4D Sleep/Wake UUID: 7095D577-34E9-4741-9ABD-8A463E984E08 Time Awake Since Boot: 420000 seconds Time Since Wake: 11198 seconds System Integrity Protection: enabled Crashed Thread: 0 CrBrowserMain Dispatch queue: com.apple.main-thread Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000010 Exception Codes: 0x0000000000000001, 0x0000000000000010 Termination Reason: Namespace SIGNAL, Code 11 Segmentation fault: 11 Terminating Process: exc handler [19388] VM Region Info: 0x10 is not in any region. Bytes before following region: 23781099700208 REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL UNUSED SPACE AT START ---> Memory Tag 255 15a0f8000000-15a100000000 [128.0M] ---/rwx SM=NUL Thread 0 Crashed:: CrBrowserMain Dispatch queue: com.apple.main-thread 0 libobjc.A.dylib 0x180b85420 objc_msgSend + 32 1 Electron Framework 0x11868b650 node::FreeArrayBufferAllocator(node::ArrayBufferAllocator*) + 275124 2 Electron Framework 0x11868b09c node::FreeArrayBufferAllocator(node::ArrayBufferAllocator*) + 273664 3 Electron Framework 0x1186179fc v8::CodeEvent::GetScriptName() + 6308 4 AppKit 0x184b405e4 -[NSApplication _terminateFromSender:askIfShouldTerminate:saveWindows:] + 124 5 AppKit 0x184b404dc __52-[NSApplication(NSAppleEventHandling) _handleAEQuit]_block_invoke + 52 6 AppKit 0x184c45764 ___NSMainRunLoopPerformBlockInModes_block_invoke + 44 7 CoreFoundation 0x18102f5e4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28 8 CoreFoundation 0x18102f4f8 __CFRunLoopDoBlocks + 356 9 CoreFoundation 0x18102e330 __CFRunLoopRun + 812 10 CoreFoundation 0x18102d9ac CFRunLoopRunSpecific + 608 11 HIToolbox 0x18b5dc448 RunCurrentEventLoopInMode + 292 12 HIToolbox 0x18b5dc0d8 ReceiveNextEventCommon + 220 13 HIToolbox 0x18b5dbfdc _BlockUntilNextEventMatchingListInModeWithFilter + 76 14 AppKit 0x18480a8a4 _DPSNextEvent + 660 15 AppKit 0x184fe4980 -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716 16 AppKit 0x1847fdd50 -[NSApplication run] + 476 17 Electron Framework 0x11b83de20 node::GetArrayBufferAllocator(node::IsolateData*) + 17970108 18 Electron Framework 0x11b83bc8c node::GetArrayBufferAllocator(node::IsolateData*) + 17961512 19 Electron Framework 0x11b7f49dc node::GetArrayBufferAllocator(node::IsolateData*) + 17670008 20 Electron Framework 0x11b7bb5c4 node::GetArrayBufferAllocator(node::IsolateData*) + 17435488 21 Electron Framework 0x11a94eb6c node::GetArrayBufferAllocator(node::IsolateData*) + 2310408 22 Electron Framework 0x11a950604 node::GetArrayBufferAllocator(node::IsolateData*) + 2317216 23 Electron Framework 0x11a94c4dc node::GetArrayBufferAllocator(node::IsolateData*) + 2300536 24 Electron Framework 0x1187e8c78 v8::internal::compiler::BasicBlock::set_loop_header(v8::internal::compiler::BasicBlock*) + 13948 25 Electron Framework 0x1187e9de0 v8::internal::compiler::BasicBlock::set_loop_header(v8::internal::compiler::BasicBlock*) + 18404 26 Electron Framework 0x1187e9c10 v8::internal::compiler::BasicBlock::set_loop_header(v8::internal::compiler::BasicBlock*) + 17940 27 Electron Framework 0x1187e84bc v8::internal::compiler::BasicBlock::set_loop_header(v8::internal::compiler::BasicBlock*) + 11968 28 Electron Framework 0x1187e865c v8::internal::compiler::BasicBlock::set_loop_header(v8::internal::compiler::BasicBlock*) + 12384 29 Electron Framework 0x1184ba2f0 ElectronMain + 128 30 dyld 0x180bd10e0 start + 2360 ``` </details> https://github.com/electron/electron/assets/27113/8c929ce3-c7a4-4fb5-8464-cc156ff50c86
https://github.com/electron/electron/issues/40798
https://github.com/electron/electron/pull/41264
9655ae7d6ae9de4b467d197957bb3c7a152e3ddd
c894645ac68af14183d617570a2d51336a2578ad
2023-12-20T09:16:23Z
c++
2024-02-09T21:44:24Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/apple/scoped_cftyperef.h" #include "base/mac/mac_util.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } bool IsPanel(NSWindow* window) { return [window isKindOfClass:[NSPanel class]]; } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); widget()->SetNativeWindowProperty(kElectronNativeWindowKey, this); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this]; [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_]; [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { // If we're a panel window, we do not want to activate the app, // which enables Electron-apps to build Spotlight-like experiences. // // On macOS < Sonoma, "activateIgnoringOtherApps:NO" would not // activate apps if focusing a window that is inActive. That // changed with macOS Sonoma, which also deprecated // "activateIgnoringOtherApps". For the panel-specific usecase, // we can simply replace "activateIgnoringOtherApps:NO" with // "activate". For details on why we cannot replace all calls 1:1, // please see // https://github.com/electron/electron/pull/40307#issuecomment-1801976591. // // There's a slim chance we should have never called // activateIgnoringOtherApps, but we tried that many years ago // and saw weird focus bugs on other macOS versions. So, to make // this safe, we're gating by versions. if (@available(macOS 14.0, *)) { if (!IsPanel(window_)) { [[NSApplication sharedApplication] activate]; } else { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; } } else { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; } [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() const { 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; } set_wants_to_be_visible(true); // 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() { set_wants_to_be_visible(true); // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // If the window wants to be visible and has a parent, then the parent may // order it back in (in the period between orderOut: and close). set_wants_to_be_visible(false); DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsOccluded() const { return !([window_ occlusionState] & NSWindowOcclusionStateVisible); } bool NativeWindowMac::IsVisible() const { return [window_ isVisible] && !IsMinimized(); } bool NativeWindowMac::IsEnabled() const { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() const { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = aspect_ratio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() const { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow() { if (parent() && !is_modal()) { parent()->RemoveChildWindow(this); NativeWindow::SetParentWindow(nullptr); } } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { if (!static_cast<NativeWindowMac*>(child)->wants_to_be_visible()) continue; auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } void NativeWindowMac::SetFullScreen(bool fullscreen) { // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; if (![window_ toggleFullScreenMode:nil]) fullscreen_transition_state_ = FullScreenTransitionState::kNone; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() const { 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() const { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() const { 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::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { // Apply the size constraints to NSWindow. if (window_constraints.HasMinimumSize()) [window_ setMinSize:window_constraints.GetMinimumSize().ToCGSize()]; if (window_constraints.HasMaximumSize()) [window_ setMaxSize:window_constraints.GetMaximumSize().ToCGSize()]; NativeWindow::SetSizeConstraints(window_constraints); } 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()); } }; // Apply the size constraints to NSWindow. NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:0]; } else { ReorderChildWindowAbove(window_, nullptr); } } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); bool was_fullscreenable = IsFullScreenable(); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreen collection behavior as well as the maximize traffic // light in SetCanResize if resizability is false on macOS unless // the window is both resizable and maximizable. We want consistent // cross-platform behavior, so if resizability is disabled we disable // the maximize button and ensure fullscreenability matches user setting. SetCanResize(resizable); SetFullScreenable(was_fullscreenable); UpdateZoomButton(); } bool NativeWindowMac::IsResizable() const { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() const { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() const { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; UpdateZoomButton(); } bool NativeWindowMac::IsMaximizable() const { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::UpdateZoomButton() { [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:HasStyleMask(NSWindowStyleMaskResizable) && (CanMaximize() || IsFullScreenable())]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); UpdateZoomButton(); } bool NativeWindowMac::IsFullScreenable() const { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() const { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() const { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() const { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() const { 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() const { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() const { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() const { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::apple::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor.get()]; } SkColor NativeWindowMac::GetBackgroundColor() const { 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() const { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() const { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() const { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() const { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() const { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() const { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[NSImageView alloc] init]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[ElectronProgressBar alloc] initWithFrame:frame]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() const { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); const int macos_version = base::mac::MacOSMajorVersion(); const bool modal = is_modal(); // If the window is modal, its corners are rounded on macOS >= 11 or higher // unless the user has explicitly passed noRoundedCorners. bool should_round_modal = !no_rounded_corner && macos_version >= 11 && modal; // If the window is nonmodal, its corners are rounded if it is frameless and // the user hasn't passed noRoundedCorners. bool should_round_nonmodal = !no_rounded_corner && !modal && !has_frame(); if (should_round_nonmodal || should_round_modal) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (macos_version >= 11) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NativeWindow::SetVibrancy(type); NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( std::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } std::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ window:this settings:std::move(items)]; [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::ShowAllTabs() { [window_ toggleTabOverview:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } std::optional<std::string> NativeWindowMac::GetTabbingIdentifier() const { if ([window_ tabbingMode] == NSWindowTabbingModeDisallowed) return std::nullopt; return base::SysNSStringToUTF8([window_ tabbingIdentifier]); } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_ = [[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]; [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:NO]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:YES]; } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { CALayer* background_layer = [[CALayer alloc] init]; [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(); // Set new parent window. if (new_parent) { new_parent->add_child_window(this); if (attach) new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } std::optional<gfx::Rect> NativeWindowMac::GetWindowControlsOverlayRect() { if (!titlebar_overlay_) return std::nullopt; // On macOS, when in fullscreen mode, window controls (the menu bar, title // bar, and toolbar) are attached to a separate NSView that slides down from // the top of the screen, independent of, and overlapping the WebContents. // Disable WCO when in fullscreen, because this space is inaccessible to // WebContents. https://crbug.com/915110. if (IsFullscreen()) return gfx::Rect(); if (buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); overlay.set_height([buttons_proxy_ useCustomHeight] ? titlebar_overlay_height() : NSHeight(buttons)); if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return std::nullopt; } // 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
41,002
[Bug]: `-webkit-app-region: drag;` in underlying browserView blocks mouse interaction
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 28.1.3 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Actual Behavior I have an app which has two BrowserViews: title bar and content. Content view can go full-screen via HTML5 Fullscreen API. In that case I listen to `enter-html-full-screen` event on webContents of content view and change it's size to be the size of all app window. Content view is placed on top of title bar view. Part of title bar view (which is behind content and which is marked as drag area via css rule `-webkit-app-region: drag`) blocks event handling in content view. Please, run my fiddle example. It will have: 1. orange area - my content view 2. green area - is my title bar view 3. blue area - `div` element which has css rule `-webkit-app-region: drag`. After that, please move mouse in orange area and see that title of button is updated. Click the button to go to full-screen and move mouse to the top of the screen. Button label will have title `x: SOME_VALUE, y: 0`. Start slowly moving cursor down and see that the value stops receiving updates when y is 7. It will start receive updates only when y value is 59. Those values perfectly match height of blue area which is 51. ### Expected Behavior `-webkit-app-region: drag` does not affect other views when it is placed behind them. ### Testcase Gist URL https://gist.github.com/Imperat/45c09b8c558ee9b99e1c3270db7cfee6 ### Additional Information _No response_
https://github.com/electron/electron/issues/41002
https://github.com/electron/electron/pull/41307
32920af4b78213b4479f20796e989d4cc56ce9db
79147e4dd825aa26ea0242470c2bad47c3998fe3
2024-01-16T08:13:34Z
c++
2024-02-14T10:12:41Z
shell/browser/native_window.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window.h" #include <algorithm> #include <string> #include <vector> #include "base/containers/contains.h" #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/web_contents_user_data.h" #include "include/core/SkColor.h" #include "shell/browser/background_throttling_source.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_features.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/window_list.h" #include "shell/common/color_util.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/persistent_dictionary.h" #include "shell/common/options_switches.h" #include "third_party/skia/include/core/SkRegion.h" #include "ui/base/hit_test.h" #include "ui/compositor/compositor.h" #include "ui/views/widget/widget.h" #if !BUILDFLAG(IS_MAC) #include "shell/browser/ui/views/frameless_view.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/win/shell.h" #include "ui/display/win/screen_win.h" #endif #if defined(USE_OZONE) #include "ui/base/ui_base_features.h" #include "ui/ozone/public/ozone_platform.h" #endif namespace gin { template <> struct Converter<electron::NativeWindow::TitleBarStyle> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindow::TitleBarStyle* out) { using TitleBarStyle = electron::NativeWindow::TitleBarStyle; std::string title_bar_style; if (!ConvertFromV8(isolate, val, &title_bar_style)) return false; if (title_bar_style == "hidden") { *out = TitleBarStyle::kHidden; #if BUILDFLAG(IS_MAC) } else if (title_bar_style == "hiddenInset") { *out = TitleBarStyle::kHiddenInset; } else if (title_bar_style == "customButtonsOnHover") { *out = TitleBarStyle::kCustomButtonsOnHover; #endif } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { #if BUILDFLAG(IS_WIN) gfx::Size GetExpandedWindowSize(const NativeWindow* window, gfx::Size size) { if (!window->transparent()) return size; gfx::Size min_size = display::win::ScreenWin::ScreenToDIPSize( window->GetAcceleratedWidget(), gfx::Size(64, 64)); // Some AMD drivers can't display windows that are less than 64x64 pixels, // so expand them to be at least that size. http://crbug.com/286609 gfx::Size expanded(std::max(size.width(), min_size.width()), std::max(size.height(), min_size.height())); return expanded; } #endif } // namespace const char kElectronNativeWindowKey[] = "__ELECTRON_NATIVE_WINDOW__"; NativeWindow::NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent) : widget_(std::make_unique<views::Widget>()), parent_(parent) { ++next_id_; options.Get(options::kFrame, &has_frame_); options.Get(options::kTransparent, &transparent_); options.Get(options::kEnableLargerThanScreen, &enable_larger_than_screen_); options.Get(options::kTitleBarStyle, &title_bar_style_); #if BUILDFLAG(IS_WIN) options.Get(options::kBackgroundMaterial, &background_material_); #elif BUILDFLAG(IS_MAC) options.Get(options::kVibrancyType, &vibrancy_); #endif v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay)) { if (titlebar_overlay->IsBoolean()) { options.Get(options::ktitleBarOverlay, &titlebar_overlay_); } else if (titlebar_overlay->IsObject()) { titlebar_overlay_ = true; auto titlebar_overlay_dict = gin_helper::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_dict); int height; if (titlebar_overlay_dict.Get(options::kOverlayHeight, &height)) titlebar_overlay_height_ = height; #if !(BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)) DCHECK(false); #endif } } if (parent) options.Get("modal", &is_modal_); #if defined(USE_OZONE) // Ozone X11 likes to prefer custom frames, but we don't need them unless // on Wayland. if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations) && !ui::OzonePlatform::GetInstance() ->GetPlatformRuntimeProperties() .supports_server_side_window_decorations) { has_client_frame_ = true; } #endif WindowList::AddWindow(this); } NativeWindow::~NativeWindow() { // It's possible that the windows gets destroyed before it's closed, in that // case we need to ensure the Widget delegate gets destroyed and // OnWindowClosed message is still notified. if (widget_->widget_delegate()) widget_->OnNativeWidgetDestroyed(); NotifyWindowClosed(); } void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) { // Setup window from options. int x = -1, y = -1; bool center; if (options.Get(options::kX, &x) && options.Get(options::kY, &y)) { SetPosition(gfx::Point(x, y)); #if BUILDFLAG(IS_WIN) // FIXME(felixrieseberg): Dirty, dirty workaround for // https://github.com/electron/electron/issues/10862 // Somehow, we need to call `SetBounds` twice to get // usable results. The root cause is still unknown. SetPosition(gfx::Point(x, y)); #endif } else if (options.Get(options::kCenter, &center) && center) { Center(); } bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); // On Linux and Window we may already have maximum size defined. extensions::SizeConstraints size_constraints( use_content_size ? GetContentSizeConstraints() : GetSizeConstraints()); int min_width = size_constraints.GetMinimumSize().width(); int min_height = size_constraints.GetMinimumSize().height(); options.Get(options::kMinWidth, &min_width); options.Get(options::kMinHeight, &min_height); size_constraints.set_minimum_size(gfx::Size(min_width, min_height)); gfx::Size max_size = size_constraints.GetMaximumSize(); int max_width = max_size.width() > 0 ? max_size.width() : INT_MAX; int max_height = max_size.height() > 0 ? max_size.height() : INT_MAX; bool have_max_width = options.Get(options::kMaxWidth, &max_width); if (have_max_width && max_width <= 0) max_width = INT_MAX; bool have_max_height = options.Get(options::kMaxHeight, &max_height); if (have_max_height && max_height <= 0) max_height = INT_MAX; // By default the window has a default maximum size that prevents it // from being resized larger than the screen, so we should only set this // if the user has passed in values. if (have_max_height || have_max_width || !max_size.IsEmpty()) size_constraints.set_maximum_size(gfx::Size(max_width, max_height)); if (use_content_size) { SetContentSizeConstraints(size_constraints); } else { SetSizeConstraints(size_constraints); } #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) bool closable; if (options.Get(options::kClosable, &closable)) { SetClosable(closable); } #endif bool movable; if (options.Get(options::kMovable, &movable)) { SetMovable(movable); } bool has_shadow; if (options.Get(options::kHasShadow, &has_shadow)) { SetHasShadow(has_shadow); } double opacity; if (options.Get(options::kOpacity, &opacity)) { SetOpacity(opacity); } bool top; if (options.Get(options::kAlwaysOnTop, &top) && top) { SetAlwaysOnTop(ui::ZOrderLevel::kFloatingWindow); } bool fullscreenable = true; bool fullscreen = false; if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) { // Disable fullscreen button if 'fullscreen' is specified to false. #if BUILDFLAG(IS_MAC) fullscreenable = false; #endif } options.Get(options::kFullScreenable, &fullscreenable); SetFullScreenable(fullscreenable); if (fullscreen) SetFullScreen(true); bool resizable; if (options.Get(options::kResizable, &resizable)) { SetResizable(resizable); } bool skip; if (options.Get(options::kSkipTaskbar, &skip)) { SetSkipTaskbar(skip); } bool kiosk; if (options.Get(options::kKiosk, &kiosk) && kiosk) { SetKiosk(kiosk); } #if BUILDFLAG(IS_MAC) std::string type; if (options.Get(options::kVibrancyType, &type)) { SetVibrancy(type); } #elif BUILDFLAG(IS_WIN) std::string material; if (options.Get(options::kBackgroundMaterial, &material)) { SetBackgroundMaterial(material); } #endif SkColor background_color = SK_ColorWHITE; if (std::string color; options.Get(options::kBackgroundColor, &color)) { background_color = ParseCSSColor(color); } else if (IsTranslucent()) { background_color = SK_ColorTRANSPARENT; } SetBackgroundColor(background_color); std::string title(Browser::Get()->GetName()); options.Get(options::kTitle, &title); SetTitle(title); // Then show it. bool show = true; options.Get(options::kShow, &show); if (show) Show(); } bool NativeWindow::IsClosed() const { return is_closed_; } void NativeWindow::SetSize(const gfx::Size& size, bool animate) { SetBounds(gfx::Rect(GetPosition(), size), animate); } gfx::Size NativeWindow::GetSize() const { return GetBounds().size(); } void NativeWindow::SetPosition(const gfx::Point& position, bool animate) { SetBounds(gfx::Rect(position, GetSize()), animate); } gfx::Point NativeWindow::GetPosition() const { return GetBounds().origin(); } void NativeWindow::SetContentSize(const gfx::Size& size, bool animate) { SetSize(ContentBoundsToWindowBounds(gfx::Rect(size)).size(), animate); } gfx::Size NativeWindow::GetContentSize() const { return GetContentBounds().size(); } void NativeWindow::SetContentBounds(const gfx::Rect& bounds, bool animate) { SetBounds(ContentBoundsToWindowBounds(bounds), animate); } gfx::Rect NativeWindow::GetContentBounds() const { return WindowBoundsToContentBounds(GetBounds()); } bool NativeWindow::IsNormal() const { return !IsMinimized() && !IsMaximized() && !IsFullscreen(); } void NativeWindow::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { size_constraints_ = window_constraints; content_size_constraints_.reset(); } extensions::SizeConstraints NativeWindow::GetSizeConstraints() const { if (size_constraints_) return *size_constraints_; if (!content_size_constraints_) return extensions::SizeConstraints(); // Convert content size constraints to window size constraints. extensions::SizeConstraints constraints; if (content_size_constraints_->HasMaximumSize()) { gfx::Rect max_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_size_constraints_->GetMaximumSize())); constraints.set_maximum_size(max_bounds.size()); } if (content_size_constraints_->HasMinimumSize()) { gfx::Rect min_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_size_constraints_->GetMinimumSize())); constraints.set_minimum_size(min_bounds.size()); } return constraints; } void NativeWindow::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { content_size_constraints_ = size_constraints; size_constraints_.reset(); } // Windows/Linux: // The return value of GetContentSizeConstraints will be passed to Chromium // to set min/max sizes of window. Note that we are returning content size // instead of window size because that is what Chromium expects, see the // comment of |WidgetSizeIsClientSize| in Chromium's codebase to learn more. // // macOS: // The min/max sizes are set directly by calling NSWindow's methods. extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const { if (content_size_constraints_) return *content_size_constraints_; if (!size_constraints_) return extensions::SizeConstraints(); // Convert window size constraints to content size constraints. // Note that we are not caching the results, because Chromium reccalculates // window frame size everytime when min/max sizes are passed, and we must // do the same otherwise the resulting size with frame included will be wrong. extensions::SizeConstraints constraints; if (size_constraints_->HasMaximumSize()) { gfx::Rect max_bounds = WindowBoundsToContentBounds( gfx::Rect(size_constraints_->GetMaximumSize())); constraints.set_maximum_size(max_bounds.size()); } if (size_constraints_->HasMinimumSize()) { gfx::Rect min_bounds = WindowBoundsToContentBounds( gfx::Rect(size_constraints_->GetMinimumSize())); constraints.set_minimum_size(min_bounds.size()); } return constraints; } void NativeWindow::SetMinimumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints = GetSizeConstraints(); size_constraints.set_minimum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMinimumSize() const { return GetSizeConstraints().GetMinimumSize(); } void NativeWindow::SetMaximumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints = GetSizeConstraints(); size_constraints.set_maximum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMaximumSize() const { return GetSizeConstraints().GetMaximumSize(); } gfx::Size NativeWindow::GetContentMinimumSize() const { return GetContentSizeConstraints().GetMinimumSize(); } gfx::Size NativeWindow::GetContentMaximumSize() const { gfx::Size maximum_size = GetContentSizeConstraints().GetMaximumSize(); #if BUILDFLAG(IS_WIN) return GetContentSizeConstraints().HasMaximumSize() ? GetExpandedWindowSize(this, maximum_size) : maximum_size; #else return maximum_size; #endif } void NativeWindow::SetSheetOffset(const double offsetX, const double offsetY) { sheet_offset_x_ = offsetX; sheet_offset_y_ = offsetY; } double NativeWindow::GetSheetOffsetX() const { return sheet_offset_x_; } double NativeWindow::GetSheetOffsetY() const { return sheet_offset_y_; } bool NativeWindow::IsTabletMode() const { return false; } void NativeWindow::SetRepresentedFilename(const std::string& filename) {} std::string NativeWindow::GetRepresentedFilename() const { return ""; } void NativeWindow::SetDocumentEdited(bool edited) {} bool NativeWindow::IsDocumentEdited() const { return false; } void NativeWindow::SetFocusable(bool focusable) {} bool NativeWindow::IsFocusable() const { return false; } void NativeWindow::SetMenu(ElectronMenuModel* menu) {} void NativeWindow::SetParentWindow(NativeWindow* parent) { parent_ = parent; } void NativeWindow::InvalidateShadow() {} void NativeWindow::SetAutoHideCursor(bool auto_hide) {} void NativeWindow::SelectPreviousTab() {} void NativeWindow::SelectNextTab() {} void NativeWindow::ShowAllTabs() {} void NativeWindow::MergeAllWindows() {} void NativeWindow::MoveTabToNewWindow() {} void NativeWindow::ToggleTabBar() {} bool NativeWindow::AddTabbedWindow(NativeWindow* window) { return true; // for non-Mac platforms } std::optional<std::string> NativeWindow::GetTabbingIdentifier() const { return ""; // for non-Mac platforms } void NativeWindow::SetVibrancy(const std::string& type) { vibrancy_ = type; } void NativeWindow::SetBackgroundMaterial(const std::string& type) { background_material_ = type; } void NativeWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) {} void NativeWindow::RefreshTouchBarItem(const std::string& item_id) {} void NativeWindow::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) {} void NativeWindow::SetAutoHideMenuBar(bool auto_hide) {} bool NativeWindow::IsMenuBarAutoHide() const { return false; } void NativeWindow::SetMenuBarVisibility(bool visible) {} bool NativeWindow::IsMenuBarVisible() const { return true; } void NativeWindow::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { aspect_ratio_ = aspect_ratio; aspect_ratio_extraSize_ = extra_size; } void NativeWindow::PreviewFile(const std::string& path, const std::string& display_name) {} void NativeWindow::CloseFilePreview() {} std::optional<gfx::Rect> NativeWindow::GetWindowControlsOverlayRect() { return overlay_rect_; } void NativeWindow::SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect) { overlay_rect_ = overlay_rect; } void NativeWindow::NotifyWindowRequestPreferredWidth(int* width) { for (NativeWindowObserver& observer : observers_) observer.RequestPreferredWidth(width); } void NativeWindow::NotifyWindowCloseButtonClicked() { // First ask the observers whether we want to close. bool prevent_default = false; for (NativeWindowObserver& observer : observers_) observer.WillCloseWindow(&prevent_default); if (prevent_default) { WindowList::WindowCloseCancelled(this); return; } // Then ask the observers how should we close the window. for (NativeWindowObserver& observer : observers_) observer.OnCloseButtonClicked(&prevent_default); if (prevent_default) return; CloseImmediately(); } void NativeWindow::NotifyWindowClosed() { if (is_closed_) return; is_closed_ = true; for (NativeWindowObserver& observer : observers_) observer.OnWindowClosed(); WindowList::RemoveWindow(this); } void NativeWindow::NotifyWindowEndSession() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEndSession(); } void NativeWindow::NotifyWindowBlur() { for (NativeWindowObserver& observer : observers_) observer.OnWindowBlur(); } void NativeWindow::NotifyWindowFocus() { for (NativeWindowObserver& observer : observers_) observer.OnWindowFocus(); } void NativeWindow::NotifyWindowIsKeyChanged(bool is_key) { for (NativeWindowObserver& observer : observers_) observer.OnWindowIsKeyChanged(is_key); } void NativeWindow::NotifyWindowShow() { for (NativeWindowObserver& observer : observers_) observer.OnWindowShow(); } void NativeWindow::NotifyWindowHide() { for (NativeWindowObserver& observer : observers_) observer.OnWindowHide(); } void NativeWindow::NotifyWindowMaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMaximize(); } void NativeWindow::NotifyWindowUnmaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowUnmaximize(); } void NativeWindow::NotifyWindowMinimize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMinimize(); } void NativeWindow::NotifyWindowRestore() { for (NativeWindowObserver& observer : observers_) observer.OnWindowRestore(); } void NativeWindow::NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillResize(new_bounds, edge, prevent_default); } void NativeWindow::NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillMove(new_bounds, prevent_default); } void NativeWindow::NotifyWindowResize() { NotifyLayoutWindowControlsOverlay(); for (NativeWindowObserver& observer : observers_) observer.OnWindowResize(); } void NativeWindow::NotifyWindowResized() { for (NativeWindowObserver& observer : observers_) observer.OnWindowResized(); } void NativeWindow::NotifyWindowMove() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMove(); } void NativeWindow::NotifyWindowMoved() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMoved(); } void NativeWindow::NotifyWindowEnterFullScreen() { NotifyLayoutWindowControlsOverlay(); for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterFullScreen(); } void NativeWindow::NotifyWindowSwipe(const std::string& direction) { for (NativeWindowObserver& observer : observers_) observer.OnWindowSwipe(direction); } void NativeWindow::NotifyWindowRotateGesture(float rotation) { for (NativeWindowObserver& observer : observers_) observer.OnWindowRotateGesture(rotation); } void NativeWindow::NotifyWindowSheetBegin() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetBegin(); } void NativeWindow::NotifyWindowSheetEnd() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetEnd(); } void NativeWindow::NotifyWindowLeaveFullScreen() { NotifyLayoutWindowControlsOverlay(); for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveFullScreen(); } void NativeWindow::NotifyWindowEnterHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterHtmlFullScreen(); } void NativeWindow::NotifyWindowLeaveHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveHtmlFullScreen(); } void NativeWindow::NotifyWindowAlwaysOnTopChanged() { for (NativeWindowObserver& observer : observers_) observer.OnWindowAlwaysOnTopChanged(); } void NativeWindow::NotifyWindowExecuteAppCommand(const std::string& command) { for (NativeWindowObserver& observer : observers_) observer.OnExecuteAppCommand(command); } void NativeWindow::NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details) { for (NativeWindowObserver& observer : observers_) observer.OnTouchBarItemResult(item_id, details); } void NativeWindow::NotifyNewWindowForTab() { for (NativeWindowObserver& observer : observers_) observer.OnNewWindowForTab(); } void NativeWindow::NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnSystemContextMenu(x, y, prevent_default); } void NativeWindow::NotifyLayoutWindowControlsOverlay() { auto bounding_rect = GetWindowControlsOverlayRect(); if (bounding_rect.has_value()) { for (NativeWindowObserver& observer : observers_) observer.UpdateWindowControlsOverlay(bounding_rect.value()); } } #if BUILDFLAG(IS_WIN) void NativeWindow::NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { for (NativeWindowObserver& observer : observers_) observer.OnWindowMessage(message, w_param, l_param); } #endif int NativeWindow::NonClientHitTest(const gfx::Point& point) { #if !BUILDFLAG(IS_MAC) // We need to ensure we account for resizing borders on Windows and Linux. if ((!has_frame() || has_client_frame()) && IsResizable()) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); int border_hit = frame->ResizingBorderHitTest(point); if (border_hit != HTNOWHERE) return border_hit; } #endif for (auto* provider : draggable_region_providers_) { int hit = provider->NonClientHitTest(point); if (hit != HTNOWHERE) return hit; } return HTNOWHERE; } void NativeWindow::AddDraggableRegionProvider( DraggableRegionProvider* provider) { if (!base::Contains(draggable_region_providers_, provider)) { draggable_region_providers_.push_back(provider); } } void NativeWindow::RemoveDraggableRegionProvider( DraggableRegionProvider* provider) { draggable_region_providers_.remove_if( [&provider](DraggableRegionProvider* p) { return p == provider; }); } void NativeWindow::AddBackgroundThrottlingSource( BackgroundThrottlingSource* source) { auto result = background_throttling_sources_.insert(source); DCHECK(result.second) << "Added already stored BackgroundThrottlingSource."; UpdateBackgroundThrottlingState(); } void NativeWindow::RemoveBackgroundThrottlingSource( BackgroundThrottlingSource* source) { auto result = background_throttling_sources_.erase(source); DCHECK(result == 1) << "Tried to remove non existing BackgroundThrottlingSource."; UpdateBackgroundThrottlingState(); } void NativeWindow::UpdateBackgroundThrottlingState() { if (!GetWidget() || !GetWidget()->GetCompositor()) { return; } bool enable_background_throttling = true; for (const auto* background_throttling_source : background_throttling_sources_) { if (!background_throttling_source->GetBackgroundThrottling()) { enable_background_throttling = false; break; } } GetWidget()->GetCompositor()->SetBackgroundThrottling( enable_background_throttling); } views::Widget* NativeWindow::GetWidget() { return widget(); } const views::Widget* NativeWindow::GetWidget() const { return widget(); } std::u16string NativeWindow::GetAccessibleWindowTitle() const { if (accessible_title_.empty()) { return views::WidgetDelegate::GetAccessibleWindowTitle(); } return accessible_title_; } void NativeWindow::SetAccessibleTitle(const std::string& title) { accessible_title_ = base::UTF8ToUTF16(title); } std::string NativeWindow::GetAccessibleTitle() { return base::UTF16ToUTF8(accessible_title_); } void NativeWindow::HandlePendingFullscreenTransitions() { if (pending_transitions_.empty()) { set_fullscreen_transition_type(FullScreenTransitionType::kNone); return; } bool next_transition = pending_transitions_.front(); pending_transitions_.pop(); SetFullScreen(next_transition); } // static int32_t NativeWindow::next_id_ = 0; bool NativeWindow::IsTranslucent() const { // Transparent windows are translucent if (transparent()) { return true; } #if BUILDFLAG(IS_MAC) // Windows with vibrancy set are translucent if (!vibrancy().empty()) { return true; } #endif #if BUILDFLAG(IS_WIN) // Windows with certain background materials may be translucent const std::string& bg_material = background_material(); if (!bg_material.empty() && bg_material != "none") { return true; } #endif return false; } // static void NativeWindowRelay::CreateForWebContents( content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) { DCHECK(web_contents); if (!web_contents->GetUserData(UserDataKey())) { web_contents->SetUserData( UserDataKey(), base::WrapUnique(new NativeWindowRelay(web_contents, window))); } } NativeWindowRelay::NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) : content::WebContentsUserData<NativeWindowRelay>(*web_contents), native_window_(window) {} NativeWindowRelay::~NativeWindowRelay() = default; WEB_CONTENTS_USER_DATA_KEY_IMPL(NativeWindowRelay); } // namespace electron
closed
electron/electron
https://github.com/electron/electron
40,826
[Bug]: protocol.handle `file` issue when dealing with FormData
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.1.3 ### What operating system are you using? macOS ### Operating System Version macOS Sonoma 14.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior 1. Intercept `file` protocol using `protocol.handle` 2. Sending FormData in the renderer 3. Request intercepted in the function registered in 1 4. The File's blob size in the form should have correct content and size ### Actual Behavior In step 4, the File's size is 0 ### Testcase Gist URL https://gist.github.com/pengx17/d7b9f3e0f16fd362b44510d3842e90d4 ### Additional Information Please see the console output. The printed File is something like this: ``` FormData { [Symbol(state)]: [ { name: 'file', value: [File] } ] } File { size: 0, type: 'application/octet-stream', name: 'test.txt', lastModified: 1703500799473 } ```
https://github.com/electron/electron/issues/40826
https://github.com/electron/electron/pull/41052
d4413a8e53590b43d622ad9dce4259be89acbb8c
80906c0adb1e1b8103dcdfb8340c4b660b330c25
2023-12-25T10:48:34Z
c++
2024-02-16T19:29:29Z
lib/browser/api/protocol.ts
import { ProtocolRequest, session } from 'electron/main'; import { createReadStream } from 'fs'; import { Readable } from 'stream'; import { ReadableStream } from 'stream/web'; // Global protocol APIs. const { registerSchemesAsPrivileged, getStandardSchemes, Protocol } = process._linkedBinding('electron_browser_protocol'); const ERR_FAILED = -2; const ERR_UNEXPECTED = -9; const isBuiltInScheme = (scheme: string) => ['http', 'https', 'file'].includes(scheme); function makeStreamFromPipe (pipe: any): ReadableStream { const buf = new Uint8Array(1024 * 1024 /* 1 MB */); return new ReadableStream({ async pull (controller) { try { const rv = await pipe.read(buf); if (rv > 0) { controller.enqueue(buf.subarray(0, rv)); } else { controller.close(); } } catch (e) { controller.error(e); } } }); } function convertToRequestBody (uploadData: ProtocolRequest['uploadData']): RequestInit['body'] { if (!uploadData) return null; // Optimization: skip creating a stream if the request is just a single buffer. if (uploadData.length === 1 && (uploadData[0] as any).type === 'rawData') return uploadData[0].bytes; const chunks = [...uploadData] as any[]; // TODO: types are wrong let current: ReadableStreamDefaultReader | null = null; return new ReadableStream({ pull (controller) { if (current) { current.read().then(({ done, value }) => { controller.enqueue(value); if (done) current = null; }, (err) => { controller.error(err); }); } else { if (!chunks.length) { return controller.close(); } const chunk = chunks.shift()!; if (chunk.type === 'rawData') { controller.enqueue(chunk.bytes); } else if (chunk.type === 'file') { current = Readable.toWeb(createReadStream(chunk.filePath, { start: chunk.offset ?? 0, end: chunk.length >= 0 ? chunk.offset + chunk.length : undefined })).getReader(); this.pull!(controller); } else if (chunk.type === 'stream') { current = makeStreamFromPipe(chunk.body).getReader(); this.pull!(controller); } } } }) as RequestInit['body']; } // TODO(codebytere): Use Object.hasOwn() once we update to ECMAScript 2022. function validateResponse (res: Response) { if (!res || typeof res !== 'object') return false; if (res.type === 'error') return true; const exists = (key: string) => Object.hasOwn(res, key); if (exists('status') && typeof res.status !== 'number') return false; if (exists('statusText') && typeof res.statusText !== 'string') return false; if (exists('headers') && typeof res.headers !== 'object') return false; if (exists('body')) { if (typeof res.body !== 'object') return false; if (res.body !== null && !(res.body instanceof ReadableStream)) return false; } return true; } Protocol.prototype.handle = function (this: Electron.Protocol, scheme: string, handler: (req: Request) => Response | Promise<Response>) { const register = isBuiltInScheme(scheme) ? this.interceptProtocol : this.registerProtocol; const success = register.call(this, scheme, async (preq: ProtocolRequest, cb: any) => { try { const body = convertToRequestBody(preq.uploadData); const req = new Request(preq.url, { headers: preq.headers, method: preq.method, referrer: preq.referrer, body, duplex: body instanceof ReadableStream ? 'half' : undefined } as any); const res = await handler(req); if (!validateResponse(res)) { return cb({ error: ERR_UNEXPECTED }); } else if (res.type === 'error') { cb({ error: ERR_FAILED }); } else { cb({ data: res.body ? Readable.fromWeb(res.body as ReadableStream<ArrayBufferView>) : null, headers: res.headers ? Object.fromEntries(res.headers) : {}, statusCode: res.status, statusText: res.statusText, mimeType: (res as any).__original_resp?._responseHead?.mimeType }); } } catch (e) { console.error(e); cb({ error: ERR_UNEXPECTED }); } }); if (!success) throw new Error(`Failed to register protocol: ${scheme}`); }; Protocol.prototype.unhandle = function (this: Electron.Protocol, scheme: string) { const unregister = isBuiltInScheme(scheme) ? this.uninterceptProtocol : this.unregisterProtocol; if (!unregister.call(this, scheme)) { throw new Error(`Failed to unhandle protocol: ${scheme}`); } }; Protocol.prototype.isProtocolHandled = function (this: Electron.Protocol, scheme: string) { const isRegistered = isBuiltInScheme(scheme) ? this.isProtocolIntercepted : this.isProtocolRegistered; return isRegistered.call(this, scheme); }; const protocol = { registerSchemesAsPrivileged, getStandardSchemes, registerStringProtocol: (...args) => session.defaultSession.protocol.registerStringProtocol(...args), registerBufferProtocol: (...args) => session.defaultSession.protocol.registerBufferProtocol(...args), registerStreamProtocol: (...args) => session.defaultSession.protocol.registerStreamProtocol(...args), registerFileProtocol: (...args) => session.defaultSession.protocol.registerFileProtocol(...args), registerHttpProtocol: (...args) => session.defaultSession.protocol.registerHttpProtocol(...args), registerProtocol: (...args) => session.defaultSession.protocol.registerProtocol(...args), unregisterProtocol: (...args) => session.defaultSession.protocol.unregisterProtocol(...args), isProtocolRegistered: (...args) => session.defaultSession.protocol.isProtocolRegistered(...args), interceptStringProtocol: (...args) => session.defaultSession.protocol.interceptStringProtocol(...args), interceptBufferProtocol: (...args) => session.defaultSession.protocol.interceptBufferProtocol(...args), interceptStreamProtocol: (...args) => session.defaultSession.protocol.interceptStreamProtocol(...args), interceptFileProtocol: (...args) => session.defaultSession.protocol.interceptFileProtocol(...args), interceptHttpProtocol: (...args) => session.defaultSession.protocol.interceptHttpProtocol(...args), interceptProtocol: (...args) => session.defaultSession.protocol.interceptProtocol(...args), uninterceptProtocol: (...args) => session.defaultSession.protocol.uninterceptProtocol(...args), isProtocolIntercepted: (...args) => session.defaultSession.protocol.isProtocolIntercepted(...args), handle: (...args) => session.defaultSession.protocol.handle(...args), unhandle: (...args) => session.defaultSession.protocol.unhandle(...args), isProtocolHandled: (...args) => session.defaultSession.protocol.isProtocolHandled(...args) } as typeof Electron.protocol; export default protocol;
closed
electron/electron
https://github.com/electron/electron
40,826
[Bug]: protocol.handle `file` issue when dealing with FormData
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 27.1.3 ### What operating system are you using? macOS ### Operating System Version macOS Sonoma 14.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior 1. Intercept `file` protocol using `protocol.handle` 2. Sending FormData in the renderer 3. Request intercepted in the function registered in 1 4. The File's blob size in the form should have correct content and size ### Actual Behavior In step 4, the File's size is 0 ### Testcase Gist URL https://gist.github.com/pengx17/d7b9f3e0f16fd362b44510d3842e90d4 ### Additional Information Please see the console output. The printed File is something like this: ``` FormData { [Symbol(state)]: [ { name: 'file', value: [File] } ] } File { size: 0, type: 'application/octet-stream', name: 'test.txt', lastModified: 1703500799473 } ```
https://github.com/electron/electron/issues/40826
https://github.com/electron/electron/pull/41052
d4413a8e53590b43d622ad9dce4259be89acbb8c
80906c0adb1e1b8103dcdfb8340c4b660b330c25
2023-12-25T10:48:34Z
c++
2024-02-16T19:29:29Z
spec/api-protocol-spec.ts
import { expect } from 'chai'; import { v4 } from 'uuid'; import { protocol, webContents, WebContents, session, BrowserWindow, ipcMain, net } from 'electron/main'; import * as ChildProcess from 'node:child_process'; import * as path from 'node:path'; import * as url from 'node:url'; import * as http from 'node:http'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as stream from 'node:stream'; import { EventEmitter, once } from 'node:events'; import { closeAllWindows, closeWindow } from './lib/window-helpers'; import { WebmGenerator } from './lib/video-helpers'; import { listen, defer, ifit } from './lib/spec-helpers'; import { setTimeout } from 'node:timers/promises'; const fixturesPath = path.resolve(__dirname, 'fixtures'); const registerStringProtocol = protocol.registerStringProtocol; const registerBufferProtocol = protocol.registerBufferProtocol; const registerFileProtocol = protocol.registerFileProtocol; const registerStreamProtocol = protocol.registerStreamProtocol; const interceptStringProtocol = protocol.interceptStringProtocol; const interceptBufferProtocol = protocol.interceptBufferProtocol; const interceptHttpProtocol = protocol.interceptHttpProtocol; const interceptStreamProtocol = protocol.interceptStreamProtocol; const unregisterProtocol = protocol.unregisterProtocol; const uninterceptProtocol = protocol.uninterceptProtocol; const text = 'valar morghulis'; const protocolName = 'no-cors'; const postData = { name: 'post test', type: 'string' }; function getStream (chunkSize = text.length, data: Buffer | string = text) { // allowHalfOpen required, otherwise Readable.toWeb gets confused and thinks // the stream isn't done when the readable half ends. const body = new stream.PassThrough({ allowHalfOpen: false }); async function sendChunks () { await setTimeout(0); // the stream protocol API breaks if you send data immediately. let buf = Buffer.from(data as any); // nodejs typings are wrong, Buffer.from can take a Buffer for (;;) { body.push(buf.slice(0, chunkSize)); buf = buf.slice(chunkSize); if (!buf.length) { break; } // emulate some network delay await setTimeout(10); } body.push(null); } sendChunks(); return body; } function getWebStream (chunkSize = text.length, data: Buffer | string = text): ReadableStream<ArrayBufferView> { return stream.Readable.toWeb(getStream(chunkSize, data)) as ReadableStream<ArrayBufferView>; } // A promise that can be resolved externally. function deferPromise (): Promise<any> & {resolve: Function, reject: Function} { let promiseResolve: Function = null as unknown as Function; let promiseReject: Function = null as unknown as Function; const promise: any = new Promise((resolve, reject) => { promiseResolve = resolve; promiseReject = reject; }); promise.resolve = promiseResolve; promise.reject = promiseReject; return promise; } describe('protocol module', () => { let contents: WebContents; // NB. sandbox: true is used because it makes navigations much (~8x) faster. before(() => { contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); }); after(() => contents.destroy()); async function ajax (url: string, options = {}) { // Note that we need to do navigation every time after a protocol is // registered or unregistered, otherwise the new protocol won't be // recognized by current page when NetworkService is used. await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html')); return contents.executeJavaScript(`ajax("${url}", ${JSON.stringify(options)})`); } afterEach(() => { protocol.unregisterProtocol(protocolName); protocol.uninterceptProtocol('http'); }); describe('protocol.register(Any)Protocol', () => { it('fails when scheme is already registered', () => { expect(registerStringProtocol(protocolName, (req, cb) => cb(''))).to.equal(true); expect(registerBufferProtocol(protocolName, (req, cb) => cb(Buffer.from('')))).to.equal(false); }); it('does not crash when handler is called twice', async () => { registerStringProtocol(protocolName, (request, callback) => { try { callback(text); callback(''); } catch { // Ignore error } }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sends error when callback is called with nothing', async () => { registerBufferProtocol(protocolName, (req, cb: any) => cb()); await expect(ajax(protocolName + '://fake-host')).to.eventually.be.rejected(); }); it('does not crash when callback is called in next tick', async () => { registerStringProtocol(protocolName, (request, callback) => { setImmediate(() => callback(text)); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('can redirect to the same scheme', async () => { registerStringProtocol(protocolName, (request, callback) => { if (request.url === `${protocolName}://fake-host/redirect`) { callback({ statusCode: 302, headers: { Location: `${protocolName}://fake-host` } }); } else { expect(request.url).to.equal(`${protocolName}://fake-host`); callback('redirected'); } }); const r = await ajax(`${protocolName}://fake-host/redirect`); expect(r.data).to.equal('redirected'); }); }); describe('protocol.unregisterProtocol', () => { it('returns false when scheme does not exist', () => { expect(unregisterProtocol('not-exist')).to.equal(false); }); }); for (const [registerStringProtocol, name] of [ [protocol.registerStringProtocol, 'protocol.registerStringProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerStringProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { it('sends string as response', async () => { registerStringProtocol(protocolName, (request, callback) => callback(text)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sets Access-Control-Allow-Origin', async () => { registerStringProtocol(protocolName, (request, callback) => callback(text)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sends object as response', async () => { registerStringProtocol(protocolName, (request, callback) => { callback({ data: text, mimeType: 'text/html' }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending object other than string', async () => { const notAString = () => {}; registerStringProtocol(protocolName, (request, callback) => callback(notAString as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); } for (const [registerBufferProtocol, name] of [ [protocol.registerBufferProtocol, 'protocol.registerBufferProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerBufferProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { const buffer = Buffer.from(text); it('sends Buffer as response', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(buffer)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sets Access-Control-Allow-Origin', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(buffer)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sends object as response', async () => { registerBufferProtocol(protocolName, (request, callback) => { callback({ data: buffer, mimeType: 'text/html' }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); if (name !== 'protocol.registerProtocol') { it('fails when sending string', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(text as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); } }); } for (const [registerFileProtocol, name] of [ [protocol.registerFileProtocol, 'protocol.registerFileProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerFileProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { const filePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'file1'); const fileContent = fs.readFileSync(filePath); const normalPath = path.join(fixturesPath, 'pages', 'a.html'); const normalContent = fs.readFileSync(normalPath); afterEach(closeAllWindows); if (name === 'protocol.registerFileProtocol') { it('sends file path as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback(filePath)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); }); } it('sets Access-Control-Allow-Origin', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sets custom headers', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath, headers: { 'X-Great-Header': 'sogreat' } })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); expect(r.headers).to.have.property('x-great-header', 'sogreat'); }); it('can load iframes with custom protocols', async () => { registerFileProtocol('custom', (request, callback) => { const filename = request.url.substring(9); const p = path.join(__dirname, 'fixtures', 'pages', filename); callback({ path: p }); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const loaded = once(ipcMain, 'loaded-iframe-custom-protocol'); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'iframe-protocol.html')); await loaded; }); it('sends object as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); }); it('can send normal file', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: normalPath })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(normalContent)); }); it('fails when sending unexist-file', async () => { const fakeFilePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'not-exist'); registerFileProtocol(protocolName, (request, callback) => callback({ path: fakeFilePath })); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('fails when sending unsupported content', async () => { registerFileProtocol(protocolName, (request, callback) => callback(new Date() as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); } for (const [registerHttpProtocol, name] of [ [protocol.registerHttpProtocol, 'protocol.registerHttpProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerHttpProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { it('sends url as response', async () => { const server = http.createServer((req, res) => { expect(req.headers.accept).to.not.equal(''); res.end(text); server.close(); }); const { url } = await listen(server); registerHttpProtocol(protocolName, (request, callback) => callback({ url })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending invalid url', async () => { registerHttpProtocol(protocolName, (request, callback) => callback({ url: 'url' })); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('fails when sending unsupported content', async () => { registerHttpProtocol(protocolName, (request, callback) => callback(new Date() as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('works when target URL redirects', async () => { const server = http.createServer((req, res) => { if (req.url === '/serverRedirect') { res.statusCode = 301; res.setHeader('Location', `http://${req.rawHeaders[1]}`); res.end(); } else { res.end(text); } }); after(() => server.close()); const { port } = await listen(server); const url = `${protocolName}://fake-host`; const redirectURL = `http://127.0.0.1:${port}/serverRedirect`; registerHttpProtocol(protocolName, (request, callback) => callback({ url: redirectURL })); const r = await ajax(url); expect(r.data).to.equal(text); }); it('can access request headers', (done) => { protocol.registerHttpProtocol(protocolName, (request) => { try { expect(request).to.have.property('headers'); done(); } catch (e) { done(e); } }); ajax(protocolName + '://fake-host').catch(() => {}); }); }); } for (const [registerStreamProtocol, name] of [ [protocol.registerStreamProtocol, 'protocol.registerStreamProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerStreamProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { it('sends Stream as response', async () => { registerStreamProtocol(protocolName, (request, callback) => callback(getStream())); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sends object as response', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream() })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.status).to.equal(200); }); it('sends custom response headers', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream(3), headers: { 'x-electron': ['a', 'b'] } })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.status).to.equal(200); expect(r.headers).to.have.property('x-electron', 'a, b'); }); it('sends custom status code', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ statusCode: 204, data: null as any })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.be.empty('data'); expect(r.status).to.equal(204); }); it('receives request headers', async () => { registerStreamProtocol(protocolName, (request, callback) => { callback({ headers: { 'content-type': 'application/json' }, data: getStream(5, JSON.stringify(Object.assign({}, request.headers))) }); }); const r = await ajax(protocolName + '://fake-host', { headers: { 'x-return-headers': 'yes' } }); expect(JSON.parse(r.data)['x-return-headers']).to.equal('yes'); }); it('returns response multiple response headers with the same name', async () => { registerStreamProtocol(protocolName, (request, callback) => { callback({ headers: { header1: ['value1', 'value2'], header2: 'value3' }, data: getStream() }); }); const r = await ajax(protocolName + '://fake-host'); // SUBTLE: when the response headers have multiple values it // separates values by ", ". When the response headers are incorrectly // converting an array to a string it separates values by ",". expect(r.headers).to.have.property('header1', 'value1, value2'); expect(r.headers).to.have.property('header2', 'value3'); }); it('can handle large responses', async () => { const data = Buffer.alloc(128 * 1024); registerStreamProtocol(protocolName, (request, callback) => { callback(getStream(data.length, data)); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.have.lengthOf(data.length); }); it('can handle a stream completing while writing', async () => { function dumbPassthrough () { return new stream.Transform({ async transform (chunk, encoding, cb) { cb(null, chunk); } }); } registerStreamProtocol(protocolName, (request, callback) => { callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: getStream(1024 * 1024, Buffer.alloc(1024 * 1024 * 2)).pipe(dumbPassthrough()) }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.have.lengthOf(1024 * 1024 * 2); }); it('can handle next-tick scheduling during read calls', async () => { const events = new EventEmitter(); function createStream () { const buffers = [ Buffer.alloc(65536), Buffer.alloc(65537), Buffer.alloc(39156) ]; const e = new stream.Readable({ highWaterMark: 0 }); e.push(buffers.shift()); e._read = function () { process.nextTick(() => this.push(buffers.shift() || null)); }; e.on('end', function () { events.emit('end'); }); return e; } registerStreamProtocol(protocolName, (request, callback) => { callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: createStream() }); }); const hasEndedPromise = once(events, 'end'); ajax(protocolName + '://fake-host').catch(() => {}); await hasEndedPromise; }); it('destroys response streams when aborted before completion', async () => { const events = new EventEmitter(); registerStreamProtocol(protocolName, (request, callback) => { const responseStream = new stream.PassThrough(); responseStream.push('data\r\n'); responseStream.on('close', () => { events.emit('close'); }); callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: responseStream }); events.emit('respond'); }); const hasRespondedPromise = once(events, 'respond'); const hasClosedPromise = once(events, 'close'); ajax(protocolName + '://fake-host').catch(() => {}); await hasRespondedPromise; await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html')); await hasClosedPromise; }); }); } describe('protocol.isProtocolRegistered', () => { it('returns false when scheme is not registered', () => { const result = protocol.isProtocolRegistered('no-exist'); expect(result).to.be.false('no-exist: is handled'); }); it('returns true for custom protocol', () => { registerStringProtocol(protocolName, (request, callback) => callback('')); const result = protocol.isProtocolRegistered(protocolName); expect(result).to.be.true('custom protocol is handled'); }); }); describe('protocol.isProtocolIntercepted', () => { it('returns true for intercepted protocol', () => { interceptStringProtocol('http', (request, callback) => callback('')); const result = protocol.isProtocolIntercepted('http'); expect(result).to.be.true('intercepted protocol is handled'); }); }); describe('protocol.intercept(Any)Protocol', () => { it('returns false when scheme is already intercepted', () => { expect(protocol.interceptStringProtocol('http', (request, callback) => callback(''))).to.equal(true); expect(protocol.interceptBufferProtocol('http', (request, callback) => callback(Buffer.from('')))).to.equal(false); }); it('does not crash when handler is called twice', async () => { interceptStringProtocol('http', (request, callback) => { try { callback(text); callback(''); } catch { // Ignore error } }); const r = await ajax('http://fake-host'); expect(r.data).to.be.equal(text); }); it('sends error when callback is called with nothing', async () => { interceptStringProtocol('http', (request, callback: any) => callback()); await expect(ajax('http://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.interceptStringProtocol', () => { it('can intercept http protocol', async () => { interceptStringProtocol('http', (request, callback) => callback(text)); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can set content-type', async () => { interceptStringProtocol('http', (request, callback) => { callback({ mimeType: 'application/json', data: '{"value": 1}' }); }); const r = await ajax('http://fake-host'); expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1); }); it('can set content-type with charset', async () => { interceptStringProtocol('http', (request, callback) => { callback({ mimeType: 'application/json; charset=UTF-8', data: '{"value": 1}' }); }); const r = await ajax('http://fake-host'); expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1); }); it('can receive post data', async () => { interceptStringProtocol('http', (request, callback) => { const uploadData = request.uploadData![0].bytes.toString(); callback({ data: uploadData }); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); }); describe('protocol.interceptBufferProtocol', () => { it('can intercept http protocol', async () => { interceptBufferProtocol('http', (request, callback) => callback(Buffer.from(text))); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can receive post data', async () => { interceptBufferProtocol('http', (request, callback) => { const uploadData = request.uploadData![0].bytes; callback(uploadData); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect(qs.parse(r.data)).to.deep.equal({ name: 'post test', type: 'string' }); }); }); describe('protocol.interceptHttpProtocol', () => { // FIXME(zcbenz): This test was passing because the test itself was wrong, // I don't know whether it ever passed before and we should take a look at // it in future. xit('can send POST request', async () => { const server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); req.on('end', () => { res.end(body); }); server.close(); }); after(() => server.close()); const { url } = await listen(server); interceptHttpProtocol('http', (request, callback) => { const data: Electron.ProtocolResponse = { url: url, method: 'POST', uploadData: { contentType: 'application/x-www-form-urlencoded', data: request.uploadData![0].bytes }, session: undefined }; callback(data); }); const r = await ajax('http://fake-host', { type: 'POST', data: postData }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); it('can use custom session', async () => { const customSession = session.fromPartition('custom-ses', { cache: false }); customSession.webRequest.onBeforeRequest((details, callback) => { expect(details.url).to.equal('http://fake-host/'); callback({ cancel: true }); }); after(() => customSession.webRequest.onBeforeRequest(null)); interceptHttpProtocol('http', (request, callback) => { callback({ url: request.url, session: customSession }); }); await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error); }); it('can access request headers', (done) => { protocol.interceptHttpProtocol('http', (request) => { try { expect(request).to.have.property('headers'); done(); } catch (e) { done(e); } }); ajax('http://fake-host').catch(() => {}); }); }); describe('protocol.interceptStreamProtocol', () => { it('can intercept http protocol', async () => { interceptStreamProtocol('http', (request, callback) => callback(getStream())); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can receive post data', async () => { interceptStreamProtocol('http', (request, callback) => { callback(getStream(3, request.uploadData![0].bytes.toString())); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); it('can execute redirects', async () => { interceptStreamProtocol('http', (request, callback) => { if (request.url.indexOf('http://fake-host') === 0) { setTimeout(300).then(() => { callback({ data: '', statusCode: 302, headers: { Location: 'http://fake-redirect' } }); }); } else { expect(request.url.indexOf('http://fake-redirect')).to.equal(0); callback(getStream(1, 'redirect')); } }); const r = await ajax('http://fake-host'); expect(r.data).to.equal('redirect'); }); it('should discard post data after redirection', async () => { interceptStreamProtocol('http', (request, callback) => { if (request.url.indexOf('http://fake-host') === 0) { setTimeout(300).then(() => { callback({ statusCode: 302, headers: { Location: 'http://fake-redirect' } }); }); } else { expect(request.url.indexOf('http://fake-redirect')).to.equal(0); callback(getStream(3, request.method)); } }); const r = await ajax('http://fake-host', { type: 'POST', data: postData }); expect(r.data).to.equal('GET'); }); }); describe('protocol.uninterceptProtocol', () => { it('returns false when scheme does not exist', () => { expect(uninterceptProtocol('not-exist')).to.equal(false); }); it('returns false when scheme is not intercepted', () => { expect(uninterceptProtocol('http')).to.equal(false); }); }); describe('protocol.registerSchemeAsPrivileged', () => { it('does not crash on exit', async () => { const appPath = path.join(__dirname, 'fixtures', 'api', 'custom-protocol-shutdown.js'); const appProcess = ChildProcess.spawn(process.execPath, ['--enable-logging', appPath]); let stdout = ''; let stderr = ''; appProcess.stdout.on('data', data => { process.stdout.write(data); stdout += data; }); appProcess.stderr.on('data', data => { process.stderr.write(data); stderr += data; }); const [code] = await once(appProcess, 'exit'); if (code !== 0) { console.log('Exit code : ', code); console.log('stdout : ', stdout); console.log('stderr : ', stderr); } expect(code).to.equal(0); expect(stdout).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED'); expect(stderr).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED'); }); }); describe('protocol.registerSchemesAsPrivileged allowServiceWorkers', () => { protocol.registerStringProtocol(serviceWorkerScheme, (request, cb) => { if (request.url.endsWith('.js')) { cb({ mimeType: 'text/javascript', charset: 'utf-8', data: 'console.log("Loaded")' }); } else { cb({ mimeType: 'text/html', charset: 'utf-8', data: '<!DOCTYPE html>' }); } }); after(() => protocol.unregisterProtocol(serviceWorkerScheme)); it('should fail when registering invalid service worker', async () => { await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`); await expect(contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.notjs', {scope: './'})`)).to.be.rejected(); }); it('should be able to register service worker for custom scheme', async () => { await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`); await contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.js', {scope: './'})`); }); }); describe('protocol.registerSchemesAsPrivileged standard', () => { const origin = `${standardScheme}://fake-host`; const imageURL = `${origin}/test.png`; const filePath = path.join(fixturesPath, 'pages', 'b.html'); const fileContent = '<img src="/test.png" />'; let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); unregisterProtocol(standardScheme); w = null as unknown as BrowserWindow; }); it('resolves relative resources', async () => { registerFileProtocol(standardScheme, (request, callback) => { if (request.url === imageURL) { callback(''); } else { callback(filePath); } }); await w.loadURL(origin); }); it('resolves absolute resources', async () => { registerStringProtocol(standardScheme, (request, callback) => { if (request.url === imageURL) { callback(''); } else { callback({ data: fileContent, mimeType: 'text/html' }); } }); await w.loadURL(origin); }); it('can have fetch working in it', async () => { const requestReceived = deferPromise(); const server = http.createServer((req, res) => { res.end(); server.close(); requestReceived.resolve(); }); const { url } = await listen(server); const content = `<script>fetch(${JSON.stringify(url)})</script>`; registerStringProtocol(standardScheme, (request, callback) => callback({ data: content, mimeType: 'text/html' })); await w.loadURL(origin); await requestReceived; }); it('can access files through the FileSystem API', (done) => { const filePath = path.join(fixturesPath, 'pages', 'filesystem.html'); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); w.loadURL(origin); ipcMain.once('file-system-error', (event, err) => done(err)); ipcMain.once('file-system-write-end', () => done()); }); it('registers secure, when {secure: true}', (done) => { const filePath = path.join(fixturesPath, 'pages', 'cache-storage.html'); ipcMain.once('success', () => done()); ipcMain.once('failure', (event, err) => done(err)); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); w.loadURL(origin); }); }); describe('protocol.registerSchemesAsPrivileged cors-fetch', function () { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; for (const scheme of [standardScheme, 'cors', 'no-cors', 'no-fetch']) { protocol.unregisterProtocol(scheme); } }); it('supports fetch api by default', async () => { const url = `file://${fixturesPath}/assets/logo.png`; await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const ok = await w.webContents.executeJavaScript(`fetch(${JSON.stringify(url)}).then(r => r.ok)`); expect(ok).to.be.true('response ok'); }); it('allows CORS requests by default', async () => { await allowsCORSRequests('cors', 200, new RegExp(''), () => { const { ipcRenderer } = require('electron'); fetch('cors://myhost').then(function (response) { ipcRenderer.send('response', response.status); }).catch(function () { ipcRenderer.send('response', 'failed'); }); }); }); // DISABLED-FIXME: Figure out why this test is failing it('disallows CORS and fetch requests when only supportFetchAPI is specified', async () => { await allowsCORSRequests('no-cors', ['failed xhr', 'failed fetch'], /has been blocked by CORS policy/, () => { const { ipcRenderer } = require('electron'); Promise.all([ new Promise(resolve => { const req = new XMLHttpRequest(); req.onload = () => resolve('loaded xhr'); req.onerror = () => resolve('failed xhr'); req.open('GET', 'no-cors://myhost'); req.send(); }), fetch('no-cors://myhost') .then(() => 'loaded fetch') .catch(() => 'failed fetch') ]).then(([xhr, fetch]) => { ipcRenderer.send('response', [xhr, fetch]); }); }); }); it('allows CORS, but disallows fetch requests, when specified', async () => { await allowsCORSRequests('no-fetch', ['loaded xhr', 'failed fetch'], /Fetch API cannot load/, () => { const { ipcRenderer } = require('electron'); Promise.all([ new Promise(resolve => { const req = new XMLHttpRequest(); req.onload = () => resolve('loaded xhr'); req.onerror = () => resolve('failed xhr'); req.open('GET', 'no-fetch://myhost'); req.send(); }), fetch('no-fetch://myhost') .then(() => 'loaded fetch') .catch(() => 'failed fetch') ]).then(([xhr, fetch]) => { ipcRenderer.send('response', [xhr, fetch]); }); }); }); async function allowsCORSRequests (corsScheme: string, expected: any, expectedConsole: RegExp, content: Function) { registerStringProtocol(standardScheme, (request, callback) => { callback({ data: `<script>(${content})()</script>`, mimeType: 'text/html' }); }); registerStringProtocol(corsScheme, (request, callback) => { callback(''); }); const newContents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true, contextIsolation: false }); const consoleMessages: string[] = []; newContents.on('console-message', (e, level, message) => consoleMessages.push(message)); try { newContents.loadURL(standardScheme + '://fake-host'); const [, response] = await once(ipcMain, 'response'); expect(response).to.deep.equal(expected); expect(consoleMessages.join('\n')).to.match(expectedConsole); } finally { // This is called in a timeout to avoid a crash that happens when // calling destroy() in a microtask. setTimeout().then(() => { newContents.destroy(); }); } } }); describe('protocol.registerSchemesAsPrivileged stream', async function () { const pagePath = path.join(fixturesPath, 'pages', 'video.html'); const videoSourceImagePath = path.join(fixturesPath, 'video-source-image.webp'); const videoPath = path.join(fixturesPath, 'video.webm'); let w: BrowserWindow; before(async () => { // generate test video const imageBase64 = await fs.promises.readFile(videoSourceImagePath, 'base64'); const imageDataUrl = `data:image/webp;base64,${imageBase64}`; const encoder = new WebmGenerator(15); for (let i = 0; i < 30; i++) { encoder.add(imageDataUrl); } await new Promise((resolve, reject) => { encoder.compile((output:Uint8Array) => { fs.promises.writeFile(videoPath, output).then(resolve, reject); }); }); }); after(async () => { await fs.promises.unlink(videoPath); }); beforeEach(async function () { w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) { this.skip(); } }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; await protocol.unregisterProtocol(standardScheme); await protocol.unregisterProtocol('stream'); }); it('successfully plays videos when content is buffered (stream: false)', async () => { await streamsResponses(standardScheme, 'play'); }); it('successfully plays videos when streaming content (stream: true)', async () => { await streamsResponses('stream', 'play'); }); async function streamsResponses (testingScheme: string, expected: any) { const protocolHandler = (request: any, callback: Function) => { if (request.url.includes('/video.webm')) { const stat = fs.statSync(videoPath); const fileSize = stat.size; const range = request.headers.Range; if (range) { const parts = range.replace(/bytes=/, '').split('-'); const start = parseInt(parts[0], 10); const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1; const chunksize = (end - start) + 1; const headers = { 'Content-Range': `bytes ${start}-${end}/${fileSize}`, 'Accept-Ranges': 'bytes', 'Content-Length': String(chunksize), 'Content-Type': 'video/webm' }; callback({ statusCode: 206, headers, data: fs.createReadStream(videoPath, { start, end }) }); } else { callback({ statusCode: 200, headers: { 'Content-Length': String(fileSize), 'Content-Type': 'video/webm' }, data: fs.createReadStream(videoPath) }); } } else { callback({ data: fs.createReadStream(pagePath), headers: { 'Content-Type': 'text/html' }, statusCode: 200 }); } }; await registerStreamProtocol(standardScheme, protocolHandler); await registerStreamProtocol('stream', protocolHandler); const newContents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true, contextIsolation: false }); try { newContents.loadURL(testingScheme + '://fake-host'); const [, response] = await once(ipcMain, 'result'); expect(response).to.deep.equal(expected); } finally { // This is called in a timeout to avoid a crash that happens when // calling destroy() in a microtask. setTimeout().then(() => { newContents.destroy(); }); } } }); describe('protocol.registerSchemesAsPrivileged codeCache', function () { const temp = require('temp').track(); const appPath = path.join(fixturesPath, 'apps', 'refresh-page'); let w: BrowserWindow; let codeCachePath: string; beforeEach(async () => { w = new BrowserWindow({ show: false }); codeCachePath = temp.path(); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('code cache in custom protocol is disabled by default', async () => { ChildProcess.spawnSync(process.execPath, [appPath, 'false', codeCachePath]); expect(fs.readdirSync(path.join(codeCachePath, 'js')).length).to.equal(2); }); it('codeCache:true enables codeCache in custom protocol', async () => { ChildProcess.spawnSync(process.execPath, [appPath, 'true', codeCachePath]); expect(fs.readdirSync(path.join(codeCachePath, 'js')).length).to.above(2); }); }); describe('handle', () => { afterEach(closeAllWindows); it('receives requests to a custom scheme', async () => { protocol.handle('test-scheme', (req) => new Response('hello ' + req.url)); defer(() => { protocol.unhandle('test-scheme'); }); const resp = await net.fetch('test-scheme://foo'); expect(resp.status).to.equal(200); }); it('can be unhandled', async () => { protocol.handle('test-scheme', (req) => new Response('hello ' + req.url)); defer(() => { try { // In case of failure, make sure we unhandle. But we should succeed // :) protocol.unhandle('test-scheme'); } catch { /* ignore */ } }); const resp1 = await net.fetch('test-scheme://foo'); expect(resp1.status).to.equal(200); protocol.unhandle('test-scheme'); await expect(net.fetch('test-scheme://foo')).to.eventually.be.rejectedWith(/ERR_UNKNOWN_URL_SCHEME/); }); it('receives requests to the existing https scheme', async () => { protocol.handle('https', (req) => new Response('hello ' + req.url)); defer(() => { protocol.unhandle('https'); }); const body = await net.fetch('https://foo').then(r => r.text()); expect(body).to.equal('hello https://foo/'); }); it('receives requests to the existing file scheme', (done) => { const filePath = path.join(__dirname, 'fixtures', 'pages', 'a.html'); protocol.handle('file', (req) => { let file; if (process.platform === 'win32') { file = `file:///${filePath.replaceAll('\\', '/')}`; } else { file = `file://${filePath}`; } if (req.url === file) done(); return new Response(req.url); }); defer(() => { protocol.unhandle('file'); }); const w = new BrowserWindow(); w.loadFile(filePath); }); it('receives requests to an existing scheme when navigating', async () => { protocol.handle('https', (req) => new Response('hello ' + req.url)); defer(() => { protocol.unhandle('https'); }); const w = new BrowserWindow({ show: false }); await w.loadURL('https://localhost'); expect(await w.webContents.executeJavaScript('document.body.textContent')).to.equal('hello https://localhost/'); }); it('can send buffer body', async () => { protocol.handle('test-scheme', (req) => new Response(Buffer.from('hello ' + req.url))); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body).to.equal('hello test-scheme://foo'); }); it('can send stream body', async () => { protocol.handle('test-scheme', () => new Response(getWebStream())); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body).to.equal(text); }); it('accepts urls with no hostname in non-standard schemes', async () => { protocol.handle('test-scheme', (req) => new Response(req.url)); defer(() => { protocol.unhandle('test-scheme'); }); { const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body).to.equal('test-scheme://foo'); } { const body = await net.fetch('test-scheme:///foo').then(r => r.text()); expect(body).to.equal('test-scheme:///foo'); } { const body = await net.fetch('test-scheme://').then(r => r.text()); expect(body).to.equal('test-scheme://'); } }); it('accepts urls with a port-like component in non-standard schemes', async () => { protocol.handle('test-scheme', (req) => new Response(req.url)); defer(() => { protocol.unhandle('test-scheme'); }); { const body = await net.fetch('test-scheme://foo:30').then(r => r.text()); expect(body).to.equal('test-scheme://foo:30'); } }); it('normalizes urls in standard schemes', async () => { // NB. 'app' is registered as a standard scheme in test setup. protocol.handle('app', (req) => new Response(req.url)); defer(() => { protocol.unhandle('app'); }); { const body = await net.fetch('app://foo').then(r => r.text()); expect(body).to.equal('app://foo/'); } { const body = await net.fetch('app:///foo').then(r => r.text()); expect(body).to.equal('app://foo/'); } // NB. 'app' is registered with the default scheme type of 'host'. { const body = await net.fetch('app://foo:1234').then(r => r.text()); expect(body).to.equal('app://foo/'); } await expect(net.fetch('app://')).to.be.rejectedWith('Invalid URL'); }); it('fails on URLs with a username', async () => { // NB. 'app' is registered as a standard scheme in test setup. protocol.handle('http', (req) => new Response(req.url)); defer(() => { protocol.unhandle('http'); }); await expect(contents.loadURL('http://x@foo:1234')).to.be.rejectedWith(/ERR_UNEXPECTED/); }); it('normalizes http urls', async () => { protocol.handle('http', (req) => new Response(req.url)); defer(() => { protocol.unhandle('http'); }); { const body = await net.fetch('http://foo').then(r => r.text()); expect(body).to.equal('http://foo/'); } }); it('can send errors', async () => { protocol.handle('test-scheme', () => Response.error()); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.eventually.be.rejectedWith('net::ERR_FAILED'); }); it('handles invalid protocol response status', async () => { protocol.handle('test-scheme', () => { return { status: [] } as any; }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles invalid protocol response statusText', async () => { protocol.handle('test-scheme', () => { return { statusText: false } as any; }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles invalid protocol response header parameters', async () => { protocol.handle('test-scheme', () => { return { headers: false } as any; }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles invalid protocol response body parameters', async () => { protocol.handle('test-scheme', () => { return { body: false } as any; }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles a synchronous error in the handler', async () => { protocol.handle('test-scheme', () => { throw new Error('test'); }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles an asynchronous error in the handler', async () => { protocol.handle('test-scheme', () => Promise.reject(new Error('rejected promise'))); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('correctly sets statusCode', async () => { protocol.handle('test-scheme', () => new Response(null, { status: 201 })); defer(() => { protocol.unhandle('test-scheme'); }); const resp = await net.fetch('test-scheme://foo'); expect(resp.status).to.equal(201); }); it('correctly sets content-type and charset', async () => { protocol.handle('test-scheme', () => new Response(null, { headers: { 'content-type': 'text/html; charset=testcharset' } })); defer(() => { protocol.unhandle('test-scheme'); }); const resp = await net.fetch('test-scheme://foo'); expect(resp.headers.get('content-type')).to.equal('text/html; charset=testcharset'); }); it('can forward to http', async () => { const server = http.createServer((req, res) => { res.end(text); }); defer(() => { server.close(); }); const { url } = await listen(server); protocol.handle('test-scheme', () => net.fetch(url)); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body).to.equal(text); }); it('can forward an http request with headers', async () => { const server = http.createServer((req, res) => { res.setHeader('foo', 'bar'); res.end(text); }); defer(() => { server.close(); }); const { url } = await listen(server); protocol.handle('test-scheme', (req) => net.fetch(url, { headers: req.headers })); defer(() => { protocol.unhandle('test-scheme'); }); const resp = await net.fetch('test-scheme://foo'); expect(resp.headers.get('foo')).to.equal('bar'); }); it('can forward to file', async () => { protocol.handle('test-scheme', () => net.fetch(url.pathToFileURL(path.join(__dirname, 'fixtures', 'hello.txt')).toString())); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body.trimEnd()).to.equal('hello world'); }); it('can receive simple request body', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo', { method: 'POST', body: 'foobar' }).then(r => r.text()); expect(body).to.equal('foobar'); }); it('can receive stream request body', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo', { method: 'POST', body: getWebStream(), duplex: 'half' // https://github.com/microsoft/TypeScript/issues/53157 } as any).then(r => r.text()); expect(body).to.equal(text); }); it('can receive multi-part postData from loadURL', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); await contents.loadURL('test-scheme://foo', { postData: [{ type: 'rawData', bytes: Buffer.from('a') }, { type: 'rawData', bytes: Buffer.from('b') }] }); expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('ab'); }); it('can receive file postData from loadURL', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); await contents.loadURL('test-scheme://foo', { postData: [{ type: 'file', filePath: path.join(fixturesPath, 'hello.txt'), length: 'hello world\n'.length, offset: 0, modificationTime: 0 }] }); expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('hello world\n'); }); it('can receive file postData from a form', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); await contents.loadURL('data:text/html,<form action="test-scheme://foo" method=POST enctype="multipart/form-data"><input name=foo type=file>'); const { debugger: dbg } = contents; dbg.attach(); const { root } = await dbg.sendCommand('DOM.getDocument'); const { nodeId: fileInputNodeId } = await dbg.sendCommand('DOM.querySelector', { nodeId: root.nodeId, selector: 'input' }); await dbg.sendCommand('DOM.setFileInputFiles', { nodeId: fileInputNodeId, files: [ path.join(fixturesPath, 'hello.txt') ] }); const navigated = once(contents, 'did-finish-load'); await contents.executeJavaScript('document.querySelector("form").submit()'); await navigated; expect(await contents.executeJavaScript('document.documentElement.textContent')).to.match(/------WebKitFormBoundary.*\nContent-Disposition: form-data; name="foo"; filename="hello.txt"\nContent-Type: text\/plain\n\nhello world\n\n------WebKitFormBoundary.*--\n/); }); it('can receive streaming fetch upload', async () => { protocol.handle('no-cors', (req) => new Response(req.body)); defer(() => { protocol.unhandle('no-cors'); }); await contents.loadURL('no-cors://foo'); const fetchBodyResult = await contents.executeJavaScript(` const stream = new ReadableStream({ async start(controller) { controller.enqueue('hello world'); controller.close(); }, }).pipeThrough(new TextEncoderStream()); fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()) `); expect(fetchBodyResult).to.equal('hello world'); }); it('can receive streaming fetch upload when a webRequest handler is present', async () => { session.defaultSession.webRequest.onBeforeRequest((details, cb) => { console.log('webRequest', details.url, details.method); cb({}); }); defer(() => { session.defaultSession.webRequest.onBeforeRequest(null); }); protocol.handle('no-cors', (req) => { console.log('handle', req.url, req.method); return new Response(req.body); }); defer(() => { protocol.unhandle('no-cors'); }); await contents.loadURL('no-cors://foo'); const fetchBodyResult = await contents.executeJavaScript(` const stream = new ReadableStream({ async start(controller) { controller.enqueue('hello world'); controller.close(); }, }).pipeThrough(new TextEncoderStream()); fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()) `); expect(fetchBodyResult).to.equal('hello world'); }); it('can receive an error from streaming fetch upload', async () => { protocol.handle('no-cors', (req) => new Response(req.body)); defer(() => { protocol.unhandle('no-cors'); }); await contents.loadURL('no-cors://foo'); const fetchBodyResult = await contents.executeJavaScript(` const stream = new ReadableStream({ async start(controller) { controller.error('test') }, }); fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()).catch(err => err) `); expect(fetchBodyResult).to.be.an.instanceOf(Error); }); it('gets an error from streaming fetch upload when the renderer dies', async () => { let gotRequest: Function; const receivedRequest = new Promise<Request>(resolve => { gotRequest = resolve; }); protocol.handle('no-cors', (req) => { if (/fetch/.test(req.url)) gotRequest(req); return new Response(); }); defer(() => { protocol.unhandle('no-cors'); }); await contents.loadURL('no-cors://foo'); contents.executeJavaScript(` const stream = new ReadableStream({ async start(controller) { window.controller = controller // no GC }, }); fetch(location.href + '/fetch', {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()).catch(err => err) `); const req = await receivedRequest; contents.destroy(); // Undo .destroy() for the next test contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); await expect(req.body!.getReader().read()).to.eventually.be.rejectedWith('net::ERR_FAILED'); }); it('can bypass intercepeted protocol handlers', async () => { protocol.handle('http', () => new Response('custom')); defer(() => { protocol.unhandle('http'); }); const server = http.createServer((req, res) => { res.end('default'); }); defer(() => server.close()); const { url } = await listen(server); expect(await net.fetch(url, { bypassCustomProtocolHandlers: true }).then(r => r.text())).to.equal('default'); }); it('bypassing custom protocol handlers also bypasses new protocols', async () => { protocol.handle('app', () => new Response('custom')); defer(() => { protocol.unhandle('app'); }); await expect(net.fetch('app://foo', { bypassCustomProtocolHandlers: true })).to.be.rejectedWith('net::ERR_UNKNOWN_URL_SCHEME'); }); it('can forward to the original handler', async () => { protocol.handle('http', (req) => net.fetch(req, { bypassCustomProtocolHandlers: true })); defer(() => { protocol.unhandle('http'); }); const server = http.createServer((req, res) => { res.end('hello'); server.close(); }); const { url } = await listen(server); await contents.loadURL(url); expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('hello'); }); it('supports sniffing mime type', async () => { protocol.handle('http', async (req) => { return net.fetch(req, { bypassCustomProtocolHandlers: true }); }); defer(() => { protocol.unhandle('http'); }); const server = http.createServer((req, res) => { if (/html/.test(req.url ?? '')) { res.end('<!doctype html><body>hi'); } else { res.end('hi'); } }); const { url } = await listen(server); defer(() => server.close()); { await contents.loadURL(url); const doc = await contents.executeJavaScript('document.documentElement.outerHTML'); expect(doc).to.match(/white-space: pre-wrap/); } { await contents.loadURL(url + '?html'); const doc = await contents.executeJavaScript('document.documentElement.outerHTML'); expect(doc).to.equal('<html><head></head><body>hi</body></html>'); } }); // TODO(nornagon): this test doesn't pass on Linux currently, investigate. ifit(process.platform !== 'linux')('is fast', async () => { // 128 MB of spaces. const chunk = new Uint8Array(128 * 1024 * 1024); chunk.fill(' '.charCodeAt(0)); const server = http.createServer((req, res) => { // The sniffed mime type for the space-filled chunk will be // text/plain, which chews up all its performance in the renderer // trying to wrap lines. Setting content-type to text/html measures // something closer to just the raw cost of getting the bytes over // the wire. res.setHeader('content-type', 'text/html'); res.end(chunk); }); defer(() => server.close()); const { url } = await listen(server); const rawTime = await (async () => { await contents.loadURL(url); // warm const begin = Date.now(); await contents.loadURL(url); const end = Date.now(); return end - begin; })(); // Fetching through an intercepted handler should not be too much slower // than it would be if the protocol hadn't been intercepted. protocol.handle('http', async (req) => { return net.fetch(req, { bypassCustomProtocolHandlers: true }); }); defer(() => { protocol.unhandle('http'); }); const interceptedTime = await (async () => { const begin = Date.now(); await contents.loadURL(url); const end = Date.now(); return end - begin; })(); expect(interceptedTime).to.be.lessThan(rawTime * 1.5); }); }); });
closed
electron/electron
https://github.com/electron/electron
40,754
[Bug]: `net.fetch()` fails to forward html form submissions intercepted with `protocol.handle()`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version `25.9.8`, `26.6.2`, `28.0.0`, `29.0.0-alpha.3` ### What operating system are you using? Windows ### Operating System Version Windows 11 Enterprise 22H2 22621.2715 ### What arch are you using? x64 ### Last Known Working Electron version None--it doesn't work with any electron version shipping `protocol.handle()`. ### Expected Behavior It is [documented](https://www.electronjs.org/docs/latest/api/net#netfetchinput-init) that if one intercepts a protocol (e.g. given `s: Electron.Session` `s.protocol.handle('http', ...)`) one can forward a request to the built-in handler by passing `bypassCustomProtocolHandlers: true` in the `RequestInit` parameter. ### Actual Behavior However, if the request originates from a plain html `<form>` submission, the built-in handler fails with ``` Error: net::ERR_FAILED at SimpleURLLoaderWrapper.<anonymous> (node:electron/js2c/browser_init:2:49030) at SimpleURLLoaderWrapper.emit (node:events:517:28) (node:9824) electron: Failed to load URL: http://127.0.0.1:3000/ with error: ERR_UNEXPECTED ``` I observed that the form submission request contains an `origin: null` header and that removing said header from the request allows the request to succeed. The request also succeeds if no custom protocol handler is installed. ### Testcase Gist URL https://gist.github.com/BurningEnlightenment/83ef1268fa71ebe0fafd9dfa4cc2811f ### Additional Information The Testcase contains an html form which can be submitted to the included koa webserver.
https://github.com/electron/electron/issues/40754
https://github.com/electron/electron/pull/41052
d4413a8e53590b43d622ad9dce4259be89acbb8c
80906c0adb1e1b8103dcdfb8340c4b660b330c25
2023-12-13T11:02:56Z
c++
2024-02-16T19:29:29Z
lib/browser/api/protocol.ts
import { ProtocolRequest, session } from 'electron/main'; import { createReadStream } from 'fs'; import { Readable } from 'stream'; import { ReadableStream } from 'stream/web'; // Global protocol APIs. const { registerSchemesAsPrivileged, getStandardSchemes, Protocol } = process._linkedBinding('electron_browser_protocol'); const ERR_FAILED = -2; const ERR_UNEXPECTED = -9; const isBuiltInScheme = (scheme: string) => ['http', 'https', 'file'].includes(scheme); function makeStreamFromPipe (pipe: any): ReadableStream { const buf = new Uint8Array(1024 * 1024 /* 1 MB */); return new ReadableStream({ async pull (controller) { try { const rv = await pipe.read(buf); if (rv > 0) { controller.enqueue(buf.subarray(0, rv)); } else { controller.close(); } } catch (e) { controller.error(e); } } }); } function convertToRequestBody (uploadData: ProtocolRequest['uploadData']): RequestInit['body'] { if (!uploadData) return null; // Optimization: skip creating a stream if the request is just a single buffer. if (uploadData.length === 1 && (uploadData[0] as any).type === 'rawData') return uploadData[0].bytes; const chunks = [...uploadData] as any[]; // TODO: types are wrong let current: ReadableStreamDefaultReader | null = null; return new ReadableStream({ pull (controller) { if (current) { current.read().then(({ done, value }) => { controller.enqueue(value); if (done) current = null; }, (err) => { controller.error(err); }); } else { if (!chunks.length) { return controller.close(); } const chunk = chunks.shift()!; if (chunk.type === 'rawData') { controller.enqueue(chunk.bytes); } else if (chunk.type === 'file') { current = Readable.toWeb(createReadStream(chunk.filePath, { start: chunk.offset ?? 0, end: chunk.length >= 0 ? chunk.offset + chunk.length : undefined })).getReader(); this.pull!(controller); } else if (chunk.type === 'stream') { current = makeStreamFromPipe(chunk.body).getReader(); this.pull!(controller); } } } }) as RequestInit['body']; } // TODO(codebytere): Use Object.hasOwn() once we update to ECMAScript 2022. function validateResponse (res: Response) { if (!res || typeof res !== 'object') return false; if (res.type === 'error') return true; const exists = (key: string) => Object.hasOwn(res, key); if (exists('status') && typeof res.status !== 'number') return false; if (exists('statusText') && typeof res.statusText !== 'string') return false; if (exists('headers') && typeof res.headers !== 'object') return false; if (exists('body')) { if (typeof res.body !== 'object') return false; if (res.body !== null && !(res.body instanceof ReadableStream)) return false; } return true; } Protocol.prototype.handle = function (this: Electron.Protocol, scheme: string, handler: (req: Request) => Response | Promise<Response>) { const register = isBuiltInScheme(scheme) ? this.interceptProtocol : this.registerProtocol; const success = register.call(this, scheme, async (preq: ProtocolRequest, cb: any) => { try { const body = convertToRequestBody(preq.uploadData); const req = new Request(preq.url, { headers: preq.headers, method: preq.method, referrer: preq.referrer, body, duplex: body instanceof ReadableStream ? 'half' : undefined } as any); const res = await handler(req); if (!validateResponse(res)) { return cb({ error: ERR_UNEXPECTED }); } else if (res.type === 'error') { cb({ error: ERR_FAILED }); } else { cb({ data: res.body ? Readable.fromWeb(res.body as ReadableStream<ArrayBufferView>) : null, headers: res.headers ? Object.fromEntries(res.headers) : {}, statusCode: res.status, statusText: res.statusText, mimeType: (res as any).__original_resp?._responseHead?.mimeType }); } } catch (e) { console.error(e); cb({ error: ERR_UNEXPECTED }); } }); if (!success) throw new Error(`Failed to register protocol: ${scheme}`); }; Protocol.prototype.unhandle = function (this: Electron.Protocol, scheme: string) { const unregister = isBuiltInScheme(scheme) ? this.uninterceptProtocol : this.unregisterProtocol; if (!unregister.call(this, scheme)) { throw new Error(`Failed to unhandle protocol: ${scheme}`); } }; Protocol.prototype.isProtocolHandled = function (this: Electron.Protocol, scheme: string) { const isRegistered = isBuiltInScheme(scheme) ? this.isProtocolIntercepted : this.isProtocolRegistered; return isRegistered.call(this, scheme); }; const protocol = { registerSchemesAsPrivileged, getStandardSchemes, registerStringProtocol: (...args) => session.defaultSession.protocol.registerStringProtocol(...args), registerBufferProtocol: (...args) => session.defaultSession.protocol.registerBufferProtocol(...args), registerStreamProtocol: (...args) => session.defaultSession.protocol.registerStreamProtocol(...args), registerFileProtocol: (...args) => session.defaultSession.protocol.registerFileProtocol(...args), registerHttpProtocol: (...args) => session.defaultSession.protocol.registerHttpProtocol(...args), registerProtocol: (...args) => session.defaultSession.protocol.registerProtocol(...args), unregisterProtocol: (...args) => session.defaultSession.protocol.unregisterProtocol(...args), isProtocolRegistered: (...args) => session.defaultSession.protocol.isProtocolRegistered(...args), interceptStringProtocol: (...args) => session.defaultSession.protocol.interceptStringProtocol(...args), interceptBufferProtocol: (...args) => session.defaultSession.protocol.interceptBufferProtocol(...args), interceptStreamProtocol: (...args) => session.defaultSession.protocol.interceptStreamProtocol(...args), interceptFileProtocol: (...args) => session.defaultSession.protocol.interceptFileProtocol(...args), interceptHttpProtocol: (...args) => session.defaultSession.protocol.interceptHttpProtocol(...args), interceptProtocol: (...args) => session.defaultSession.protocol.interceptProtocol(...args), uninterceptProtocol: (...args) => session.defaultSession.protocol.uninterceptProtocol(...args), isProtocolIntercepted: (...args) => session.defaultSession.protocol.isProtocolIntercepted(...args), handle: (...args) => session.defaultSession.protocol.handle(...args), unhandle: (...args) => session.defaultSession.protocol.unhandle(...args), isProtocolHandled: (...args) => session.defaultSession.protocol.isProtocolHandled(...args) } as typeof Electron.protocol; export default protocol;
closed
electron/electron
https://github.com/electron/electron
40,754
[Bug]: `net.fetch()` fails to forward html form submissions intercepted with `protocol.handle()`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version `25.9.8`, `26.6.2`, `28.0.0`, `29.0.0-alpha.3` ### What operating system are you using? Windows ### Operating System Version Windows 11 Enterprise 22H2 22621.2715 ### What arch are you using? x64 ### Last Known Working Electron version None--it doesn't work with any electron version shipping `protocol.handle()`. ### Expected Behavior It is [documented](https://www.electronjs.org/docs/latest/api/net#netfetchinput-init) that if one intercepts a protocol (e.g. given `s: Electron.Session` `s.protocol.handle('http', ...)`) one can forward a request to the built-in handler by passing `bypassCustomProtocolHandlers: true` in the `RequestInit` parameter. ### Actual Behavior However, if the request originates from a plain html `<form>` submission, the built-in handler fails with ``` Error: net::ERR_FAILED at SimpleURLLoaderWrapper.<anonymous> (node:electron/js2c/browser_init:2:49030) at SimpleURLLoaderWrapper.emit (node:events:517:28) (node:9824) electron: Failed to load URL: http://127.0.0.1:3000/ with error: ERR_UNEXPECTED ``` I observed that the form submission request contains an `origin: null` header and that removing said header from the request allows the request to succeed. The request also succeeds if no custom protocol handler is installed. ### Testcase Gist URL https://gist.github.com/BurningEnlightenment/83ef1268fa71ebe0fafd9dfa4cc2811f ### Additional Information The Testcase contains an html form which can be submitted to the included koa webserver.
https://github.com/electron/electron/issues/40754
https://github.com/electron/electron/pull/41052
d4413a8e53590b43d622ad9dce4259be89acbb8c
80906c0adb1e1b8103dcdfb8340c4b660b330c25
2023-12-13T11:02:56Z
c++
2024-02-16T19:29:29Z
spec/api-protocol-spec.ts
import { expect } from 'chai'; import { v4 } from 'uuid'; import { protocol, webContents, WebContents, session, BrowserWindow, ipcMain, net } from 'electron/main'; import * as ChildProcess from 'node:child_process'; import * as path from 'node:path'; import * as url from 'node:url'; import * as http from 'node:http'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as stream from 'node:stream'; import { EventEmitter, once } from 'node:events'; import { closeAllWindows, closeWindow } from './lib/window-helpers'; import { WebmGenerator } from './lib/video-helpers'; import { listen, defer, ifit } from './lib/spec-helpers'; import { setTimeout } from 'node:timers/promises'; const fixturesPath = path.resolve(__dirname, 'fixtures'); const registerStringProtocol = protocol.registerStringProtocol; const registerBufferProtocol = protocol.registerBufferProtocol; const registerFileProtocol = protocol.registerFileProtocol; const registerStreamProtocol = protocol.registerStreamProtocol; const interceptStringProtocol = protocol.interceptStringProtocol; const interceptBufferProtocol = protocol.interceptBufferProtocol; const interceptHttpProtocol = protocol.interceptHttpProtocol; const interceptStreamProtocol = protocol.interceptStreamProtocol; const unregisterProtocol = protocol.unregisterProtocol; const uninterceptProtocol = protocol.uninterceptProtocol; const text = 'valar morghulis'; const protocolName = 'no-cors'; const postData = { name: 'post test', type: 'string' }; function getStream (chunkSize = text.length, data: Buffer | string = text) { // allowHalfOpen required, otherwise Readable.toWeb gets confused and thinks // the stream isn't done when the readable half ends. const body = new stream.PassThrough({ allowHalfOpen: false }); async function sendChunks () { await setTimeout(0); // the stream protocol API breaks if you send data immediately. let buf = Buffer.from(data as any); // nodejs typings are wrong, Buffer.from can take a Buffer for (;;) { body.push(buf.slice(0, chunkSize)); buf = buf.slice(chunkSize); if (!buf.length) { break; } // emulate some network delay await setTimeout(10); } body.push(null); } sendChunks(); return body; } function getWebStream (chunkSize = text.length, data: Buffer | string = text): ReadableStream<ArrayBufferView> { return stream.Readable.toWeb(getStream(chunkSize, data)) as ReadableStream<ArrayBufferView>; } // A promise that can be resolved externally. function deferPromise (): Promise<any> & {resolve: Function, reject: Function} { let promiseResolve: Function = null as unknown as Function; let promiseReject: Function = null as unknown as Function; const promise: any = new Promise((resolve, reject) => { promiseResolve = resolve; promiseReject = reject; }); promise.resolve = promiseResolve; promise.reject = promiseReject; return promise; } describe('protocol module', () => { let contents: WebContents; // NB. sandbox: true is used because it makes navigations much (~8x) faster. before(() => { contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); }); after(() => contents.destroy()); async function ajax (url: string, options = {}) { // Note that we need to do navigation every time after a protocol is // registered or unregistered, otherwise the new protocol won't be // recognized by current page when NetworkService is used. await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html')); return contents.executeJavaScript(`ajax("${url}", ${JSON.stringify(options)})`); } afterEach(() => { protocol.unregisterProtocol(protocolName); protocol.uninterceptProtocol('http'); }); describe('protocol.register(Any)Protocol', () => { it('fails when scheme is already registered', () => { expect(registerStringProtocol(protocolName, (req, cb) => cb(''))).to.equal(true); expect(registerBufferProtocol(protocolName, (req, cb) => cb(Buffer.from('')))).to.equal(false); }); it('does not crash when handler is called twice', async () => { registerStringProtocol(protocolName, (request, callback) => { try { callback(text); callback(''); } catch { // Ignore error } }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sends error when callback is called with nothing', async () => { registerBufferProtocol(protocolName, (req, cb: any) => cb()); await expect(ajax(protocolName + '://fake-host')).to.eventually.be.rejected(); }); it('does not crash when callback is called in next tick', async () => { registerStringProtocol(protocolName, (request, callback) => { setImmediate(() => callback(text)); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('can redirect to the same scheme', async () => { registerStringProtocol(protocolName, (request, callback) => { if (request.url === `${protocolName}://fake-host/redirect`) { callback({ statusCode: 302, headers: { Location: `${protocolName}://fake-host` } }); } else { expect(request.url).to.equal(`${protocolName}://fake-host`); callback('redirected'); } }); const r = await ajax(`${protocolName}://fake-host/redirect`); expect(r.data).to.equal('redirected'); }); }); describe('protocol.unregisterProtocol', () => { it('returns false when scheme does not exist', () => { expect(unregisterProtocol('not-exist')).to.equal(false); }); }); for (const [registerStringProtocol, name] of [ [protocol.registerStringProtocol, 'protocol.registerStringProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerStringProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { it('sends string as response', async () => { registerStringProtocol(protocolName, (request, callback) => callback(text)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sets Access-Control-Allow-Origin', async () => { registerStringProtocol(protocolName, (request, callback) => callback(text)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sends object as response', async () => { registerStringProtocol(protocolName, (request, callback) => { callback({ data: text, mimeType: 'text/html' }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending object other than string', async () => { const notAString = () => {}; registerStringProtocol(protocolName, (request, callback) => callback(notAString as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); } for (const [registerBufferProtocol, name] of [ [protocol.registerBufferProtocol, 'protocol.registerBufferProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerBufferProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { const buffer = Buffer.from(text); it('sends Buffer as response', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(buffer)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sets Access-Control-Allow-Origin', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(buffer)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sends object as response', async () => { registerBufferProtocol(protocolName, (request, callback) => { callback({ data: buffer, mimeType: 'text/html' }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); if (name !== 'protocol.registerProtocol') { it('fails when sending string', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(text as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); } }); } for (const [registerFileProtocol, name] of [ [protocol.registerFileProtocol, 'protocol.registerFileProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerFileProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { const filePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'file1'); const fileContent = fs.readFileSync(filePath); const normalPath = path.join(fixturesPath, 'pages', 'a.html'); const normalContent = fs.readFileSync(normalPath); afterEach(closeAllWindows); if (name === 'protocol.registerFileProtocol') { it('sends file path as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback(filePath)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); }); } it('sets Access-Control-Allow-Origin', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sets custom headers', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath, headers: { 'X-Great-Header': 'sogreat' } })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); expect(r.headers).to.have.property('x-great-header', 'sogreat'); }); it('can load iframes with custom protocols', async () => { registerFileProtocol('custom', (request, callback) => { const filename = request.url.substring(9); const p = path.join(__dirname, 'fixtures', 'pages', filename); callback({ path: p }); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const loaded = once(ipcMain, 'loaded-iframe-custom-protocol'); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'iframe-protocol.html')); await loaded; }); it('sends object as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); }); it('can send normal file', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: normalPath })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(normalContent)); }); it('fails when sending unexist-file', async () => { const fakeFilePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'not-exist'); registerFileProtocol(protocolName, (request, callback) => callback({ path: fakeFilePath })); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('fails when sending unsupported content', async () => { registerFileProtocol(protocolName, (request, callback) => callback(new Date() as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); } for (const [registerHttpProtocol, name] of [ [protocol.registerHttpProtocol, 'protocol.registerHttpProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerHttpProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { it('sends url as response', async () => { const server = http.createServer((req, res) => { expect(req.headers.accept).to.not.equal(''); res.end(text); server.close(); }); const { url } = await listen(server); registerHttpProtocol(protocolName, (request, callback) => callback({ url })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending invalid url', async () => { registerHttpProtocol(protocolName, (request, callback) => callback({ url: 'url' })); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('fails when sending unsupported content', async () => { registerHttpProtocol(protocolName, (request, callback) => callback(new Date() as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('works when target URL redirects', async () => { const server = http.createServer((req, res) => { if (req.url === '/serverRedirect') { res.statusCode = 301; res.setHeader('Location', `http://${req.rawHeaders[1]}`); res.end(); } else { res.end(text); } }); after(() => server.close()); const { port } = await listen(server); const url = `${protocolName}://fake-host`; const redirectURL = `http://127.0.0.1:${port}/serverRedirect`; registerHttpProtocol(protocolName, (request, callback) => callback({ url: redirectURL })); const r = await ajax(url); expect(r.data).to.equal(text); }); it('can access request headers', (done) => { protocol.registerHttpProtocol(protocolName, (request) => { try { expect(request).to.have.property('headers'); done(); } catch (e) { done(e); } }); ajax(protocolName + '://fake-host').catch(() => {}); }); }); } for (const [registerStreamProtocol, name] of [ [protocol.registerStreamProtocol, 'protocol.registerStreamProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerStreamProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { it('sends Stream as response', async () => { registerStreamProtocol(protocolName, (request, callback) => callback(getStream())); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sends object as response', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream() })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.status).to.equal(200); }); it('sends custom response headers', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream(3), headers: { 'x-electron': ['a', 'b'] } })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.status).to.equal(200); expect(r.headers).to.have.property('x-electron', 'a, b'); }); it('sends custom status code', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ statusCode: 204, data: null as any })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.be.empty('data'); expect(r.status).to.equal(204); }); it('receives request headers', async () => { registerStreamProtocol(protocolName, (request, callback) => { callback({ headers: { 'content-type': 'application/json' }, data: getStream(5, JSON.stringify(Object.assign({}, request.headers))) }); }); const r = await ajax(protocolName + '://fake-host', { headers: { 'x-return-headers': 'yes' } }); expect(JSON.parse(r.data)['x-return-headers']).to.equal('yes'); }); it('returns response multiple response headers with the same name', async () => { registerStreamProtocol(protocolName, (request, callback) => { callback({ headers: { header1: ['value1', 'value2'], header2: 'value3' }, data: getStream() }); }); const r = await ajax(protocolName + '://fake-host'); // SUBTLE: when the response headers have multiple values it // separates values by ", ". When the response headers are incorrectly // converting an array to a string it separates values by ",". expect(r.headers).to.have.property('header1', 'value1, value2'); expect(r.headers).to.have.property('header2', 'value3'); }); it('can handle large responses', async () => { const data = Buffer.alloc(128 * 1024); registerStreamProtocol(protocolName, (request, callback) => { callback(getStream(data.length, data)); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.have.lengthOf(data.length); }); it('can handle a stream completing while writing', async () => { function dumbPassthrough () { return new stream.Transform({ async transform (chunk, encoding, cb) { cb(null, chunk); } }); } registerStreamProtocol(protocolName, (request, callback) => { callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: getStream(1024 * 1024, Buffer.alloc(1024 * 1024 * 2)).pipe(dumbPassthrough()) }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.have.lengthOf(1024 * 1024 * 2); }); it('can handle next-tick scheduling during read calls', async () => { const events = new EventEmitter(); function createStream () { const buffers = [ Buffer.alloc(65536), Buffer.alloc(65537), Buffer.alloc(39156) ]; const e = new stream.Readable({ highWaterMark: 0 }); e.push(buffers.shift()); e._read = function () { process.nextTick(() => this.push(buffers.shift() || null)); }; e.on('end', function () { events.emit('end'); }); return e; } registerStreamProtocol(protocolName, (request, callback) => { callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: createStream() }); }); const hasEndedPromise = once(events, 'end'); ajax(protocolName + '://fake-host').catch(() => {}); await hasEndedPromise; }); it('destroys response streams when aborted before completion', async () => { const events = new EventEmitter(); registerStreamProtocol(protocolName, (request, callback) => { const responseStream = new stream.PassThrough(); responseStream.push('data\r\n'); responseStream.on('close', () => { events.emit('close'); }); callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: responseStream }); events.emit('respond'); }); const hasRespondedPromise = once(events, 'respond'); const hasClosedPromise = once(events, 'close'); ajax(protocolName + '://fake-host').catch(() => {}); await hasRespondedPromise; await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html')); await hasClosedPromise; }); }); } describe('protocol.isProtocolRegistered', () => { it('returns false when scheme is not registered', () => { const result = protocol.isProtocolRegistered('no-exist'); expect(result).to.be.false('no-exist: is handled'); }); it('returns true for custom protocol', () => { registerStringProtocol(protocolName, (request, callback) => callback('')); const result = protocol.isProtocolRegistered(protocolName); expect(result).to.be.true('custom protocol is handled'); }); }); describe('protocol.isProtocolIntercepted', () => { it('returns true for intercepted protocol', () => { interceptStringProtocol('http', (request, callback) => callback('')); const result = protocol.isProtocolIntercepted('http'); expect(result).to.be.true('intercepted protocol is handled'); }); }); describe('protocol.intercept(Any)Protocol', () => { it('returns false when scheme is already intercepted', () => { expect(protocol.interceptStringProtocol('http', (request, callback) => callback(''))).to.equal(true); expect(protocol.interceptBufferProtocol('http', (request, callback) => callback(Buffer.from('')))).to.equal(false); }); it('does not crash when handler is called twice', async () => { interceptStringProtocol('http', (request, callback) => { try { callback(text); callback(''); } catch { // Ignore error } }); const r = await ajax('http://fake-host'); expect(r.data).to.be.equal(text); }); it('sends error when callback is called with nothing', async () => { interceptStringProtocol('http', (request, callback: any) => callback()); await expect(ajax('http://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.interceptStringProtocol', () => { it('can intercept http protocol', async () => { interceptStringProtocol('http', (request, callback) => callback(text)); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can set content-type', async () => { interceptStringProtocol('http', (request, callback) => { callback({ mimeType: 'application/json', data: '{"value": 1}' }); }); const r = await ajax('http://fake-host'); expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1); }); it('can set content-type with charset', async () => { interceptStringProtocol('http', (request, callback) => { callback({ mimeType: 'application/json; charset=UTF-8', data: '{"value": 1}' }); }); const r = await ajax('http://fake-host'); expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1); }); it('can receive post data', async () => { interceptStringProtocol('http', (request, callback) => { const uploadData = request.uploadData![0].bytes.toString(); callback({ data: uploadData }); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); }); describe('protocol.interceptBufferProtocol', () => { it('can intercept http protocol', async () => { interceptBufferProtocol('http', (request, callback) => callback(Buffer.from(text))); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can receive post data', async () => { interceptBufferProtocol('http', (request, callback) => { const uploadData = request.uploadData![0].bytes; callback(uploadData); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect(qs.parse(r.data)).to.deep.equal({ name: 'post test', type: 'string' }); }); }); describe('protocol.interceptHttpProtocol', () => { // FIXME(zcbenz): This test was passing because the test itself was wrong, // I don't know whether it ever passed before and we should take a look at // it in future. xit('can send POST request', async () => { const server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); req.on('end', () => { res.end(body); }); server.close(); }); after(() => server.close()); const { url } = await listen(server); interceptHttpProtocol('http', (request, callback) => { const data: Electron.ProtocolResponse = { url: url, method: 'POST', uploadData: { contentType: 'application/x-www-form-urlencoded', data: request.uploadData![0].bytes }, session: undefined }; callback(data); }); const r = await ajax('http://fake-host', { type: 'POST', data: postData }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); it('can use custom session', async () => { const customSession = session.fromPartition('custom-ses', { cache: false }); customSession.webRequest.onBeforeRequest((details, callback) => { expect(details.url).to.equal('http://fake-host/'); callback({ cancel: true }); }); after(() => customSession.webRequest.onBeforeRequest(null)); interceptHttpProtocol('http', (request, callback) => { callback({ url: request.url, session: customSession }); }); await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error); }); it('can access request headers', (done) => { protocol.interceptHttpProtocol('http', (request) => { try { expect(request).to.have.property('headers'); done(); } catch (e) { done(e); } }); ajax('http://fake-host').catch(() => {}); }); }); describe('protocol.interceptStreamProtocol', () => { it('can intercept http protocol', async () => { interceptStreamProtocol('http', (request, callback) => callback(getStream())); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can receive post data', async () => { interceptStreamProtocol('http', (request, callback) => { callback(getStream(3, request.uploadData![0].bytes.toString())); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); it('can execute redirects', async () => { interceptStreamProtocol('http', (request, callback) => { if (request.url.indexOf('http://fake-host') === 0) { setTimeout(300).then(() => { callback({ data: '', statusCode: 302, headers: { Location: 'http://fake-redirect' } }); }); } else { expect(request.url.indexOf('http://fake-redirect')).to.equal(0); callback(getStream(1, 'redirect')); } }); const r = await ajax('http://fake-host'); expect(r.data).to.equal('redirect'); }); it('should discard post data after redirection', async () => { interceptStreamProtocol('http', (request, callback) => { if (request.url.indexOf('http://fake-host') === 0) { setTimeout(300).then(() => { callback({ statusCode: 302, headers: { Location: 'http://fake-redirect' } }); }); } else { expect(request.url.indexOf('http://fake-redirect')).to.equal(0); callback(getStream(3, request.method)); } }); const r = await ajax('http://fake-host', { type: 'POST', data: postData }); expect(r.data).to.equal('GET'); }); }); describe('protocol.uninterceptProtocol', () => { it('returns false when scheme does not exist', () => { expect(uninterceptProtocol('not-exist')).to.equal(false); }); it('returns false when scheme is not intercepted', () => { expect(uninterceptProtocol('http')).to.equal(false); }); }); describe('protocol.registerSchemeAsPrivileged', () => { it('does not crash on exit', async () => { const appPath = path.join(__dirname, 'fixtures', 'api', 'custom-protocol-shutdown.js'); const appProcess = ChildProcess.spawn(process.execPath, ['--enable-logging', appPath]); let stdout = ''; let stderr = ''; appProcess.stdout.on('data', data => { process.stdout.write(data); stdout += data; }); appProcess.stderr.on('data', data => { process.stderr.write(data); stderr += data; }); const [code] = await once(appProcess, 'exit'); if (code !== 0) { console.log('Exit code : ', code); console.log('stdout : ', stdout); console.log('stderr : ', stderr); } expect(code).to.equal(0); expect(stdout).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED'); expect(stderr).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED'); }); }); describe('protocol.registerSchemesAsPrivileged allowServiceWorkers', () => { protocol.registerStringProtocol(serviceWorkerScheme, (request, cb) => { if (request.url.endsWith('.js')) { cb({ mimeType: 'text/javascript', charset: 'utf-8', data: 'console.log("Loaded")' }); } else { cb({ mimeType: 'text/html', charset: 'utf-8', data: '<!DOCTYPE html>' }); } }); after(() => protocol.unregisterProtocol(serviceWorkerScheme)); it('should fail when registering invalid service worker', async () => { await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`); await expect(contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.notjs', {scope: './'})`)).to.be.rejected(); }); it('should be able to register service worker for custom scheme', async () => { await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`); await contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.js', {scope: './'})`); }); }); describe('protocol.registerSchemesAsPrivileged standard', () => { const origin = `${standardScheme}://fake-host`; const imageURL = `${origin}/test.png`; const filePath = path.join(fixturesPath, 'pages', 'b.html'); const fileContent = '<img src="/test.png" />'; let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); unregisterProtocol(standardScheme); w = null as unknown as BrowserWindow; }); it('resolves relative resources', async () => { registerFileProtocol(standardScheme, (request, callback) => { if (request.url === imageURL) { callback(''); } else { callback(filePath); } }); await w.loadURL(origin); }); it('resolves absolute resources', async () => { registerStringProtocol(standardScheme, (request, callback) => { if (request.url === imageURL) { callback(''); } else { callback({ data: fileContent, mimeType: 'text/html' }); } }); await w.loadURL(origin); }); it('can have fetch working in it', async () => { const requestReceived = deferPromise(); const server = http.createServer((req, res) => { res.end(); server.close(); requestReceived.resolve(); }); const { url } = await listen(server); const content = `<script>fetch(${JSON.stringify(url)})</script>`; registerStringProtocol(standardScheme, (request, callback) => callback({ data: content, mimeType: 'text/html' })); await w.loadURL(origin); await requestReceived; }); it('can access files through the FileSystem API', (done) => { const filePath = path.join(fixturesPath, 'pages', 'filesystem.html'); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); w.loadURL(origin); ipcMain.once('file-system-error', (event, err) => done(err)); ipcMain.once('file-system-write-end', () => done()); }); it('registers secure, when {secure: true}', (done) => { const filePath = path.join(fixturesPath, 'pages', 'cache-storage.html'); ipcMain.once('success', () => done()); ipcMain.once('failure', (event, err) => done(err)); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); w.loadURL(origin); }); }); describe('protocol.registerSchemesAsPrivileged cors-fetch', function () { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; for (const scheme of [standardScheme, 'cors', 'no-cors', 'no-fetch']) { protocol.unregisterProtocol(scheme); } }); it('supports fetch api by default', async () => { const url = `file://${fixturesPath}/assets/logo.png`; await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const ok = await w.webContents.executeJavaScript(`fetch(${JSON.stringify(url)}).then(r => r.ok)`); expect(ok).to.be.true('response ok'); }); it('allows CORS requests by default', async () => { await allowsCORSRequests('cors', 200, new RegExp(''), () => { const { ipcRenderer } = require('electron'); fetch('cors://myhost').then(function (response) { ipcRenderer.send('response', response.status); }).catch(function () { ipcRenderer.send('response', 'failed'); }); }); }); // DISABLED-FIXME: Figure out why this test is failing it('disallows CORS and fetch requests when only supportFetchAPI is specified', async () => { await allowsCORSRequests('no-cors', ['failed xhr', 'failed fetch'], /has been blocked by CORS policy/, () => { const { ipcRenderer } = require('electron'); Promise.all([ new Promise(resolve => { const req = new XMLHttpRequest(); req.onload = () => resolve('loaded xhr'); req.onerror = () => resolve('failed xhr'); req.open('GET', 'no-cors://myhost'); req.send(); }), fetch('no-cors://myhost') .then(() => 'loaded fetch') .catch(() => 'failed fetch') ]).then(([xhr, fetch]) => { ipcRenderer.send('response', [xhr, fetch]); }); }); }); it('allows CORS, but disallows fetch requests, when specified', async () => { await allowsCORSRequests('no-fetch', ['loaded xhr', 'failed fetch'], /Fetch API cannot load/, () => { const { ipcRenderer } = require('electron'); Promise.all([ new Promise(resolve => { const req = new XMLHttpRequest(); req.onload = () => resolve('loaded xhr'); req.onerror = () => resolve('failed xhr'); req.open('GET', 'no-fetch://myhost'); req.send(); }), fetch('no-fetch://myhost') .then(() => 'loaded fetch') .catch(() => 'failed fetch') ]).then(([xhr, fetch]) => { ipcRenderer.send('response', [xhr, fetch]); }); }); }); async function allowsCORSRequests (corsScheme: string, expected: any, expectedConsole: RegExp, content: Function) { registerStringProtocol(standardScheme, (request, callback) => { callback({ data: `<script>(${content})()</script>`, mimeType: 'text/html' }); }); registerStringProtocol(corsScheme, (request, callback) => { callback(''); }); const newContents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true, contextIsolation: false }); const consoleMessages: string[] = []; newContents.on('console-message', (e, level, message) => consoleMessages.push(message)); try { newContents.loadURL(standardScheme + '://fake-host'); const [, response] = await once(ipcMain, 'response'); expect(response).to.deep.equal(expected); expect(consoleMessages.join('\n')).to.match(expectedConsole); } finally { // This is called in a timeout to avoid a crash that happens when // calling destroy() in a microtask. setTimeout().then(() => { newContents.destroy(); }); } } }); describe('protocol.registerSchemesAsPrivileged stream', async function () { const pagePath = path.join(fixturesPath, 'pages', 'video.html'); const videoSourceImagePath = path.join(fixturesPath, 'video-source-image.webp'); const videoPath = path.join(fixturesPath, 'video.webm'); let w: BrowserWindow; before(async () => { // generate test video const imageBase64 = await fs.promises.readFile(videoSourceImagePath, 'base64'); const imageDataUrl = `data:image/webp;base64,${imageBase64}`; const encoder = new WebmGenerator(15); for (let i = 0; i < 30; i++) { encoder.add(imageDataUrl); } await new Promise((resolve, reject) => { encoder.compile((output:Uint8Array) => { fs.promises.writeFile(videoPath, output).then(resolve, reject); }); }); }); after(async () => { await fs.promises.unlink(videoPath); }); beforeEach(async function () { w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) { this.skip(); } }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; await protocol.unregisterProtocol(standardScheme); await protocol.unregisterProtocol('stream'); }); it('successfully plays videos when content is buffered (stream: false)', async () => { await streamsResponses(standardScheme, 'play'); }); it('successfully plays videos when streaming content (stream: true)', async () => { await streamsResponses('stream', 'play'); }); async function streamsResponses (testingScheme: string, expected: any) { const protocolHandler = (request: any, callback: Function) => { if (request.url.includes('/video.webm')) { const stat = fs.statSync(videoPath); const fileSize = stat.size; const range = request.headers.Range; if (range) { const parts = range.replace(/bytes=/, '').split('-'); const start = parseInt(parts[0], 10); const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1; const chunksize = (end - start) + 1; const headers = { 'Content-Range': `bytes ${start}-${end}/${fileSize}`, 'Accept-Ranges': 'bytes', 'Content-Length': String(chunksize), 'Content-Type': 'video/webm' }; callback({ statusCode: 206, headers, data: fs.createReadStream(videoPath, { start, end }) }); } else { callback({ statusCode: 200, headers: { 'Content-Length': String(fileSize), 'Content-Type': 'video/webm' }, data: fs.createReadStream(videoPath) }); } } else { callback({ data: fs.createReadStream(pagePath), headers: { 'Content-Type': 'text/html' }, statusCode: 200 }); } }; await registerStreamProtocol(standardScheme, protocolHandler); await registerStreamProtocol('stream', protocolHandler); const newContents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true, contextIsolation: false }); try { newContents.loadURL(testingScheme + '://fake-host'); const [, response] = await once(ipcMain, 'result'); expect(response).to.deep.equal(expected); } finally { // This is called in a timeout to avoid a crash that happens when // calling destroy() in a microtask. setTimeout().then(() => { newContents.destroy(); }); } } }); describe('protocol.registerSchemesAsPrivileged codeCache', function () { const temp = require('temp').track(); const appPath = path.join(fixturesPath, 'apps', 'refresh-page'); let w: BrowserWindow; let codeCachePath: string; beforeEach(async () => { w = new BrowserWindow({ show: false }); codeCachePath = temp.path(); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('code cache in custom protocol is disabled by default', async () => { ChildProcess.spawnSync(process.execPath, [appPath, 'false', codeCachePath]); expect(fs.readdirSync(path.join(codeCachePath, 'js')).length).to.equal(2); }); it('codeCache:true enables codeCache in custom protocol', async () => { ChildProcess.spawnSync(process.execPath, [appPath, 'true', codeCachePath]); expect(fs.readdirSync(path.join(codeCachePath, 'js')).length).to.above(2); }); }); describe('handle', () => { afterEach(closeAllWindows); it('receives requests to a custom scheme', async () => { protocol.handle('test-scheme', (req) => new Response('hello ' + req.url)); defer(() => { protocol.unhandle('test-scheme'); }); const resp = await net.fetch('test-scheme://foo'); expect(resp.status).to.equal(200); }); it('can be unhandled', async () => { protocol.handle('test-scheme', (req) => new Response('hello ' + req.url)); defer(() => { try { // In case of failure, make sure we unhandle. But we should succeed // :) protocol.unhandle('test-scheme'); } catch { /* ignore */ } }); const resp1 = await net.fetch('test-scheme://foo'); expect(resp1.status).to.equal(200); protocol.unhandle('test-scheme'); await expect(net.fetch('test-scheme://foo')).to.eventually.be.rejectedWith(/ERR_UNKNOWN_URL_SCHEME/); }); it('receives requests to the existing https scheme', async () => { protocol.handle('https', (req) => new Response('hello ' + req.url)); defer(() => { protocol.unhandle('https'); }); const body = await net.fetch('https://foo').then(r => r.text()); expect(body).to.equal('hello https://foo/'); }); it('receives requests to the existing file scheme', (done) => { const filePath = path.join(__dirname, 'fixtures', 'pages', 'a.html'); protocol.handle('file', (req) => { let file; if (process.platform === 'win32') { file = `file:///${filePath.replaceAll('\\', '/')}`; } else { file = `file://${filePath}`; } if (req.url === file) done(); return new Response(req.url); }); defer(() => { protocol.unhandle('file'); }); const w = new BrowserWindow(); w.loadFile(filePath); }); it('receives requests to an existing scheme when navigating', async () => { protocol.handle('https', (req) => new Response('hello ' + req.url)); defer(() => { protocol.unhandle('https'); }); const w = new BrowserWindow({ show: false }); await w.loadURL('https://localhost'); expect(await w.webContents.executeJavaScript('document.body.textContent')).to.equal('hello https://localhost/'); }); it('can send buffer body', async () => { protocol.handle('test-scheme', (req) => new Response(Buffer.from('hello ' + req.url))); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body).to.equal('hello test-scheme://foo'); }); it('can send stream body', async () => { protocol.handle('test-scheme', () => new Response(getWebStream())); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body).to.equal(text); }); it('accepts urls with no hostname in non-standard schemes', async () => { protocol.handle('test-scheme', (req) => new Response(req.url)); defer(() => { protocol.unhandle('test-scheme'); }); { const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body).to.equal('test-scheme://foo'); } { const body = await net.fetch('test-scheme:///foo').then(r => r.text()); expect(body).to.equal('test-scheme:///foo'); } { const body = await net.fetch('test-scheme://').then(r => r.text()); expect(body).to.equal('test-scheme://'); } }); it('accepts urls with a port-like component in non-standard schemes', async () => { protocol.handle('test-scheme', (req) => new Response(req.url)); defer(() => { protocol.unhandle('test-scheme'); }); { const body = await net.fetch('test-scheme://foo:30').then(r => r.text()); expect(body).to.equal('test-scheme://foo:30'); } }); it('normalizes urls in standard schemes', async () => { // NB. 'app' is registered as a standard scheme in test setup. protocol.handle('app', (req) => new Response(req.url)); defer(() => { protocol.unhandle('app'); }); { const body = await net.fetch('app://foo').then(r => r.text()); expect(body).to.equal('app://foo/'); } { const body = await net.fetch('app:///foo').then(r => r.text()); expect(body).to.equal('app://foo/'); } // NB. 'app' is registered with the default scheme type of 'host'. { const body = await net.fetch('app://foo:1234').then(r => r.text()); expect(body).to.equal('app://foo/'); } await expect(net.fetch('app://')).to.be.rejectedWith('Invalid URL'); }); it('fails on URLs with a username', async () => { // NB. 'app' is registered as a standard scheme in test setup. protocol.handle('http', (req) => new Response(req.url)); defer(() => { protocol.unhandle('http'); }); await expect(contents.loadURL('http://x@foo:1234')).to.be.rejectedWith(/ERR_UNEXPECTED/); }); it('normalizes http urls', async () => { protocol.handle('http', (req) => new Response(req.url)); defer(() => { protocol.unhandle('http'); }); { const body = await net.fetch('http://foo').then(r => r.text()); expect(body).to.equal('http://foo/'); } }); it('can send errors', async () => { protocol.handle('test-scheme', () => Response.error()); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.eventually.be.rejectedWith('net::ERR_FAILED'); }); it('handles invalid protocol response status', async () => { protocol.handle('test-scheme', () => { return { status: [] } as any; }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles invalid protocol response statusText', async () => { protocol.handle('test-scheme', () => { return { statusText: false } as any; }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles invalid protocol response header parameters', async () => { protocol.handle('test-scheme', () => { return { headers: false } as any; }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles invalid protocol response body parameters', async () => { protocol.handle('test-scheme', () => { return { body: false } as any; }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles a synchronous error in the handler', async () => { protocol.handle('test-scheme', () => { throw new Error('test'); }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles an asynchronous error in the handler', async () => { protocol.handle('test-scheme', () => Promise.reject(new Error('rejected promise'))); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('correctly sets statusCode', async () => { protocol.handle('test-scheme', () => new Response(null, { status: 201 })); defer(() => { protocol.unhandle('test-scheme'); }); const resp = await net.fetch('test-scheme://foo'); expect(resp.status).to.equal(201); }); it('correctly sets content-type and charset', async () => { protocol.handle('test-scheme', () => new Response(null, { headers: { 'content-type': 'text/html; charset=testcharset' } })); defer(() => { protocol.unhandle('test-scheme'); }); const resp = await net.fetch('test-scheme://foo'); expect(resp.headers.get('content-type')).to.equal('text/html; charset=testcharset'); }); it('can forward to http', async () => { const server = http.createServer((req, res) => { res.end(text); }); defer(() => { server.close(); }); const { url } = await listen(server); protocol.handle('test-scheme', () => net.fetch(url)); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body).to.equal(text); }); it('can forward an http request with headers', async () => { const server = http.createServer((req, res) => { res.setHeader('foo', 'bar'); res.end(text); }); defer(() => { server.close(); }); const { url } = await listen(server); protocol.handle('test-scheme', (req) => net.fetch(url, { headers: req.headers })); defer(() => { protocol.unhandle('test-scheme'); }); const resp = await net.fetch('test-scheme://foo'); expect(resp.headers.get('foo')).to.equal('bar'); }); it('can forward to file', async () => { protocol.handle('test-scheme', () => net.fetch(url.pathToFileURL(path.join(__dirname, 'fixtures', 'hello.txt')).toString())); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body.trimEnd()).to.equal('hello world'); }); it('can receive simple request body', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo', { method: 'POST', body: 'foobar' }).then(r => r.text()); expect(body).to.equal('foobar'); }); it('can receive stream request body', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo', { method: 'POST', body: getWebStream(), duplex: 'half' // https://github.com/microsoft/TypeScript/issues/53157 } as any).then(r => r.text()); expect(body).to.equal(text); }); it('can receive multi-part postData from loadURL', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); await contents.loadURL('test-scheme://foo', { postData: [{ type: 'rawData', bytes: Buffer.from('a') }, { type: 'rawData', bytes: Buffer.from('b') }] }); expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('ab'); }); it('can receive file postData from loadURL', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); await contents.loadURL('test-scheme://foo', { postData: [{ type: 'file', filePath: path.join(fixturesPath, 'hello.txt'), length: 'hello world\n'.length, offset: 0, modificationTime: 0 }] }); expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('hello world\n'); }); it('can receive file postData from a form', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); await contents.loadURL('data:text/html,<form action="test-scheme://foo" method=POST enctype="multipart/form-data"><input name=foo type=file>'); const { debugger: dbg } = contents; dbg.attach(); const { root } = await dbg.sendCommand('DOM.getDocument'); const { nodeId: fileInputNodeId } = await dbg.sendCommand('DOM.querySelector', { nodeId: root.nodeId, selector: 'input' }); await dbg.sendCommand('DOM.setFileInputFiles', { nodeId: fileInputNodeId, files: [ path.join(fixturesPath, 'hello.txt') ] }); const navigated = once(contents, 'did-finish-load'); await contents.executeJavaScript('document.querySelector("form").submit()'); await navigated; expect(await contents.executeJavaScript('document.documentElement.textContent')).to.match(/------WebKitFormBoundary.*\nContent-Disposition: form-data; name="foo"; filename="hello.txt"\nContent-Type: text\/plain\n\nhello world\n\n------WebKitFormBoundary.*--\n/); }); it('can receive streaming fetch upload', async () => { protocol.handle('no-cors', (req) => new Response(req.body)); defer(() => { protocol.unhandle('no-cors'); }); await contents.loadURL('no-cors://foo'); const fetchBodyResult = await contents.executeJavaScript(` const stream = new ReadableStream({ async start(controller) { controller.enqueue('hello world'); controller.close(); }, }).pipeThrough(new TextEncoderStream()); fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()) `); expect(fetchBodyResult).to.equal('hello world'); }); it('can receive streaming fetch upload when a webRequest handler is present', async () => { session.defaultSession.webRequest.onBeforeRequest((details, cb) => { console.log('webRequest', details.url, details.method); cb({}); }); defer(() => { session.defaultSession.webRequest.onBeforeRequest(null); }); protocol.handle('no-cors', (req) => { console.log('handle', req.url, req.method); return new Response(req.body); }); defer(() => { protocol.unhandle('no-cors'); }); await contents.loadURL('no-cors://foo'); const fetchBodyResult = await contents.executeJavaScript(` const stream = new ReadableStream({ async start(controller) { controller.enqueue('hello world'); controller.close(); }, }).pipeThrough(new TextEncoderStream()); fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()) `); expect(fetchBodyResult).to.equal('hello world'); }); it('can receive an error from streaming fetch upload', async () => { protocol.handle('no-cors', (req) => new Response(req.body)); defer(() => { protocol.unhandle('no-cors'); }); await contents.loadURL('no-cors://foo'); const fetchBodyResult = await contents.executeJavaScript(` const stream = new ReadableStream({ async start(controller) { controller.error('test') }, }); fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()).catch(err => err) `); expect(fetchBodyResult).to.be.an.instanceOf(Error); }); it('gets an error from streaming fetch upload when the renderer dies', async () => { let gotRequest: Function; const receivedRequest = new Promise<Request>(resolve => { gotRequest = resolve; }); protocol.handle('no-cors', (req) => { if (/fetch/.test(req.url)) gotRequest(req); return new Response(); }); defer(() => { protocol.unhandle('no-cors'); }); await contents.loadURL('no-cors://foo'); contents.executeJavaScript(` const stream = new ReadableStream({ async start(controller) { window.controller = controller // no GC }, }); fetch(location.href + '/fetch', {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()).catch(err => err) `); const req = await receivedRequest; contents.destroy(); // Undo .destroy() for the next test contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); await expect(req.body!.getReader().read()).to.eventually.be.rejectedWith('net::ERR_FAILED'); }); it('can bypass intercepeted protocol handlers', async () => { protocol.handle('http', () => new Response('custom')); defer(() => { protocol.unhandle('http'); }); const server = http.createServer((req, res) => { res.end('default'); }); defer(() => server.close()); const { url } = await listen(server); expect(await net.fetch(url, { bypassCustomProtocolHandlers: true }).then(r => r.text())).to.equal('default'); }); it('bypassing custom protocol handlers also bypasses new protocols', async () => { protocol.handle('app', () => new Response('custom')); defer(() => { protocol.unhandle('app'); }); await expect(net.fetch('app://foo', { bypassCustomProtocolHandlers: true })).to.be.rejectedWith('net::ERR_UNKNOWN_URL_SCHEME'); }); it('can forward to the original handler', async () => { protocol.handle('http', (req) => net.fetch(req, { bypassCustomProtocolHandlers: true })); defer(() => { protocol.unhandle('http'); }); const server = http.createServer((req, res) => { res.end('hello'); server.close(); }); const { url } = await listen(server); await contents.loadURL(url); expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('hello'); }); it('supports sniffing mime type', async () => { protocol.handle('http', async (req) => { return net.fetch(req, { bypassCustomProtocolHandlers: true }); }); defer(() => { protocol.unhandle('http'); }); const server = http.createServer((req, res) => { if (/html/.test(req.url ?? '')) { res.end('<!doctype html><body>hi'); } else { res.end('hi'); } }); const { url } = await listen(server); defer(() => server.close()); { await contents.loadURL(url); const doc = await contents.executeJavaScript('document.documentElement.outerHTML'); expect(doc).to.match(/white-space: pre-wrap/); } { await contents.loadURL(url + '?html'); const doc = await contents.executeJavaScript('document.documentElement.outerHTML'); expect(doc).to.equal('<html><head></head><body>hi</body></html>'); } }); // TODO(nornagon): this test doesn't pass on Linux currently, investigate. ifit(process.platform !== 'linux')('is fast', async () => { // 128 MB of spaces. const chunk = new Uint8Array(128 * 1024 * 1024); chunk.fill(' '.charCodeAt(0)); const server = http.createServer((req, res) => { // The sniffed mime type for the space-filled chunk will be // text/plain, which chews up all its performance in the renderer // trying to wrap lines. Setting content-type to text/html measures // something closer to just the raw cost of getting the bytes over // the wire. res.setHeader('content-type', 'text/html'); res.end(chunk); }); defer(() => server.close()); const { url } = await listen(server); const rawTime = await (async () => { await contents.loadURL(url); // warm const begin = Date.now(); await contents.loadURL(url); const end = Date.now(); return end - begin; })(); // Fetching through an intercepted handler should not be too much slower // than it would be if the protocol hadn't been intercepted. protocol.handle('http', async (req) => { return net.fetch(req, { bypassCustomProtocolHandlers: true }); }); defer(() => { protocol.unhandle('http'); }); const interceptedTime = await (async () => { const begin = Date.now(); await contents.loadURL(url); const end = Date.now(); return end - begin; })(); expect(interceptedTime).to.be.lessThan(rawTime * 1.5); }); }); });