Compare commits

...

27 Commits

Author SHA1 Message Date
Sam Maddock
cc6164fe27 feat: ServiceWorkerMain (#45341) 2025-01-31 12:40:19 -05:00
trop[bot]
59e4794ff5 build: fix slack-github-action for backports (#45403)
build: fix slack-github-action for backports

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2025-01-31 09:53:50 -05:00
trop[bot]
fa03b92f7e feat: contextBridge.executeInMainWorld (#45330)
Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Samuel Maddock <samuel.maddock@gmail.com>
2025-01-31 09:50:44 -05:00
trop[bot]
9d696ceffe feat: redesign preload APIs (#45329)
* feat: redesign preload APIs

Co-authored-by: Samuel Maddock <samuel.maddock@gmail.com>

* docs: remove service-worker mentions for now

Co-authored-by: Samuel Maddock <samuel.maddock@gmail.com>

* fix lint

Co-authored-by: Samuel Maddock <samuel.maddock@gmail.com>

* remove service-worker ipc code

Co-authored-by: Samuel Maddock <samuel.maddock@gmail.com>

* add filename

Co-authored-by: Samuel Maddock <samuel.maddock@gmail.com>

* fix: web preferences preload not included

Co-authored-by: Samuel Maddock <samuel.maddock@gmail.com>

* fix: missing common init

Co-authored-by: Samuel Maddock <samuel.maddock@gmail.com>

* fix: preload bundle script error

Co-authored-by: Samuel Maddock <samuel.maddock@gmail.com>

---------

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Samuel Maddock <samuel.maddock@gmail.com>
2025-01-31 09:46:17 -05:00
trop[bot]
e9b3e4cc91 fix: multiple directory selection on Linux (#45394)
Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2025-01-31 09:38:44 +01:00
trop[bot]
895bc51272 build: fixup concurrent builds on protected branches (#45383)
Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org>
2025-01-30 10:36:24 +01:00
Keeley Hammond
ef1ad85082 fix: crash in gin::wrappable::secondweakcallback (#45378)
fix: crash in gin::wrappable::secondweakcallback (#45368)
2025-01-29 15:04:08 -08:00
trop[bot]
e99328a45e docs: reference security guide in ipcRenderer.on docs (#45371)
Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Niklas Wenzel <dev@nikwen.de>
2025-01-29 15:44:07 -05:00
trop[bot]
04f5fe6a1c build: add NSPrefersDisplaySafeAreaCompatibilityMode = false to Info.plist (#45357)
build: add NSPrefersDisplaySafeAreaCompatibilityMode = false to Info.plist

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Milan Burda <milan.burda@gmail.com>
2025-01-29 19:55:03 +01:00
trop[bot]
08b6bb1712 build: use Python311 exe (#45364)
build: yse Python311 exe

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Keeley Hammond <khammond@slack-corp.com>
2025-01-28 20:43:17 -08:00
trop[bot]
813efbcdf7 docs: fix broken code in drag and drop example (#45336)
Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Niklas Wenzel <dev@nikwen.de>
2025-01-27 13:05:42 -05:00
trop[bot]
d34fa2e301 docs: Add note about directly exposing Electron APIs in preload (#45324)
* docs: Add note about directly exposing Electron APIs in preload

Co-authored-by: Felix Rieseberg <fr@makenotion.com>

* Implement feedback

Co-authored-by: Felix Rieseberg <fr@makenotion.com>

---------

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Felix Rieseberg <fr@makenotion.com>
2025-01-23 16:29:48 -08:00
trop[bot]
724744af16 chore: better logging if Node initialization fails (#45317)
feat: better logging if Node initialization fails

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Charles Kerr <charles@charleskerr.com>
2025-01-23 12:16:18 -06:00
trop[bot]
91bb748eaa refactor: remove InspectableWebContentsViewMac in favor of the Views version (#45238)
* refactor: remove InspectableWebContentsViewMac in favor of the Views version

* cherry-pick: refactor: remove InspectableWebContentsViewMac in favor of the Views version (#41326)

commit e67ab9a93d

Confilcts not resolved, except removal of the files removed
by the original commit.

* resolved conflicts and build issues after cherry-pick

* cherry-picked: fix: add method allowing to disable headless mode in native widget

https://github.com/electron/electron/pull/42996
fixing
https://github.com/electron/electron/issues/42995

* fix: displaying select popup in window created as fullscreen window

`constrainFrameRect:toScreen:` is not being call for windows created
with `fullscreen: true` therefore `headless` mode was not being removed
and `RenderWidgetHostNSViewBridge::DisplayPopupMenu` ignored displaying
popup.

Issue could be fixed by placing additional removal of `headless` mode
in the `toggleFullScreen:`, but `orderWindow:relativeTo:` is called
both for a regular and a fullscreen window, therefore there will be
a single place fixing both cases.

Because `electron::NativeWindowMac` lifetime may be shorter than
`ElectronNSWindow` on which macOS may execute `orderWindow:relativeTo:`
we need to clear `shell_` when `NativeWindow` is being closed.

Fixes #43010.

* fix: Content visibility when using `vibrancy`

We need to put `NSVisualEffectView` before `ViewsCompositorSuperview`
otherwise when using `vibrancy` in `BrowserWindow` `NSVisualEffectView`
will hide content displayed by the compositor.

Fixes #43003
Fixes #42336

In fact main issues reported in these tickets were not present after
cherry-picking original refactor switching to `views::WebView`, so
text could be selected and click event was properly generated. However
both issues testcases were using `vibrancy` and actual content was
invisible, because it was covered by the `NSVisualEffectView`.

* fix: EXCEPTION_ACCESS_VIOLATION crash on BrowserWindow.destroy()

Restored postponed deletion of the `NativeWindow`.

Restoration caused `DCHECK(new_parent_ui_layer->GetCompositor());` failure
in `BrowserCompositorMac::SetParentUiLayer` after the spec test:
`chrome extensions chrome.webRequest does not take precedence over Electron webRequest - http`
with stack:
```
7   Electron Framework 0x000000011fe07830 content::BrowserCompositorMac::SetParentUiLayer(ui::Layer*) + 628
8   Electron Framework 0x000000011fe0c154 content::RenderWidgetHostViewMac::SetParentUiLayer(ui::Layer*) + 220
9   Electron Framework 0x000000011fe226a8 content::WebContentsViewMac::CreateViewForWidget(content::RenderWidgetHost*) + 600
10  Electron Framework 0x000000011fd37e4c content::WebContentsImpl::CreateRenderWidgetHostViewForRenderManager(content::RenderViewHost*) + 164
11  Electron Framework 0x000000011fb32278 content::RenderFrameHostManager::CreateSpeculativeRenderFrame(content::SiteInstanceImpl*, bool, scoped_refptr<content::BrowsingContextState> const&) + 816
12  Electron Framework 0x000000011fb2ab8c content::RenderFrameHostManager::CreateSpeculativeRenderFrameHost(content::SiteInstanceImpl*, content::SiteInstanceImpl*, bool) + 1308
13  Electron Framework 0x000000011fb28598 content::RenderFrameHostManager::GetFrameHostForNavigation(content::NavigationRequest*, content::BrowsingContextGroupSwap*, std::__Cr::basic_string<char, std::__Cr::char_traits<char>, std::__Cr::allocator<char>>*) + 1796
14  Electron Framework 0x000000011fa78660 content::NavigationRequest::SelectFrameHostForOnRequestFailedInternal(bool, bool, std::__Cr::optional<std::__Cr::basic_string<char, std::__Cr::char_traits<char>, std::__Cr::allocator<char>>> const&) + 280
15  Electron Framework 0x000000011fa6a994 content::NavigationRequest::OnRequestFailedInternal(network::URLLoaderCompletionStatus const&, bool, std::__Cr::optional<std::__Cr::basic_string<char, std::__Cr::char_traits<char>, std::__Cr::allocator<char>>> const&, bo
+ 1008
16  Electron Framework 0x000000011fa7772c content::NavigationRequest::OnRequestFailed(network::URLLoaderCompletionStatus const&) + 72
17  Electron Framework 0x000000011f8554ac content::NavigationURLLoaderImpl::NotifyRequestFailed(network::URLLoaderCompletionStatus const&) + 248
```
This was probably the reason of removing `NativeWindow` immediately
in order to cleanup `views_host_` in `WebContentsViewMac` to prevent
using layer without compositor in `WebContentsViewMac::CreateViewForWidget`.

`[ElectronNSWindowDelegate windowWillClose:]` is deleting window host
and the compositor used by the `NativeWindow` therefore detach `NativeWindow`
contents from parent. This will clear `views_host_` and prevent failing
mentioned `DCHECK`.

Fixes #42975

* chore: Applied review suggestions

Co-authored-by: Michał Pichliński <michal.pichlinski@here.io>

* refactor: directly cleanup shell

Co-authored-by: Samuel Maddock <smaddock@slack-corp.com>

---------

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Michał Pichliński <michal.pichlinski@here.io>
Co-authored-by: Samuel Maddock <smaddock@slack-corp.com>
2025-01-23 11:54:15 +01:00
trop[bot]
d77c2d75ed fix: potential crash in chrome.tabs.update() (#45302)
fix: potential crash in chrome.tabs.update()

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2025-01-23 11:53:40 +01:00
trop[bot]
f4c3eb4391 refactor: in StopTracing(), use string literals instead of optional<string> (#45292)
refactor: simplify StopTracing() a little by using a string_view instead of an optional<string>

We have compile-time string literals that we're passing to a method
that takes a string_view argument, so we don't need all this extra
optional<string> scaffolding

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Charles Kerr <charles@charleskerr.com>
2025-01-22 09:43:38 -06:00
trop[bot]
9aca9e9fb6 docs: add DocCardList component for index doc (#45296)
Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Erick Zhao <ezhao@slack-corp.com>
2025-01-22 10:53:19 +01:00
trop[bot]
e0fa647601 refactor: simplify ParseUserScript() (#45288)
refactor: simplify ParseUserScript()

local variable user_script no longer needed after #43205

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Charles Kerr <charles@charleskerr.com>
2025-01-22 10:11:16 +01:00
trop[bot]
6b0fd02c0a fix: webContents.print() with OOP printing (#45285)
* fix: webContents.print() with OOP printing

Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>

* Update patches/chromium/printing.patch

Co-authored-by: Robo <hop2deep@gmail.com>

Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>

---------

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2025-01-21 15:13:29 -05:00
trop[bot]
1017ac821f chore: align clipboard blink::web_pref::WebPreferences with upstream (#45280)
chore: align clipboard blink::web_pref::WebPreferences with upstream

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2025-01-21 09:39:04 -08:00
trop[bot]
91b53b633a fix: getAsFileSystemHandle failure when drag-dropping two directories (#45256)
fix: drag-dropping two directories

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2025-01-20 14:01:15 -06:00
trop[bot]
8da9572592 fix: two possible FSA crashes (#45261)
* 5786874: Change Observer: Fix crash when navigating to new page

https://chromium-review.googlesource.com/c/chromium/src/+/5786874

Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>

* 5794141: Change Observer: Fix Get*PermissionGrant crash

https://chromium-review.googlesource.com/c/chromium/src/+/5794141

Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>

---------

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2025-01-20 18:20:55 +01:00
trop[bot]
291bbff5d8 build: fix clang-format duplicate message (#45265)
Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2025-01-20 18:20:47 +01:00
trop[bot]
d704a3fc5b fix: page scaling in silent mode printing (#45262)
Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2025-01-20 10:37:54 -06:00
trop[bot]
fb70b81ee6 fix: broken OOP window.print() on macOS/Linux (#45259)
fix: broken OOP printing on macOS/Linux

Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2025-01-20 10:37:35 -06:00
trop[bot]
97fa059e1f docs: remove quickstart (#45209)
Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com>
Co-authored-by: Anny Yang <yangannyx@gmail.com>
2025-01-17 10:36:58 +01:00
Felix Rieseberg
8a64cdc0b1 docs: Why Electron? (#45191) (#45222)
* docs: Why Electron?

* Apply suggestions from code review




* Update docs/why-electron.md

---------

Co-authored-by: Sam Maddock <samuel.maddock@gmail.com>
Co-authored-by: Erick Zhao <erick@hotmail.ca>
2025-01-16 14:06:57 -05:00
112 changed files with 3413 additions and 1925 deletions

View File

@@ -16,5 +16,5 @@ runs:
e auto-update disable
if [ "$(expr substr $(uname -s) 1 10)" == "MSYS_NT-10" ]; then
e d cipd.bat --version
cp "C:\Python37\python.exe" "C:\Python37\python3.exe"
cp "C:\Python311\python.exe" "C:\Python311\python3.exe"
fi

View File

@@ -56,8 +56,8 @@ on:
default: false
concurrency:
group: electron-build-and-test-and-nan-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !endsWith(github.ref, '-x-y') }}
group: electron-build-and-test-and-nan-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref_protected == true && github.run_id || github.ref }}
cancel-in-progress: ${{ github.ref_protected != true }}
jobs:
build:

View File

@@ -56,8 +56,8 @@ on:
default: false
concurrency:
group: electron-build-and-test-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !endsWith(github.ref, '-x-y') }}
group: electron-build-and-test-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref_protected == true && github.run_id || github.ref }}
cancel-in-progress: ${{ github.ref_protected != true }}
permissions:
contents: read

View File

@@ -9,8 +9,8 @@ on:
type: string
concurrency:
group: electron-lint-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !endsWith(github.ref, '-x-y') }}
group: electron-lint-${{ github.ref_protected == true && github.run_id || github.ref }}
cancel-in-progress: ${{ github.ref_protected != true }}
jobs:
lint:

View File

@@ -61,8 +61,8 @@ on:
concurrency:
group: electron-build-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ inputs.target-variant }}-${{ inputs.is-asan }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !endsWith(github.ref, '-x-y') }}
group: electron-build-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ inputs.target-variant }}-${{ inputs.is-asan }}-${{ github.ref_protected == true && github.run_id || github.ref }}
cancel-in-progress: ${{ github.ref_protected != true }}
env:
ELECTRON_ARTIFACTS_BLOB_STORAGE: ${{ secrets.ELECTRON_ARTIFACTS_BLOB_STORAGE }}

View File

@@ -27,8 +27,8 @@ on:
default: false
concurrency:
group: electron-test-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ inputs.is-asan }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !endsWith(github.ref, '-x-y') }}
group: electron-test-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ inputs.is-asan }}-${{ github.ref_protected == true && github.run_id || github.ref }}
cancel-in-progress: ${{ github.ref_protected != true }}
permissions:
contents: read

View File

@@ -27,8 +27,8 @@ on:
default: testing
concurrency:
group: electron-node-nan-test-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !endsWith(github.ref, '-x-y') }}
group: electron-node-nan-test-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref_protected == true && github.run_id || github.ref }}
cancel-in-progress: ${{ github.ref_protected != true }}
env:
ELECTRON_OUT_DIR: Default

View File

@@ -15,12 +15,12 @@ jobs:
- name: Trigger Slack workflow
uses: slackapi/slack-github-action@485a9d42d3a73031f12ec201c457e2162c45d02d # v2.0.0
with:
webhook: ${{ secrets.BACKPORT_REQUESTED_SLACK_WEBHOOK_URL }}
webhook-type: webhook-trigger
payload: |
{
"url": "${{ github.event.pull_request.html_url }}"
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.BACKPORT_REQUESTED_SLACK_WEBHOOK_URL }}
pull-request-labeled-deprecation-review-complete:
name: deprecation-review/complete label added
if: github.event.label.name == 'deprecation-review/complete ✅'

View File

@@ -21,7 +21,6 @@ an issue:
### Getting started
* [Introduction](tutorial/introduction.md)
* [Quick Start](tutorial/quick-start.md)
* [Process Model](tutorial/process-model.md)
### Learning the basics
@@ -128,6 +127,7 @@ These individual tutorials expand on topics discussed in the guide above.
* [pushNotifications](api/push-notifications.md)
* [safeStorage](api/safe-storage.md)
* [screen](api/screen.md)
* [ServiceWorkerMain](api/service-worker-main.md)
* [session](api/session.md)
* [ShareMenu](api/share-menu.md)
* [systemPreferences](api/system-preferences.md)

View File

@@ -61,6 +61,20 @@ The `contextBridge` module has the following methods:
* `apiKey` string - The key to inject the API onto `window` with. The API will be accessible on `window[apiKey]`.
* `api` any - Your API, more information on what this API can be and how it works is available below.
### `contextBridge.executeInMainWorld(executionScript)` _Experimental_
<!-- TODO(samuelmaddock): add generics to map the `args` types to the `func` params -->
* `executionScript` Object
* `func` (...args: any[]) => any - A JavaScript function to execute. This function will be serialized which means
that any bound parameters and execution context will be lost.
* `args` any[] (optional) - An array of arguments to pass to the provided function. These
arguments will be copied between worlds in accordance with
[the table of supported types.](#parameter--error--return-type-support)
Returns `any` - A copy of the resulting value from executing the function in the main world.
[Refer to the table](#parameter--error--return-type-support) on how values are copied between worlds.
## Usage
### API

View File

@@ -41,6 +41,16 @@ The `ipcRenderer` module has the following method to listen for events and send
Listens to `channel`, when a new message arrives `listener` would be called with
`listener(event, args...)`.
:::warning
Do not expose the `event` argument to the renderer for security reasons! Wrap any
callback that you receive from the renderer in another function like this:
`ipcRenderer.on('my-channel', (event, ...args) => callback(...args))`.
Not wrapping the callback in such a function would expose dangerous Electron APIs
to the renderer process. See the
[security guide](../tutorial/security.md#20-do-not-expose-electron-apis-to-untrusted-web-content)
for more info.
:::
### `ipcRenderer.off(channel, listener)`
* `channel` string

View File

@@ -0,0 +1,34 @@
# ServiceWorkerMain
> An instance of a Service Worker representing a version of a script for a given scope.
Process: [Main](../glossary.md#main-process)
## Class: ServiceWorkerMain
Process: [Main](../glossary.md#main-process)<br />
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._
### Instance Methods
#### `serviceWorker.isDestroyed()` _Experimental_
Returns `boolean` - Whether the service worker has been destroyed.
#### `serviceWorker.startTask()` _Experimental_
Returns `Object`:
- `end` Function - Method to call when the task has ended. If never called, the service won't terminate while otherwise idle.
Initiate a task to keep the service worker alive until ended.
### Instance Properties
#### `serviceWorker.scope` _Readonly_ _Experimental_
A `string` representing the scope URL of the service worker.
#### `serviceWorker.versionId` _Readonly_ _Experimental_
A `number` representing the ID of the specific version of the service worker script in its scope.

View File

@@ -56,6 +56,17 @@ Returns:
Emitted when a service worker has been registered. Can occur after a call to [`navigator.serviceWorker.register('/sw.js')`](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register) successfully resolves or when a Chrome extension is loaded.
#### Event: 'running-status-changed' _Experimental_
Returns:
* `details` Event\<\>
* `versionId` number - ID of the updated service worker version
* `runningStatus` string - Running status.
Possible values include `starting`, `running`, `stopping`, or `stopped`.
Emitted when a service worker's running status has changed.
### Instance Methods
The following methods are available on instances of `ServiceWorkers`:
@@ -64,10 +75,56 @@ The following methods are available on instances of `ServiceWorkers`:
Returns `Record<number, ServiceWorkerInfo>` - A [ServiceWorkerInfo](structures/service-worker-info.md) object where the keys are the service worker version ID and the values are the information about that service worker.
#### `serviceWorkers.getFromVersionID(versionId)`
#### `serviceWorkers.getInfoFromVersionID(versionId)`
* `versionId` number
* `versionId` number - ID of the service worker version
Returns [`ServiceWorkerInfo`](structures/service-worker-info.md) - Information about this service worker
If the service worker does not exist or is not running this method will throw an exception.
#### `serviceWorkers.getFromVersionID(versionId)` _Deprecated_
* `versionId` number - ID of the service worker version
Returns [`ServiceWorkerInfo`](structures/service-worker-info.md) - Information about this service worker
If the service worker does not exist or is not running this method will throw an exception.
**Deprecated:** Use the new `serviceWorkers.getInfoFromVersionID` API.
#### `serviceWorkers.getWorkerFromVersionID(versionId)` _Experimental_
* `versionId` number - ID of the service worker version
Returns [`ServiceWorkerMain | undefined`](service-worker-main.md) - Instance of the service worker associated with the given version ID. If there's no associated version, or its running status has changed to 'stopped', this will return `undefined`.
#### `serviceWorkers.startWorkerForScope(scope)` _Experimental_
* `scope` string - The scope of the service worker to start.
Returns `Promise<ServiceWorkerMain>` - Resolves with the service worker when it's started.
Starts the service worker or does nothing if already running.
<!-- TODO(samuelmaddock): extend example to send IPC after starting worker -->
```js
const { app, session } = require('electron')
const { serviceWorkers } = session.defaultSession
// Collect service workers scopes
const workerScopes = Object.values(serviceWorkers.getAllRunning()).map((info) => info.scope)
app.on('browser-window-created', async (event, window) => {
for (const scope of workerScopes) {
try {
// Ensure worker is started
await serviceWorkers.startWorkerForScope(scope)
} catch (error) {
console.error(`Failed to start service worker for ${scope}`)
console.error(error)
}
}
})
```

View File

@@ -1330,18 +1330,43 @@ the initial state will be `interrupted`. The download will start only when the
Returns `Promise<void>` - resolves when the sessions HTTP authentication cache has been cleared.
#### `ses.setPreloads(preloads)`
#### `ses.setPreloads(preloads)` _Deprecated_
* `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()`
**Deprecated:** Use the new `ses.registerPreloadScript` API.
#### `ses.getPreloads()` _Deprecated_
Returns `string[]` an array of paths to preload scripts that have been
registered.
**Deprecated:** Use the new `ses.getPreloadScripts` API. This will only return preload script paths
for `frame` context types.
#### `ses.registerPreloadScript(script)`
* `script` [PreloadScriptRegistration](structures/preload-script-registration.md) - Preload script
Registers preload script that will be executed in its associated context type in this session. For
`frame` contexts, this will run prior to any preload defined in the web preferences of a
WebContents.
Returns `string` - The ID of the registered preload script.
#### `ses.unregisterPreloadScript(id)`
* `id` string - Preload script ID
Unregisters script.
#### `ses.getPreloadScripts()`
Returns [`PreloadScript[]`](structures/preload-script.md): 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.

View File

@@ -0,0 +1,6 @@
# PreloadScriptRegistration Object
* `type` string - Context type where the preload script will be executed.
Possible values include `frame`.
* `id` string (optional) - Unique ID of preload script. Defaults to a random UUID.
* `filePath` string - Path of the script file. Must be an absolute path.

View File

@@ -0,0 +1,6 @@
# PreloadScript Object
* `type` string - Context type where the preload script will be executed.
Possible values include `frame`.
* `id` string - Unique ID of preload script.
* `filePath` string - Path of the script file. Must be an absolute path.

View File

@@ -3,3 +3,4 @@
* `scriptUrl` string - The full URL to the script that this service worker runs
* `scope` string - The base URL that this service worker is active for.
* `renderProcessId` number - The virtual ID of the process that this service worker is running in. This is not an OS level PID. This aligns with the ID set used for `webContents.getProcessId()`.
* `versionId` number - ID of the service worker version

View File

@@ -14,6 +14,40 @@ This document uses the following convention to categorize breaking changes:
## Planned Breaking API Changes (35.0)
### Deprecated: `setPreloads`, `getPreloads` on `Session`
`registerPreloadScript`, `unregisterPreloadScript`, and `getPreloadScripts` are introduced as a
replacement for the deprecated methods. These new APIs allow third-party libraries to register
preload scripts without replacing existing scripts. Also, the new `type` option allows for
additional preload targets beyond `frame`.
```js
// Deprecated
session.setPreloads([path.join(__dirname, 'preload.js')])
// Replace with:
session.registerPreloadScript({
type: 'frame',
id: 'app-preload',
filePath: path.join(__dirname, 'preload.js')
})
```
### Deprecated: `getFromVersionID` on `session.serviceWorkers`
The `session.serviceWorkers.fromVersionID(versionId)` API has been deprecated
in favor of `session.serviceWorkers.getInfoFromVersionID(versionId)`. This was
changed to make it more clear which object is returned with the introduction
of the `session.serviceWorkers.getWorkerFromVersionID(versionId)` API.
```js
// Deprecated
session.serviceWorkers.fromVersionID(versionId)
// Replace with
session.serviceWorkers.getInfoFromVersionID(versionId)
```
### Deprecated: `level`, `message`, `line`, and `sourceId` arguments in `console-message` event on `WebContents`
The `console-message` event on `WebContents` has been updated to provide details on the `Event`
@@ -56,15 +90,15 @@ immediately upon being received. Otherwise, it's not guaranteed to point to the
same webpage as when received. To avoid misaligned expectations, Electron will
return `null` in the case of late access where the webpage has changed.
```ts
```js
ipcMain.on('unload-event', (event) => {
event.senderFrame; // ✅ accessed immediately
});
event.senderFrame // ✅ accessed immediately
})
ipcMain.on('unload-event', async (event) => {
await crossOriginNavigationPromise;
event.senderFrame; // ❌ returns `null` due to late access
});
await crossOriginNavigationPromise
event.senderFrame // ❌ returns `null` due to late access
})
```
### Behavior Changed: custom protocol URL handling on Windows

View File

@@ -14,7 +14,7 @@ To configure a local keyboard shortcut, you need to specify an [`accelerator`][]
property when creating a [MenuItem][] within the [Menu][] module.
Starting with a working application from the
[Quick Start Guide](quick-start.md), update the `main.js` to be:
[tutorial starter code][tutorial-starter-code], update the `main.js` to be:
```fiddle docs/fiddles/features/keyboard-shortcuts/local
const { app, BrowserWindow, Menu, MenuItem } = require('electron/main')
@@ -75,7 +75,7 @@ module to detect keyboard events even when the application does not have
keyboard focus.
Starting with a working application from the
[Quick Start Guide](quick-start.md), update the `main.js` to be:
[tutorial starter code][tutorial-starter-code], update the `main.js` to be:
```fiddle docs/fiddles/features/keyboard-shortcuts/global
const { app, BrowserWindow, globalShortcut } = require('electron/main')
@@ -144,7 +144,7 @@ is emitted before dispatching `keydown` and `keyup` events in the page. It can
be used to catch and handle custom shortcuts that are not visible in the menu.
Starting with a working application from the
[Quick Start Guide](quick-start.md), update the `main.js` file with the
[tutorial starter code][tutorial-starter-code], update the `main.js` file with the
following lines:
```fiddle docs/fiddles/features/keyboard-shortcuts/interception-from-main
@@ -207,3 +207,4 @@ Mousetrap.bind('up up down down left right left right b a enter', () => {
[mousetrap]: https://github.com/ccampbell/mousetrap
[dom-events]: https://developer.mozilla.org/en-US/docs/Web/Events
[addEventListener-api]: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
[tutorial-starter-code]: tutorial-2-first-app.md#final-starter-code

View File

@@ -22,12 +22,9 @@ In `preload.js` use the [`contextBridge`][] to inject a method `window.electron.
```js
const { contextBridge, ipcRenderer } = require('electron')
const path = require('node:path')
contextBridge.exposeInMainWorld('electron', {
startDrag: (fileName) => {
ipcRenderer.send('ondragstart', path.join(process.cwd(), fileName))
}
startDrag: (fileName) => ipcRenderer.send('ondragstart', fileName)
})
```

View File

@@ -86,7 +86,7 @@ The main process also controls your application's lifecycle through Electron's
that you can use to add custom application behavior (for instance, programmatically
quitting your application, modifying the application dock, or showing an About panel).
As a practical example, the app shown in the [quick start guide][quick-start-lifecycle]
As a practical example, the app shown in the [tutorial starter code][tutorial-lifecycle]
uses `app` APIs to create a more native application window experience.
```js title='main.js'
@@ -97,7 +97,7 @@ app.on('window-all-closed', () => {
```
[app]: ../api/app.md
[quick-start-lifecycle]: ../tutorial/quick-start.md#manage-your-windows-lifecycle
[tutorial-lifecycle]: ../tutorial/tutorial-2-first-app.md#quit-the-app-when-all-windows-are-closed-windows--linux
### Native APIs

View File

@@ -1,513 +0,0 @@
# Quick Start
This guide will step you through the process of creating a barebones Hello World app in
Electron, similar to [`electron/electron-quick-start`][quick-start].
By the end of this tutorial, your app will open a browser window that displays a web page
with information about which Chromium, Node.js, and Electron versions are running.
[quick-start]: https://github.com/electron/electron-quick-start
## Prerequisites
To use Electron, you need to install [Node.js][node-download]. We recommend that you
use the latest `LTS` version available.
> Please install Node.js using pre-built installers for your platform.
> You may encounter incompatibility issues with different development tools otherwise.
To check that Node.js was installed correctly, type the following commands in your
terminal client:
```sh
node -v
npm -v
```
The commands should print the versions of Node.js and npm accordingly.
**Note:** Since Electron embeds Node.js into its binary, the version of Node.js running
your code is unrelated to the version running on your system.
[node-download]: https://nodejs.org/en/download/
## Create your application
### Scaffold the project
Electron apps follow the same general structure as other Node.js projects.
Start by creating a folder and initializing an npm package.
```sh npm2yarn
mkdir my-electron-app && cd my-electron-app
npm init
```
The interactive `init` command will prompt you to set some fields in your config.
There are a few rules to follow for the purposes of this tutorial:
* `entry point` should be `main.js`.
* `author` and `description` can be any value, but are necessary for
[app packaging](#package-and-distribute-your-application).
Your `package.json` file should look something like this:
```json
{
"name": "my-electron-app",
"version": "1.0.0",
"description": "Hello World!",
"main": "main.js",
"author": "Jane Doe",
"license": "MIT"
}
```
Then, install the `electron` package into your app's `devDependencies`.
```sh npm2yarn
npm install --save-dev electron
```
> Note: If you're encountering any issues with installing Electron, please
> refer to the [Advanced Installation][advanced-installation] guide.
Finally, you want to be able to execute Electron. In the [`scripts`][package-scripts]
field of your `package.json` config, add a `start` command like so:
```json
{
"scripts": {
"start": "electron ."
}
}
```
This `start` command will let you open your app in development mode.
```sh npm2yarn
npm start
```
> Note: This script tells Electron to run on your project's root folder. At this stage,
> your app will immediately throw an error telling you that it cannot find an app to run.
[advanced-installation]: ./installation.md
[package-scripts]: https://docs.npmjs.com/cli/v7/using-npm/scripts
### Run the main process
The entry point of any Electron application is its `main` script. This script controls the
**main process**, which runs in a full Node.js environment and is responsible for
controlling your app's lifecycle, displaying native interfaces, performing privileged
operations, and managing renderer processes (more on that later).
During execution, Electron will look for this script in the [`main`][package-json-main]
field of the app's `package.json` config, which you should have configured during the
[app scaffolding](#scaffold-the-project) step.
To initialize the `main` script, create an empty file named `main.js` in the root folder
of your project.
> Note: If you run the `start` script again at this point, your app will no longer throw
> any errors! However, it won't do anything yet because we haven't added any code into
> `main.js`.
[package-json-main]: https://docs.npmjs.com/cli/v7/configuring-npm/package-json#main
### Create a web page
Before we can create a window for our application, we need to create the content that
will be loaded into it. In Electron, each window displays web contents that can be loaded
from either a local HTML file or a remote URL.
For this tutorial, you will be doing the former. Create an `index.html` file in the root
folder of your project:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using Node.js <span id="node-version"></span>,
Chromium <span id="chrome-version"></span>,
and Electron <span id="electron-version"></span>.
</body>
</html>
```
> Note: Looking at this HTML document, you can observe that the version numbers are
> missing from the body text. We'll manually insert them later using JavaScript.
### Opening your web page in a browser window
Now that you have a web page, load it into an application window. To do so, you'll
need two Electron modules:
* The [`app`][app] module, which controls your application's event lifecycle.
* The [`BrowserWindow`][browser-window] module, which creates and manages application
windows.
Because the main process runs Node.js, you can import these as [CommonJS][commonjs]
modules at the top of your `main.js` file:
```js
const { app, BrowserWindow } = require('electron')
```
Then, add a `createWindow()` function that loads `index.html` into a new `BrowserWindow`
instance.
```js
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
}
```
Next, call this `createWindow()` function to open your window.
In Electron, browser windows can only be created after the `app` module's
[`ready`][app-ready] event is fired. You can wait for this event by using the
[`app.whenReady()`][app-when-ready] API. Call `createWindow()` after `whenReady()`
resolves its Promise.
```js @ts-type={createWindow:()=>void}
app.whenReady().then(() => {
createWindow()
})
```
> Note: At this point, your Electron application should successfully
> open a window that displays your web page!
[app]: ../api/app.md
[browser-window]: ../api/browser-window.md
[commonjs]: https://nodejs.org/docs/latest/api/modules.html#modules_modules_commonjs_modules
[app-ready]: ../api/app.md#event-ready
[app-when-ready]: ../api/app.md#appwhenready
### Manage your window's lifecycle
Although you can now open a browser window, you'll need some additional boilerplate code
to make it feel more native to each platform. Application windows behave differently on
each OS, and Electron puts the responsibility on developers to implement these
conventions in their app.
In general, you can use the `process` global's [`platform`][node-platform] attribute
to run code specifically for certain operating systems.
#### Quit the app when all windows are closed (Windows & Linux)
On Windows and Linux, exiting all windows generally quits an application entirely.
To implement this, listen for the `app` module's [`'window-all-closed'`][window-all-closed]
event, and call [`app.quit()`][app-quit] if the user is not on macOS (`darwin`).
```js
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
```
[node-platform]: https://nodejs.org/api/process.html#process_process_platform
[window-all-closed]: ../api/app.md#event-window-all-closed
[app-quit]: ../api/app.md#appquit
#### Open a window if none are open (macOS)
Whereas Linux and Windows apps quit when they have no windows open, macOS apps generally
continue running even without any windows open, and activating the app when no windows
are available should open a new one.
To implement this feature, listen for the `app` module's [`activate`][activate]
event, and call your existing `createWindow()` method if no browser windows are open.
Because windows cannot be created before the `ready` event, you should only listen for
`activate` events after your app is initialized. Do this by attaching your event listener
from within your existing `whenReady()` callback.
[activate]: ../api/app.md#event-activate-macos
```js @ts-type={createWindow:()=>void}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
```
> Note: At this point, your window controls should be fully functional!
### Access Node.js from the renderer with a preload script
Now, the last thing to do is print out the version numbers for Electron and its
dependencies onto your web page.
Accessing this information is trivial to do in the main process through Node's
global `process` object. However, you can't just edit the DOM from the main
process because it has no access to the renderer's `document` context.
They're in entirely different processes!
> Note: If you need a more in-depth look at Electron processes, see the
> [Process Model][] document.
This is where attaching a **preload** script to your renderer comes in handy.
A preload script runs before the renderer process is loaded, and has access to both
renderer globals (e.g. `window` and `document`) and a Node.js environment.
Create a new script named `preload.js` as such:
```js
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}
for (const dependency of ['chrome', 'node', 'electron']) {
replaceText(`${dependency}-version`, process.versions[dependency])
}
})
```
The above code accesses the Node.js `process.versions` object and runs a basic `replaceText`
helper function to insert the version numbers into the HTML document.
To attach this script to your renderer process, pass in the path to your preload script
to the `webPreferences.preload` option in your existing `BrowserWindow` constructor.
```js
const { app, BrowserWindow } = require('electron')
// include the Node.js 'path' module at the top of your file
const path = require('node:path')
// modify your existing createWindow() function
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
win.loadFile('index.html')
}
// ...
```
There are two Node.js concepts that are used here:
* The [`__dirname`][dirname] string points to the path of the currently executing script
(in this case, your project's root folder).
* The [`path.join`][path-join] API joins multiple path segments together, creating a
combined path string that works across all platforms.
We use a path relative to the currently executing JavaScript file so that your relative
path will work in both development and packaged mode.
[Process Model]: ./process-model.md
[dirname]: https://nodejs.org/api/modules.html#modules_dirname
[path-join]: https://nodejs.org/api/path.html#path_path_join_paths
### Bonus: Add functionality to your web contents
At this point, you might be wondering how to add more functionality to your application.
For any interactions with your web contents, you want to add scripts to your
renderer process. Because the renderer runs in a normal web environment, you can add a
`<script>` tag right before your `index.html` file's closing `</body>` tag to include
any arbitrary scripts you want:
```html
<script src="./renderer.js"></script>
```
The code contained in `renderer.js` can then use the same JavaScript APIs and tooling
you use for typical front-end development, such as using [`webpack`][webpack] to bundle
and minify your code or [React][react] to manage your user interfaces.
[webpack]: https://webpack.js.org
[react]: https://reactjs.org
### Recap
After following the above steps, you should have a fully functional
Electron application that looks like this:
![Simplest Electron app](../images/simplest-electron-app.png)
<!--TODO(erickzhao): Remove the individual code blocks for static website -->
The full code is available below:
```js
// main.js
// Modules to control application life and create native browser window
const { app, BrowserWindow } = require('electron')
const path = require('node:path')
const 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', () => {
// 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', () => {
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.
```
```js
// preload.js
// All the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}
for (const dependency of ['chrome', 'node', 'electron']) {
replaceText(`${dependency}-version`, process.versions[dependency])
}
})
```
```html
<!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using Node.js <span id="node-version"></span>,
Chromium <span id="chrome-version"></span>,
and Electron <span id="electron-version"></span>.
<!-- You can also require other files to run in this process -->
<script src="./renderer.js"></script>
</body>
</html>
```
```fiddle docs/fiddles/quick-start
```
To summarize all the steps we've done:
* We bootstrapped a Node.js application and added Electron as a dependency.
* We created a `main.js` script that runs our main process, which controls our app
and runs in a Node.js environment. In this script, we used Electron's `app` and
`BrowserWindow` modules to create a browser window that displays web content
in a separate process (the renderer).
* In order to access certain Node.js functionality in the renderer, we attached
a preload script to our `BrowserWindow` constructor.
## Package and distribute your application
The fastest way to distribute your newly created app is using
[Electron Forge](https://www.electronforge.io).
:::info
To build an RPM package for Linux, you will need to [install its required system dependencies](https://www.electronforge.io/config/makers/rpm).
:::
1. Add a description to your `package.json` file, otherwise rpmbuild will fail. Blank description are not valid.
2. Add Electron Forge as a development dependency of your app, and use its `import` command to set up
Forge's scaffolding:
```sh npm2yarn
npm install --save-dev @electron-forge/cli
npx electron-forge import
✔ Checking your system
✔ Initializing Git Repository
✔ Writing modified package.json file
✔ Installing dependencies
✔ Writing modified package.json file
✔ Fixing .gitignore
We have ATTEMPTED to convert your app to be in a format that electron-forge understands.
Thanks for using "electron-forge"!!!
```
3. Create a distributable using Forge's `make` command:
```sh npm2yarn
npm run make
> my-electron-app@1.0.0 make /my-electron-app
> electron-forge make
✔ Checking your system
✔ Resolving Forge Config
We need to package your application before we can make it
✔ Preparing to Package Application for arch: x64
✔ Preparing native dependencies
✔ Packaging Application
Making for the following targets: zip
✔ Making for target: zip - On platform: darwin - For arch: x64
```
Electron Forge creates the `out` folder where your package will be located:
```plain
// Example for macOS
out/
├── out/make/zip/darwin/x64/my-electron-app-darwin-x64-1.0.0.zip
├── ...
└── out/my-electron-app-darwin-x64/my-electron-app.app/Contents/MacOS/my-electron-app
```

View File

@@ -116,6 +116,7 @@ You should at least follow these steps to improve the security of your applicati
17. [Validate the `sender` of all IPC messages](#17-validate-the-sender-of-all-ipc-messages)
18. [Avoid usage of the `file://` protocol and prefer usage of custom protocols](#18-avoid-usage-of-the-file-protocol-and-prefer-usage-of-custom-protocols)
19. [Check which fuses you can change](#19-check-which-fuses-you-can-change)
20. [Do not expose Electron APIs to untrusted web content](#20-do-not-expose-electron-apis-to-untrusted-web-content)
To automate the detection of misconfigurations and insecure patterns, it is
possible to use
@@ -229,7 +230,7 @@ API to remotely loaded content via the [contextBridge API](../api/context-bridge
### 3. Enable Context Isolation
:::info
This recommendation is the default behavior in Electron since 12.0.0.
Context Isolation is the default behavior in Electron since 12.0.0.
:::
Context isolation is an Electron feature that allows developers to run code
@@ -804,6 +805,48 @@ flipping these fuses easy. Check out the README of that module for more details
potential error cases, and refer to
[How do I flip the fuses?](./fuses.md#how-do-i-flip-the-fuses) in our documentation.
### 20. Do not expose Electron APIs to untrusted web content
You should not directly expose Electron's APIs, especially IPC, to untrusted web content in your
preload scripts.
### Why?
Exposing raw APIs like `ipcRenderer.on` is dangerous because it gives renderer processes direct
access to the entire IPC event system, allowing them to listen for any IPC events, not just the ones
intended for them.
To avoid that exposure, we also cannot pass callbacks directly through: The first
argument to IPC event callbacks is an `IpcRendererEvent` object, which includes properties like `sender`
that provide access to the underlying `ipcRenderer` instance. Even if you only listen for specific
events, passing the callback directly means the renderer gets access to this event object.
In short, we want the untrusted web content to only have access to necessary information and APIs.
### How?
```js title='preload'.js'
// Bad
contextBridge.exposeInMainWorld('electronAPI', {
on: ipcRenderer.on
})
// Also bad
contextBridge.exposeInMainWorld('electronAPI', {
onUpdateCounter: (callback) => ipcRenderer.on('update-counter', callback)
})
// Good
contextBridge.exposeInMainWorld('electronAPI', {
onUpdateCounter: (callback) => ipcRenderer.on('update-counter', (_event, value) => callback(value))
})
```
:::info
For more information on what `contextIsolation` is and how to use it to secure your app,
please see the [Context Isolation](context-isolation.md) document.
:::
[breaking-changes]: ../breaking-changes.md
[browser-window]: ../api/browser-window.md
[webview-tag]: ../api/webview-tag.md

View File

@@ -1,3 +1,5 @@
import DocCardList from '@theme/DocCardList';
# Window Customization
The [`BrowserWindow`][] module is the foundation of your Electron application, and
@@ -5,13 +7,15 @@ it exposes many APIs that let you customize the look and behavior of your app
This section covers how to implement various use cases for window customization on macOS,
Windows, and Linux.
:::info
`BrowserWindow` is a subclass of the [`BaseWindow`][] module. Both modules allow
you to create and manage application windows in Electron, with the main difference
being that `BrowserWindow` supports a single, full size web view while `BaseWindow`
supports composing many web views. `BaseWindow` can be used interchangeably with `BrowserWindow`
in the examples of the documents in this section.
:::
> [!NOTE]
> `BrowserWindow` is a subclass of the [`BaseWindow`][] module. Both modules allow
> you to create and manage application windows in Electron, with the main difference
> being that `BrowserWindow` supports a single, full size web view while `BaseWindow`
> supports composing many web views. `BaseWindow` can be used interchangeably with `BrowserWindow`
> in the examples of the documents in this section.
<!-- markdownlint-disable-next-line MD033 -->
<DocCardList />
[`BaseWindow`]: ../api/base-window.md
[`BrowserWindow`]: ../api/browser-window.md

View File

@@ -8,7 +8,7 @@ If your app doesn't use any native modules, then it's really easy to create an A
1. Make sure that your app's `node_modules` directory is empty.
2. Using a _Command Prompt_, run `set npm_config_arch=arm64` before running `npm install`/`yarn install` as usual.
3. [If you have Electron installed as a development dependency](quick-start.md#prerequisites), npm will download and unpack the arm64 version. You can then package and distribute your app as normal.
3. [If you have Electron installed as a development dependency](tutorial-2-first-app.md#initializing-your-npm-project), npm will download and unpack the arm64 version. You can then package and distribute your app as normal.
## General considerations

View File

@@ -57,7 +57,7 @@ To set user tasks for your application, you can use
##### Set user tasks
Starting with a working application from the
[Quick Start Guide](quick-start.md), update the `main.js` file with the
[tutorial starter code][tutorial-starter-code], update the `main.js` file with the
following lines:
```js
@@ -121,7 +121,7 @@ To set thumbnail toolbar in your application, you need to use
##### Set thumbnail toolbar
Starting with a working application from the
[Quick Start Guide](quick-start.md), update the `main.js` file with the
[tutorial starter code][tutorial-starter-code], update the `main.js` file with the
following lines:
```js
@@ -185,7 +185,7 @@ To set the overlay icon for a window, you need to use the
#### Example
Starting with a working application from the
[Quick Start Guide](quick-start.md), update the `main.js` file with the
[tutorial starter code][tutorial-starter-code], update the `main.js` file with the
following lines:
```js
@@ -214,7 +214,7 @@ To flash the BrowserWindow taskbar button, you need to use the
#### Example
Starting with a working application from the
[Quick Start Guide](quick-start.md), update the `main.js` file with the
[tutorial starter code][tutorial-starter-code], update the `main.js` file with the
following lines:
```js
@@ -231,10 +231,10 @@ In the above example, it is called when the window comes into focus,
but you might use a timeout or some other event to disable it.
[msdn-flash-frame]: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-flashwindow#remarks
[setthumbarbuttons]: ../api/browser-window.md#winsetthumbarbuttonsbuttons-windows
[setusertaskstasks]: ../api/app.md#appsetusertaskstasks-windows
[setoverlayicon]: ../api/browser-window.md#winsetoverlayiconoverlay-description-windows
[flashframe]: ../api/browser-window.md#winflashframeflag
[recent-documents]: ./recent-documents.md
[progress-bar]: ./progress-bar.md
[tutorial-starter-code]: ../tutorial/tutorial-2-first-app.md#final-starter-code

103
docs/why-electron.md Normal file
View File

@@ -0,0 +1,103 @@
# Why Electron
Electron is a framework enabling developers to build cross-platform desktop applications for macOS, Windows, and Linux by combining web technologies (HTML, JavaScript, CSS) with Node.js and native code. It is open-source, MIT-licensed, and free for both commercial and personal use. In this document, well explain why companies and developers choose Electron.
We can split up the benefits of Electron in two questions: First, why should you use web technologies to build your application? Then, why should you choose Electron as the framework to do so?
If youre already using web technologies for your application, you can skip straight to the `Why Electron?` section below.
## Why choose web technologies
Web technologies include HTML, CSS, JavaScript, and WebAssembly. Theyre the storefront of the modern Internet. Those technologies have emerged as the best choice for building user interfaces — both for consumer applications as well as mission-critical business applications. This is true both for applications that need to run in a browser as well as desktop applications that are not accessible from a browser. Our bold claim here is that this isnt just true for cross-platform applications that need to run on multiple operating systems but true overall.
As an example, NASAs actual [Mission Control](https://github.com/nasa/openmct) is written with web technologies. The [Bloomberg Terminal](https://en.wikipedia.org/wiki/Bloomberg_Terminal), the computer system found at every financial institution, is written with web technologies and runs inside Chromium. It costs $25,000 per user, per year. The McDonalds ordering kiosk, powering the worlds biggest food retailer, is entirely built with Chromium. The [SpaceXs Dragon 2 space capsule](https://old.reddit.com/r/spacex/comments/gxb7j1/we_are_the_spacex_software_team_ask_us_anything/ft62781/?context=3) uses Chromium to display its interface. You get the point: web technologies are a great tech stack to build user interfaces.
Here are the reasons we, the Electron maintainers, are betting on the web.
### Versatility
Modern versions of HTML and CSS enable your developers and designers to fully express themselves. The webs showcase includes Google Earth, Netflix, Spotify, Gmail, Facebook, Airbnb, or GitHub. Whatever interface your application needs, you will be able to express it with HTML, CSS, and JavaScript.
If you want to focus on building a great product without figuring out how you can realize your designers vision in a specific UI framework, the web is a safe bet.
### Reliability
Web technologies are the most-used foundation for user interfaces on the planet. The have been hardened accordingly. Modern computers have been optimized from the CPU to the operating system to be good at running web technologies. The manufacturers of your users devices—be that an Android phone or the latest MacBook—will ensure that they can visit websites, play videos on YouTube, or display emails. In turn, theyll also ensure that your app has a stable foundation, even if you have just one user.
If you want to focus on building a great product without debugging a weird quirk that nobody has found before, the web is a safe bet.
### Interoperability
Whatever provider or customer data you need to interact with, they will have probably thought of an integration path with the web. Depending on your technology choice, embedding a YouTube video either takes 30 seconds or requires you to hire a team devoted to streaming and hardware-accelerated video decoding. In the case of YouTube, using anything other than the provided players is actually against their terms and conditions, so youll likely embed a browser frame before you implement your own video streaming decoder.
There will be virtually no platform where your app cannot run if you build it with web technologies. Virtually all devices with a display—be that an ATM, a car infotainment system, a smart TV, a fridge, or a Nintendo Switch—come with means to display web technologies. The web is safe bet if you want to be cross-platform.
### Ubiquity
Its easy to find developers with experience building with web technologies. If youre a developer, itll be easy to find answers to your questions on Google, Stack Overflow, GitHub, or a coding AI of your choice. Whatever problem you need to solve, its likely that somebody has solved it well before—and that you can find the answer to the puzzle online.
If you want to focus on building a great product with ample access to resources and materials, the web is a safe bet.
## Why choose Electron
Electron combines Chromium, Node.js, and the ability to write custom native code into one framework for building powerful desktop applications. There are three main reasons to use Electron:
### Enterprise-grade
Electron is reliable, secure, stable, and mature. It is the premier choice for companies building their flagship product. We have a list of some of those companies on our homepage, but just among chat apps, Slack, Discord, and Skype are built with Electron. Among AI applications, both OpenAIs ChatGPT and Anthropics Claude use Electron. Visual Studio Code, Loom, Canva, Notion, Docker, and countless other leading developers of software bet on Electron.
We did make it a priority to make Electron easy to work with and a delight for developers. Thats likely the main reason why Electron became as popular as it is today — but what keeps Electron alive and thriving is the maintainers focus on making Electron as stable, secure, performant, and capable of mission-critical use cases for end users as possible. Were building an Electron that is ready to be used in scenarios where unfixable bugs, unpatched security holes, and outages of any kind are worst-case scenarios.
### Mature
Our current estimation is that most desktop computers on the planet run at least one Electron app. Electron has grown by prioritizing talent in its maintainer group, fostering excellent and sustainable engineering practices in managing the ongoing maintenance, and proactively inviting companies betting on Electron to directly contribute to the project. Were an impact project with the OpenJS foundation, which is itself a part of the Linux foundation. We share resources and expertise with other foundation projects like Node.js, ESLint, Webpack - or the Linux Kernel or Kubernetes.
What does all of that mean for you, a developer, in practice?
- **Reliable release schedule**: Electron will release a new major version in lockstep with every second major Chromium release, usually on the same day as Chromium. A lot of work, both in the form of building processes and tools, but also in terms of raw invested hours every week, has to go into making that happen.
- **No dictators**: Sometimes, betting on a technology also requires you to bet on a single person or company. In turn, it requires you to trust that the person or company never has a breakdown, starts fighting you directly, or does anything else drastic thatll force you rethink your entire tech stack. Electron is maintained by a diverse set of companies (Microsoft, Slack/Salesforce, Notion, and more) and will continue to welcome more companies interested in ensuring their “seat at the decision-making table”.
### Stability, security, performance
Electron delivers the best experience on all target platforms (macOS, Windows, Linux) by bundling the latest version of Chromium, V8, and Node.js directly with the application binary. When it comes to running and rendering web content with upmost stability, security, and performance, we currently believe that stack to be “best in class”.
#### Why bundle anything at all
You might wonder why we bundle Chromiums web stack with our apps when most modern operating systems already ship a browser and some form of web view. Bundling doesnt just increase the amount of work for Electron maintainers dramatically, it also increases the total disk size of Electron apps (most apps are >100MB). Many Electron maintainers once developed applications that did make use of embedded web views — and have since accepted the increased disk size and maintainer work as a worthy trade-off.
When using an operating system's built-in web view, you're limited by the browser version included in the oldest operating system version you need to support. We have found the following problems with this approach:
- **Stability**: The modern web technology stack is complex, and as a result, youll sooner or later encounter bugs. If you use the operating systems web view, your only recourse will be to ask your customers to upgrade their operating system. If no upgrade is available for that machine (because of no ability to upgrade to the latest macOS or Windows 11), youll have to ask them to buy a new computer. If youre unlucky, youre now losing a major customer because they will not upgrade their entire fleet of thousands of machines just because one team wanted to try your startups app. You have _no recourse_ in this situation. Even the risk of that happening is unacceptable to the companies that employ the Electron maintainers.
- **Security:** Similar to how you can fix stability bugs by releasing an app update, you can also release security fixes to your application without asking your customer to upgrade their operating system. Even if operating system providers prioritize updates to their built-in browser, we have not seen them reliably update the built-in web views with similar urgency. Bundling a web renderer gives you, the developer, control.
- **Performance:** For simple HTML documents, a built-in web view will sometimes use fewer resources than an app with a bundled framework. For bigger apps, it is our experience that we can deliver better performance with the latest version of Chromium than we can with built-in web views. You might think that the built-in view can share a lot of resources with other apps and the operating system— but for security reasons, apps have to run in their own sandboxes, isolated from each other. At that point, the question is whether the OS web view is more performant than Chromium. Across many apps, our experience is that bundling Chromium and Node.js enables us to build better and more performant experiences.
#### Why bundle Chromium and Node.js
Electron aims to enable the apps it supports to deliver the best possible user experience, followed by the best possible developer experience. Chromium is currently the best cross-platform rendering stack available. Node.js uses Chromiums JavaScript engine V8, allowing us to combine the powers of both.
- **Native code when you want it**: Thanks to Node.js mature native addon system, you can always write native code. There is no system API out of reach for you. Whatever macOS, Windows, or Linux feature youll want to integrate with —as long as you can do it in C, C++, Objective-C, Rust, or another native language, youll be able to do it in Electron. Again, this gives you, the developer, maximum control. With Electron, you can use web technologies without choosing _only_ web technologies.
### Developer experience
To summarize, we aim to build an Electron that is mature, enterprise-grade, and ready for mission-critical applications. We prioritize reliability, stability, security, and performance. That said, you might also choose Electron for its developer experience:
- **Powerful ecosystem**: Anything you find on npm will run inside Electron. Any resource available to you about how to work with Node.js also applies to Electron. In addition, Electron itself has a [thriving ecosystem](https://www.npmjs.com/search?q=electron) — including plenty of choices for installers, updaters, deeper operating system-integration, and more.
- **Plenty of built-in capabilities:** Over the last ten years, Electrons core has gained plenty of native capabilities that you might need to build your application. Written in C++ and Objective-C, Electron has [dozens of easy-to-use APIs for deeper operating-system integration](https://www.electronjs.org/docs/latest/api/app) — like advanced window customization for transparent or oddly shaped widgets, receiving push notifications from the Apple Push Notification Network, or handling a custom URL protocol for your app.
- **Open source**: The entire stack is open source and open to your inspection. This ensures your freedom to add any feature or fix any bug you might encounter in the future.
- **Native code when you need it:** It bears repeating that Electron allows you to mix and match web technologies and C++, C, Objective-C, Rust, and other native languages. Whether it be SQLite, a whole LLM, or just the ability to call one specific native API, Electron will make it easy.
---
## Why choose something else
As outlined above, the web is an amazing platform for building interfaces. That doesnt mean that we, the maintainers, would build _everything_ with HTML and CSS. Here are some notable exceptions:
**Resource-Constrained Environments and IoT:** In scenarios with very limited memory or processing power (say, one megabyte of memory and 100MHz of processing power on a low-powered ARM Cortex-M), you will likely need to use a low-level language to directly talk to the display to output basic text and images. Even on slightly higher-powered single-chip devices you might want to consider an embedded UI framework. A classic example is a smart watch.
**Small Disk Footprint**: Zipped Electron apps are usually around 80 to 100 Megabytes. If a smaller disk footprint is a hard requirement, youll have to use something else.
**Operating System UI Frameworks and Libraries**: By allowing you to write native code, Electron can do anything a native application can do, including the use of the operating systems UI components, like WinUI, SwiftUI, or AppKit. In practice, most Electron apps make rare use of that ability. If you want the majority of your app to be built with operating system-provided interface components, youll likely be better off building fully native apps for each operating system youd like to target. Its not that its impossible with Electron, itll just likely be an overall easier development process.
**Games and Real-Time Graphics:** If you're building a high-performance game or application requiring complex real-time 3D graphics, native frameworks like Unity, Unreal Engine, or DirectX/OpenGL will provide better performance and more direct access to graphics hardware. Web fans might point out caveats, like the fact that even Unreal Engine ships with Chromium — or that WebGPU and WebGL are developing rapidly and many game engines, including the ones listed here, can now output their games in a format that runs in a browser. That said, if you asked us to build the next AAA game, wed likely use something else than just web technologies.
**Embedding Lightweight Websites**: Electron apps typically are mostly web apps with native code sprinkled in where useful. Processing-heavy Electron applications tend to write the UI in HTML/CSS and build the backend in Rust, C++, or another native language. If youre planning to build a primarily native application that also wants to display a little website in a specific view, you might be better off using the OS-provided web view or something like [ultralight](https://ultralig.ht/).

View File

@@ -45,6 +45,7 @@ auto_filenames = {
"docs/api/push-notifications.md",
"docs/api/safe-storage.md",
"docs/api/screen.md",
"docs/api/service-worker-main.md",
"docs/api/service-workers.md",
"docs/api/session.md",
"docs/api/share-menu.md",
@@ -114,6 +115,8 @@ auto_filenames = {
"docs/api/structures/permission-request.md",
"docs/api/structures/point.md",
"docs/api/structures/post-body.md",
"docs/api/structures/preload-script-registration.md",
"docs/api/structures/preload-script.md",
"docs/api/structures/printer-info.md",
"docs/api/structures/process-memory-info.md",
"docs/api/structures/process-metric.md",
@@ -183,6 +186,8 @@ auto_filenames = {
"lib/sandboxed_renderer/api/exports/electron.ts",
"lib/sandboxed_renderer/api/module-list.ts",
"lib/sandboxed_renderer/init.ts",
"lib/sandboxed_renderer/pre-init.ts",
"lib/sandboxed_renderer/preload.ts",
"package.json",
"tsconfig.electron.json",
"tsconfig.json",
@@ -239,6 +244,7 @@ auto_filenames = {
"lib/browser/api/push-notifications.ts",
"lib/browser/api/safe-storage.ts",
"lib/browser/api/screen.ts",
"lib/browser/api/service-worker-main.ts",
"lib/browser/api/session.ts",
"lib/browser/api/share-menu.ts",
"lib/browser/api/system-preferences.ts",

View File

@@ -159,12 +159,8 @@ filenames = {
"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",
@@ -191,8 +187,6 @@ filenames = {
"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",
@@ -224,8 +218,6 @@ filenames = {
"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",
@@ -304,6 +296,8 @@ filenames = {
"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_service_worker_main.cc",
"shell/browser/api/electron_api_service_worker_main.h",
"shell/browser/api/electron_api_session.cc",
"shell/browser/api/electron_api_session.h",
"shell/browser/api/electron_api_system_preferences.cc",
@@ -482,6 +476,7 @@ filenames = {
"shell/browser/osr/osr_web_contents_view.h",
"shell/browser/plugins/plugin_utils.cc",
"shell/browser/plugins/plugin_utils.h",
"shell/browser/preload_script.h",
"shell/browser/protocol_registry.cc",
"shell/browser/protocol_registry.h",
"shell/browser/relauncher.cc",
@@ -621,6 +616,8 @@ filenames = {
"shell/common/gin_converters/osr_converter.cc",
"shell/common/gin_converters/osr_converter.h",
"shell/common/gin_converters/serial_port_info_converter.h",
"shell/common/gin_converters/service_worker_converter.cc",
"shell/common/gin_converters/service_worker_converter.h",
"shell/common/gin_converters/std_converter.h",
"shell/common/gin_converters/time_converter.cc",
"shell/common/gin_converters/time_converter.h",

View File

@@ -29,6 +29,7 @@ export const browserModuleList: ElectronInternal.ModuleEntry[] = [
{ name: 'protocol', loader: () => require('./protocol') },
{ name: 'safeStorage', loader: () => require('./safe-storage') },
{ name: 'screen', loader: () => require('./screen') },
{ name: 'ServiceWorkerMain', loader: () => require('./service-worker-main') },
{ name: 'session', loader: () => require('./session') },
{ name: 'ShareMenu', loader: () => require('./share-menu') },
{ name: 'systemPreferences', loader: () => require('./system-preferences') },

View File

@@ -0,0 +1,17 @@
const { ServiceWorkerMain } = process._linkedBinding('electron_browser_service_worker_main');
ServiceWorkerMain.prototype.startTask = function () {
// TODO(samuelmaddock): maybe make timeout configurable in the future
const hasTimeout = false;
const { id, ok } = this._startExternalRequest(hasTimeout);
if (!ok) {
throw new Error('Unable to start service worker task.');
}
return {
end: () => this._finishExternalRequest(id)
};
};
module.exports = ServiceWorkerMain;

View File

@@ -1,4 +1,5 @@
import { fetchWithSession } from '@electron/internal/browser/api/net-fetch';
import * as deprecate from '@electron/internal/common/deprecate';
import { net } from 'electron/main';
@@ -36,6 +37,31 @@ Session.prototype.setDisplayMediaRequestHandler = function (handler, opts) {
}, opts);
};
const getPreloadsDeprecated = deprecate.warnOnce('session.getPreloads', 'session.getPreloadScripts');
Session.prototype.getPreloads = function () {
getPreloadsDeprecated();
return this.getPreloadScripts()
.filter((script) => script.type === 'frame')
.map((script) => script.filePath);
};
const setPreloadsDeprecated = deprecate.warnOnce('session.setPreloads', 'session.registerPreloadScript');
Session.prototype.setPreloads = function (preloads) {
setPreloadsDeprecated();
this.getPreloadScripts()
.filter((script) => script.type === 'frame')
.forEach((script) => {
this.unregisterPreloadScript(script.id);
});
preloads.map(filePath => ({
type: 'frame',
filePath,
_deprecated: true
}) as Electron.PreloadScriptRegistration).forEach(script => {
this.registerPreloadScript(script);
});
};
export default {
fromPartition,
fromPath,

View File

@@ -146,6 +146,9 @@ require('@electron/internal/browser/devtools');
// Load protocol module to ensure it is populated on app ready
require('@electron/internal/browser/api/protocol');
// Load service-worker-main module to ensure it is populated on app ready
require('@electron/internal/browser/api/service-worker-main');
// Load web-contents module to ensure it is populated on app ready
require('@electron/internal/browser/api/web-contents');

View File

@@ -5,6 +5,7 @@ import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages';
import { clipboard } from 'electron/common';
import * as fs from 'fs';
import * as path from 'path';
// Implements window.close()
ipcMainInternal.on(IPC_MESSAGES.BROWSER_WINDOW_CLOSE, function (event) {
@@ -43,22 +44,40 @@ ipcMainUtils.handleSync(IPC_MESSAGES.BROWSER_CLIPBOARD_SYNC, function (event, me
return (clipboard as any)[method](...args);
});
const getPreloadScript = async function (preloadPath: string) {
let preloadSrc = null;
let preloadError = null;
const getPreloadScriptsFromEvent = (event: ElectronInternal.IpcMainInternalEvent) => {
const session: Electron.Session = event.sender.session;
const preloadScripts = session.getPreloadScripts();
const framePreloads = preloadScripts.filter(script => script.type === 'frame');
const webPrefPreload = event.sender._getPreloadScript();
if (webPrefPreload) framePreloads.push(webPrefPreload);
// TODO(samuelmaddock): Remove filter after Session.setPreloads is fully
// deprecated. The new API will prevent relative paths from being registered.
return framePreloads.filter(script => path.isAbsolute(script.filePath));
};
const readPreloadScript = async function (script: Electron.PreloadScript): Promise<ElectronInternal.PreloadScript> {
let contents;
let error;
try {
preloadSrc = await fs.promises.readFile(preloadPath, 'utf8');
} catch (error) {
preloadError = error;
contents = await fs.promises.readFile(script.filePath, 'utf8');
} catch (err) {
if (err instanceof Error) {
error = err;
}
}
return { preloadPath, preloadSrc, preloadError };
return {
...script,
contents,
error
};
};
ipcMainUtils.handleSync(IPC_MESSAGES.BROWSER_SANDBOX_LOAD, async function (event) {
const preloadPaths = event.sender._getPreloadPaths();
const preloadScripts = getPreloadScriptsFromEvent(event);
return {
preloadScripts: await Promise.all(preloadPaths.map(path => getPreloadScript(path))),
preloadScripts: await Promise.all(preloadScripts.map(readPreloadScript)),
process: {
arch: process.arch,
platform: process.platform,
@@ -71,7 +90,8 @@ ipcMainUtils.handleSync(IPC_MESSAGES.BROWSER_SANDBOX_LOAD, async function (event
});
ipcMainUtils.handleSync(IPC_MESSAGES.BROWSER_NONSANDBOX_LOAD, function (event) {
return { preloadPaths: event.sender._getPreloadPaths() };
const preloadScripts = getPreloadScriptsFromEvent(event);
return { preloadPaths: preloadScripts.map(script => script.filePath) };
});
ipcMainInternal.on(IPC_MESSAGES.BROWSER_PRELOAD_ERROR, function (event, preloadPath: string, error: Error) {

View File

@@ -5,13 +5,17 @@ const checkContextIsolationEnabled = () => {
};
const contextBridge: Electron.ContextBridge = {
exposeInMainWorld: (key: string, api: any) => {
exposeInMainWorld: (key, api) => {
checkContextIsolationEnabled();
return binding.exposeAPIInWorld(0, key, api);
},
exposeInIsolatedWorld: (worldId: number, key: string, api: any) => {
exposeInIsolatedWorld: (worldId, key, api) => {
checkContextIsolationEnabled();
return binding.exposeAPIInWorld(worldId, key, api);
},
executeInMainWorld: (script) => {
checkContextIsolationEnabled();
return binding.executeInWorld(0, script);
}
};
@@ -27,8 +31,7 @@ export const internalContextBridge = {
},
overrideGlobalPropertyFromIsolatedWorld: (keys: string[], getter: Function, setter?: Function) => {
return binding._overrideGlobalPropertyFromIsolatedWorld(keys, getter, setter || null);
},
isInMainWorld: () => binding._isCalledFromMainWorld() as boolean
}
};
if (binding._isDebug) {

View File

@@ -1,6 +1,7 @@
import '@electron/internal/sandboxed_renderer/pre-init';
import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages';
import type * as ipcRendererInternalModule from '@electron/internal/renderer/ipc-renderer-internal';
import type * as ipcRendererUtilsModule from '@electron/internal/renderer/ipc-renderer-internal-utils';
import { createPreloadProcessObject, executeSandboxedPreloadScripts } from '@electron/internal/sandboxed_renderer/preload';
import * as events from 'events';
import { setImmediate, clearImmediate } from 'timers';
@@ -11,35 +12,14 @@ declare const binding: {
createPreloadScript: (src: string) => Function
};
const { EventEmitter } = events;
process._linkedBinding = binding.get;
const v8Util = process._linkedBinding('electron_common_v8_util');
// Expose Buffer shim as a hidden value. This is used by C++ code to
// deserialize Buffer instances sent from browser process.
v8Util.setHiddenValue(global, 'Buffer', Buffer);
// The process object created by webpack is not an event emitter, fix it so
// the API is more compatible with non-sandboxed renderers.
for (const prop of Object.keys(EventEmitter.prototype) as (keyof typeof process)[]) {
if (Object.hasOwn(process, prop)) {
delete process[prop];
}
}
Object.setPrototypeOf(process, EventEmitter.prototype);
const { ipcRendererInternal } = require('@electron/internal/renderer/ipc-renderer-internal') as typeof ipcRendererInternalModule;
const ipcRendererUtils = require('@electron/internal/renderer/ipc-renderer-internal-utils') as typeof ipcRendererUtilsModule;
const {
preloadScripts,
process: processProps
} = ipcRendererUtils.invokeSync<{
preloadScripts: {
preloadPath: string;
preloadSrc: string | null;
preloadError: null | Error;
}[];
preloadScripts: ElectronInternal.PreloadScript[];
process: NodeJS.Process;
}>(IPC_MESSAGES.BROWSER_SANDBOX_LOAD);
@@ -60,8 +40,7 @@ const loadableModules = new Map<string, Function>([
['node:url', () => require('url')]
]);
// Pass different process object to the preload script.
const preloadProcess: NodeJS.Process = new EventEmitter() as any;
const preloadProcess = createPreloadProcessObject();
// InvokeEmitProcessEvent in ElectronSandboxedRendererClient will look for this
v8Util.setHiddenValue(global, 'emit-process-event', (event: string) => {
@@ -72,77 +51,22 @@ v8Util.setHiddenValue(global, 'emit-process-event', (event: string) => {
Object.assign(preloadProcess, binding.process);
Object.assign(preloadProcess, processProps);
Object.assign(process, binding.process);
Object.assign(process, processProps);
process.getProcessMemoryInfo = preloadProcess.getProcessMemoryInfo = () => {
return ipcRendererInternal.invoke<Electron.ProcessMemoryInfo>(IPC_MESSAGES.BROWSER_GET_PROCESS_MEMORY_INFO);
};
Object.defineProperty(preloadProcess, 'noDeprecation', {
get () {
return process.noDeprecation;
},
set (value) {
process.noDeprecation = value;
}
});
// This is the `require` function that will be visible to the preload script
function preloadRequire (module: string) {
if (loadedModules.has(module)) {
return loadedModules.get(module);
}
if (loadableModules.has(module)) {
const loadedModule = loadableModules.get(module)!();
loadedModules.set(module, loadedModule);
return loadedModule;
}
throw new Error(`module not found: ${module}`);
}
// Process command line arguments.
const { hasSwitch } = process._linkedBinding('electron_common_command_line');
// Similar to nodes --expose-internals flag, this exposes _linkedBinding so
// that tests can call it to get access to some test only bindings
if (hasSwitch('unsafely-expose-electron-internals-for-testing')) {
preloadProcess._linkedBinding = process._linkedBinding;
}
// Common renderer initialization
require('@electron/internal/renderer/common-init');
// Wrap the script into a function executed in global scope. It won't have
// access to the current scope, so we'll expose a few objects as arguments:
//
// - `require`: The `preloadRequire` function
// - `process`: The `preloadProcess` object
// - `Buffer`: Shim of `Buffer` implementation
// - `global`: The window object, which is aliased to `global` by webpack.
function runPreloadScript (preloadSrc: string) {
const preloadWrapperSrc = `(function(require, process, Buffer, global, setImmediate, clearImmediate, exports, module) {
${preloadSrc}
})`;
// eval in window scope
const preloadFn = binding.createPreloadScript(preloadWrapperSrc);
const exports = {};
preloadFn(preloadRequire, preloadProcess, Buffer, global, setImmediate, clearImmediate, exports, { exports });
}
for (const { preloadPath, preloadSrc, preloadError } of preloadScripts) {
try {
if (preloadSrc) {
runPreloadScript(preloadSrc);
} else if (preloadError) {
throw preloadError;
}
} catch (error) {
console.error(`Unable to load preload script: ${preloadPath}`);
console.error(error);
ipcRendererInternal.send(IPC_MESSAGES.BROWSER_PRELOAD_ERROR, preloadPath, error);
executeSandboxedPreloadScripts({
loadedModules,
loadableModules,
process: preloadProcess,
createPreloadScript: binding.createPreloadScript,
exposeGlobals: {
Buffer,
// FIXME(samuelmaddock): workaround webpack bug replacing this with just
// `__webpack_require__.g,` which causes script error
global: globalThis,
setImmediate,
clearImmediate
}
}
}, preloadScripts);

View File

@@ -0,0 +1,30 @@
// Pre-initialization code for sandboxed renderers.
import * as events from 'events';
declare const binding: {
get: (name: string) => any;
process: NodeJS.Process;
};
// Expose internal binding getter.
process._linkedBinding = binding.get;
const { EventEmitter } = events;
const v8Util = process._linkedBinding('electron_common_v8_util');
// Include properties from script 'binding' parameter.
Object.assign(process, binding.process);
// Expose Buffer shim as a hidden value. This is used by C++ code to
// deserialize Buffer instances sent from browser process.
v8Util.setHiddenValue(global, 'Buffer', Buffer);
// The process object created by webpack is not an event emitter, fix it so
// the API is more compatible with non-sandboxed renderers.
for (const prop of Object.keys(EventEmitter.prototype) as (keyof typeof process)[]) {
if (Object.hasOwn(process, prop)) {
delete process[prop];
}
}
Object.setPrototypeOf(process, EventEmitter.prototype);

View File

@@ -0,0 +1,101 @@
import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages';
import { ipcRendererInternal } from '@electron/internal/renderer/ipc-renderer-internal';
import { EventEmitter } from 'events';
interface PreloadContext {
loadedModules: Map<string, any>;
loadableModules: Map<string, any>;
/** Process object to pass into preloads. */
process: NodeJS.Process;
createPreloadScript: (src: string) => Function
/** Globals to be exposed to preload context. */
exposeGlobals: any;
}
export function createPreloadProcessObject (): NodeJS.Process {
const preloadProcess: NodeJS.Process = new EventEmitter() as any;
preloadProcess.getProcessMemoryInfo = () => {
return ipcRendererInternal.invoke<Electron.ProcessMemoryInfo>(IPC_MESSAGES.BROWSER_GET_PROCESS_MEMORY_INFO);
};
Object.defineProperty(preloadProcess, 'noDeprecation', {
get () {
return process.noDeprecation;
},
set (value) {
process.noDeprecation = value;
}
});
const { hasSwitch } = process._linkedBinding('electron_common_command_line');
// Similar to nodes --expose-internals flag, this exposes _linkedBinding so
// that tests can call it to get access to some test only bindings
if (hasSwitch('unsafely-expose-electron-internals-for-testing')) {
preloadProcess._linkedBinding = process._linkedBinding;
}
return preloadProcess;
}
// This is the `require` function that will be visible to the preload script
function preloadRequire (context: PreloadContext, module: string) {
if (context.loadedModules.has(module)) {
return context.loadedModules.get(module);
}
if (context.loadableModules.has(module)) {
const loadedModule = context.loadableModules.get(module)!();
context.loadedModules.set(module, loadedModule);
return loadedModule;
}
throw new Error(`module not found: ${module}`);
}
// Wrap the script into a function executed in global scope. It won't have
// access to the current scope, so we'll expose a few objects as arguments:
//
// - `require`: The `preloadRequire` function
// - `process`: The `preloadProcess` object
// - `Buffer`: Shim of `Buffer` implementation
// - `global`: The window object, which is aliased to `global` by webpack.
function runPreloadScript (context: PreloadContext, preloadSrc: string) {
const globalVariables = [];
const fnParameters = [];
for (const [key, value] of Object.entries(context.exposeGlobals)) {
globalVariables.push(key);
fnParameters.push(value);
}
const preloadWrapperSrc = `(function(require, process, exports, module, ${globalVariables.join(', ')}) {
${preloadSrc}
})`;
// eval in window scope
const preloadFn = context.createPreloadScript(preloadWrapperSrc);
const exports = {};
preloadFn(preloadRequire.bind(null, context), context.process, exports, { exports }, ...fnParameters);
}
/**
* Execute preload scripts within a sandboxed process.
*/
export function executeSandboxedPreloadScripts (context: PreloadContext, preloadScripts: ElectronInternal.PreloadScript[]) {
for (const { filePath, contents, error } of preloadScripts) {
try {
if (contents) {
runPreloadScript(context, contents);
} else if (error) {
throw error;
}
} catch (error) {
console.error(`Unable to load preload script: ${filePath}`);
console.error(error);
ipcRendererInternal.send(IPC_MESSAGES.BROWSER_PRELOAD_ERROR, filePath, error);
}
}
}

View File

@@ -133,7 +133,10 @@ osr_shared_texture_remove_keyed_mutex_on_win_dxgi.patch
feat_allow_usage_of_sccontentsharingpicker_on_supported_platforms.patch
chore_partial_revert_of.patch
fix_software_compositing_infinite_loop.patch
fix_add_method_which_disables_headless_mode_on_native_widget.patch
fix_put_nsvisualeffectview_before_viewscompositorsuperview.patch
refactor_unfilter_unresponsive_events.patch
build_disable_thin_lto_mac.patch
build_add_public_config_simdutf_config.patch
revert_code_health_clean_up_stale_macwebcontentsocclusion.patch
feat_add_signals_when_embedder_cleanup_callbacks_run_for.patch

View File

@@ -0,0 +1,168 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: deepak1556 <hop2deep@gmail.com>
Date: Wed, 29 Jan 2025 17:01:03 +0900
Subject: feat: add signals when embedder cleanup callbacks run for
gin::wrappable
Current setup of finalization callbacks does not work well with
gin_helper::CleanedUpAtExit for wrappables specifically on environment
shutdown leading to UAF in the second pass.
Details at https://github.com/microsoft/vscode/issues/192119#issuecomment-2375851531
The signals exposed in this patch does the following 2 things,
1) Fix weak state of the wrapped object when the finializer callbacks
have not yet been processed
2) Avoid calling into the second pass when the embedder has already
destroyed the wrapped object via CleanedUpAtExit.
This patch is more of a bandaid fix to improve the lifetime
management with existing finalizer callbacks. We should be able to
remove this patch once gin::Wrappable can be managed by V8 Oilpan
Refs https://issues.chromium.org/issues/40210365 which is blocked
on https://issues.chromium.org/issues/42203693
diff --git a/gin/isolate_holder.cc b/gin/isolate_holder.cc
index e5ee2c6b3cb787ff9f8272d4344a1e18c44971e2..22469cf0ab1025eefcf94e2cd351087e52182130 100644
--- a/gin/isolate_holder.cc
+++ b/gin/isolate_holder.cc
@@ -34,6 +34,8 @@ v8::ArrayBuffer::Allocator* g_array_buffer_allocator = nullptr;
const intptr_t* g_reference_table = nullptr;
v8::FatalErrorCallback g_fatal_error_callback = nullptr;
v8::OOMErrorCallback g_oom_error_callback = nullptr;
+bool g_initialized_microtasks_runner = false;
+bool g_destroyed_microtasks_runner = false;
std::unique_ptr<v8::Isolate::CreateParams> getModifiedIsolateParams(
std::unique_ptr<v8::Isolate::CreateParams> params,
@@ -194,10 +196,26 @@ IsolateHolder::getDefaultIsolateParams() {
return params;
}
+// static
+bool IsolateHolder::DestroyedMicrotasksRunner() {
+ return g_initialized_microtasks_runner &&
+ g_destroyed_microtasks_runner;
+}
+
void IsolateHolder::EnableIdleTasks(
std::unique_ptr<V8IdleTaskRunner> idle_task_runner) {
DCHECK(isolate_data_.get());
isolate_data_->EnableIdleTasks(std::move(idle_task_runner));
}
+void IsolateHolder::WillCreateMicrotasksRunner() {
+ DCHECK(!g_initialized_microtasks_runner);
+ g_initialized_microtasks_runner = true;
+}
+
+void IsolateHolder::WillDestroyMicrotasksRunner() {
+ DCHECK(g_initialized_microtasks_runner);
+ g_destroyed_microtasks_runner = true;
+}
+
} // namespace gin
diff --git a/gin/public/isolate_holder.h b/gin/public/isolate_holder.h
index c22b0a7f9af621573e888a518ccdc22293ce07ef..d3e5ced425df54f42534cec5cc0c5bbfb9d79c6c 100644
--- a/gin/public/isolate_holder.h
+++ b/gin/public/isolate_holder.h
@@ -130,6 +130,8 @@ class GIN_EXPORT IsolateHolder {
// Should only be called after v8::IsolateHolder::Initialize() is invoked.
static std::unique_ptr<v8::Isolate::CreateParams> getDefaultIsolateParams();
+ static bool DestroyedMicrotasksRunner();
+
v8::Isolate* isolate() { return isolate_; }
// This method returns if v8::Locker is needed to access isolate.
@@ -143,6 +145,9 @@ class GIN_EXPORT IsolateHolder {
void EnableIdleTasks(std::unique_ptr<V8IdleTaskRunner> idle_task_runner);
+ void WillCreateMicrotasksRunner();
+ void WillDestroyMicrotasksRunner();
+
// This method returns V8IsolateMemoryDumpProvider of this isolate, used for
// testing.
V8IsolateMemoryDumpProvider* isolate_memory_dump_provider_for_testing()
diff --git a/gin/wrappable.cc b/gin/wrappable.cc
index 402355cb836cea14e9ee725a142a4bad44fd5bed..7e7f028dcfb87c7b80adebabac19ced8791f642e 100644
--- a/gin/wrappable.cc
+++ b/gin/wrappable.cc
@@ -13,6 +13,9 @@ namespace gin {
WrappableBase::WrappableBase() = default;
WrappableBase::~WrappableBase() {
+ if (!wrapper_.IsEmpty()) {
+ wrapper_.ClearWeak();
+ }
wrapper_.Reset();
}
@@ -28,15 +31,24 @@ const char* WrappableBase::GetTypeName() {
void WrappableBase::FirstWeakCallback(
const v8::WeakCallbackInfo<WrappableBase>& data) {
WrappableBase* wrappable = data.GetParameter();
- wrappable->dead_ = true;
- wrappable->wrapper_.Reset();
- data.SetSecondPassCallback(SecondWeakCallback);
+ WrappableBase* wrappable_from_field =
+ static_cast<WrappableBase*>(data.GetInternalField(1));
+ if (wrappable && wrappable == wrappable_from_field) {
+ wrappable->dead_ = true;
+ wrappable->wrapper_.Reset();
+ data.SetSecondPassCallback(SecondWeakCallback);
+ }
}
void WrappableBase::SecondWeakCallback(
const v8::WeakCallbackInfo<WrappableBase>& data) {
+ if (IsolateHolder::DestroyedMicrotasksRunner()) {
+ return;
+ }
WrappableBase* wrappable = data.GetParameter();
- delete wrappable;
+ if (wrappable) {
+ delete wrappable;
+ }
}
v8::MaybeLocal<v8::Object> WrappableBase::GetWrapperImpl(v8::Isolate* isolate,
@@ -71,10 +83,16 @@ v8::MaybeLocal<v8::Object> WrappableBase::GetWrapperImpl(v8::Isolate* isolate,
void* values[] = {info, this};
wrapper->SetAlignedPointerInInternalFields(2, indices, values);
wrapper_.Reset(isolate, wrapper);
- wrapper_.SetWeak(this, FirstWeakCallback, v8::WeakCallbackType::kParameter);
+ wrapper_.SetWeak(this, FirstWeakCallback, v8::WeakCallbackType::kInternalFields);
return v8::MaybeLocal<v8::Object>(wrapper);
}
+void WrappableBase::ClearWeak() {
+ if (!wrapper_.IsEmpty()) {
+ wrapper_.ClearWeak();
+ }
+}
+
namespace internal {
void* FromV8Impl(v8::Isolate* isolate, v8::Local<v8::Value> val,
diff --git a/gin/wrappable.h b/gin/wrappable.h
index 4e7115685a5bf6997e78edcc1851e28bd00b1aa2..ca51fe33605e855438e88969e3d3cc734ef4523e 100644
--- a/gin/wrappable.h
+++ b/gin/wrappable.h
@@ -80,6 +80,13 @@ class GIN_EXPORT WrappableBase {
v8::MaybeLocal<v8::Object> GetWrapperImpl(v8::Isolate* isolate,
WrapperInfo* wrapper_info);
+ // Make this wrappable strong again. This is useful when the wrappable is
+ // destroyed outside the finalizer callbacks and we want to avoid scheduling
+ // the weak callbacks if they haven't been scheduled yet.
+ // NOTE!!! this does not prevent finalization callbacks from running if they
+ // have already been processed.
+ void ClearWeak();
+
private:
static void FirstWeakCallback(
const v8::WeakCallbackInfo<WrappableBase>& data);

View File

@@ -14,10 +14,25 @@ It also:
This may be partially upstreamed to Chromium in the future.
diff --git a/ui/gtk/select_file_dialog_linux_gtk.cc b/ui/gtk/select_file_dialog_linux_gtk.cc
index b83f0177a2adb0a19be49684f865941e6708f626..f313c766ddc2b79f082e70138dd566a846f0d923 100644
index b83f0177a2adb0a19be49684f865941e6708f626..a8c7032cfc122b97665c41da9e1191e747b95a33 100644
--- a/ui/gtk/select_file_dialog_linux_gtk.cc
+++ b/ui/gtk/select_file_dialog_linux_gtk.cc
@@ -407,9 +407,11 @@ GtkWidget* SelectFileDialogLinuxGtk::CreateFileOpenHelper(
@@ -259,8 +259,12 @@ void SelectFileDialogLinuxGtk::SelectFileImpl(
case SELECT_EXISTING_FOLDER:
dialog = CreateSelectFolderDialog(type, title_string, default_path,
owning_window);
- connect("response",
- &SelectFileDialogLinuxGtk::OnSelectSingleFolderDialogResponse);
+ if (allow_multiple_selection())
+ connect("response",
+ &SelectFileDialogLinuxGtk::OnSelectMultiFolderDialogResponse);
+ else
+ connect("response",
+ &SelectFileDialogLinuxGtk::OnSelectSingleFolderDialogResponse);
break;
case SELECT_OPEN_FILE:
dialog = CreateFileOpenDialog(title_string, default_path, owning_window);
@@ -407,9 +411,11 @@ GtkWidget* SelectFileDialogLinuxGtk::CreateFileOpenHelper(
const std::string& title,
const base::FilePath& default_path,
gfx::NativeWindow parent) {
@@ -30,7 +45,7 @@ index b83f0177a2adb0a19be49684f865941e6708f626..f313c766ddc2b79f082e70138dd566a8
SetGtkTransientForAura(dialog, parent);
AddFilters(GTK_FILE_CHOOSER(dialog));
@@ -425,6 +427,7 @@ GtkWidget* SelectFileDialogLinuxGtk::CreateFileOpenHelper(
@@ -425,6 +431,7 @@ GtkWidget* SelectFileDialogLinuxGtk::CreateFileOpenHelper(
GtkFileChooserSetCurrentFolder(GTK_FILE_CHOOSER(dialog),
*last_opened_path());
}
@@ -38,7 +53,7 @@ index b83f0177a2adb0a19be49684f865941e6708f626..f313c766ddc2b79f082e70138dd566a8
return dialog;
}
@@ -440,11 +443,15 @@ GtkWidget* SelectFileDialogLinuxGtk::CreateSelectFolderDialog(
@@ -440,11 +447,15 @@ GtkWidget* SelectFileDialogLinuxGtk::CreateSelectFolderDialog(
? l10n_util::GetStringUTF8(IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE)
: l10n_util::GetStringUTF8(IDS_SELECT_FOLDER_DIALOG_TITLE);
}
@@ -59,7 +74,7 @@ index b83f0177a2adb0a19be49684f865941e6708f626..f313c766ddc2b79f082e70138dd566a8
GtkWidget* dialog = GtkFileChooserDialogNew(
title_string.c_str(), nullptr, GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,
@@ -466,7 +473,8 @@ GtkWidget* SelectFileDialogLinuxGtk::CreateSelectFolderDialog(
@@ -466,7 +477,8 @@ GtkWidget* SelectFileDialogLinuxGtk::CreateSelectFolderDialog(
gtk_file_filter_add_mime_type(only_folders, "inode/directory");
gtk_file_filter_add_mime_type(only_folders, "text/directory");
gtk_file_chooser_add_filter(chooser, only_folders);
@@ -69,7 +84,7 @@ index b83f0177a2adb0a19be49684f865941e6708f626..f313c766ddc2b79f082e70138dd566a8
return dialog;
}
@@ -503,10 +511,11 @@ GtkWidget* SelectFileDialogLinuxGtk::CreateSaveAsDialog(
@@ -503,10 +515,11 @@ GtkWidget* SelectFileDialogLinuxGtk::CreateSaveAsDialog(
std::string title_string =
!title.empty() ? title
: l10n_util::GetStringUTF8(IDS_SAVE_AS_DIALOG_TITLE);
@@ -83,7 +98,7 @@ index b83f0177a2adb0a19be49684f865941e6708f626..f313c766ddc2b79f082e70138dd566a8
GTK_RESPONSE_ACCEPT);
SetGtkTransientForAura(dialog, parent);
@@ -532,9 +541,10 @@ GtkWidget* SelectFileDialogLinuxGtk::CreateSaveAsDialog(
@@ -532,9 +545,10 @@ GtkWidget* SelectFileDialogLinuxGtk::CreateSaveAsDialog(
gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog), FALSE);
// Overwrite confirmation is always enabled in GTK4.
if (!GtkCheckVersion(4)) {
@@ -96,6 +111,65 @@ index b83f0177a2adb0a19be49684f865941e6708f626..f313c766ddc2b79f082e70138dd566a8
return dialog;
}
@@ -589,15 +603,29 @@ void SelectFileDialogLinuxGtk::OnSelectSingleFolderDialogResponse(
void SelectFileDialogLinuxGtk::OnSelectMultiFileDialogResponse(
GtkWidget* dialog,
int response_id) {
+ SelectMultiFileHelper(dialog, response_id, false);
+}
+
+void SelectFileDialogLinuxGtk::OnSelectMultiFolderDialogResponse(
+ GtkWidget* dialog,
+ int response_id) {
+ SelectMultiFileHelper(dialog, response_id, true);
+}
+
+void SelectFileDialogLinuxGtk::SelectMultiFileHelper(GtkWidget* dialog,
+ int response_id,
+ bool allow_folder) {
if (IsCancelResponse(response_id)) {
FileNotSelected(dialog);
return;
}
auto filenames = GtkFileChooserGetFilenames(dialog);
- std::erase_if(filenames, [this](const base::FilePath& path) {
- return CallDirectoryExistsOnUIThread(path);
+ std::erase_if(filenames, [this, &allow_folder](const base::FilePath& path) {
+ bool directory_exists = CallDirectoryExistsOnUIThread(path);
+ return !allow_folder && directory_exists;
});
+
if (filenames.empty()) {
FileNotSelected(dialog);
return;
diff --git a/ui/gtk/select_file_dialog_linux_gtk.h b/ui/gtk/select_file_dialog_linux_gtk.h
index 213eaa5ec6d657a659726cb38103e8bd671fe907..f497447c598198bf690758b1d1c5c6fe4112627f 100644
--- a/ui/gtk/select_file_dialog_linux_gtk.h
+++ b/ui/gtk/select_file_dialog_linux_gtk.h
@@ -108,6 +108,12 @@ class SelectFileDialogLinuxGtk : public ui::SelectFileDialogLinux,
gint response_id,
bool allow_folder);
+ // Common function for OnSelectMultiFileDialogResponse and
+ // OnSelectMultiFolderDialogResponse.
+ void SelectMultiFileHelper(GtkWidget* dialog,
+ gint response_id,
+ bool allow_folder);
+
// Common function for CreateFileOpenDialog and CreateMultiFileOpenDialog.
GtkWidget* CreateFileOpenHelper(const std::string& title,
const base::FilePath& default_path,
@@ -122,6 +128,9 @@ class SelectFileDialogLinuxGtk : public ui::SelectFileDialogLinux,
// Callback for when the user responds to a Open Multiple Files dialog.
void OnSelectMultiFileDialogResponse(GtkWidget* dialog, int response_id);
+ // Callback for when the user responds to a Select Multiple Folders dialog.
+ void OnSelectMultiFolderDialogResponse(GtkWidget* dialog, int response_id);
+
// Callback for when the file chooser gets destroyed.
void OnFileChooserDestroy(GtkWidget* dialog);
diff --git a/ui/shell_dialogs/select_file_dialog.h b/ui/shell_dialogs/select_file_dialog.h
index eb3d997598631b220c3566748f23a5cdac3e4692..b4b2f7294ce6e9349a4a8a05f614e93359eca25a 100644
--- a/ui/shell_dialogs/select_file_dialog.h
@@ -186,18 +260,90 @@ index 61683d0eddb04c494ca5e650e7d556b44968ec49..5492456a9138b250e97a5479838bb443
} // namespace ui
diff --git a/ui/shell_dialogs/select_file_dialog_linux_kde.cc b/ui/shell_dialogs/select_file_dialog_linux_kde.cc
index 64a79ebe2e2d21d5a6b4a98042d1cdb7b6edad52..16f2ae01a8d33e6341ed52638e963c340455ebf8 100644
index 64a79ebe2e2d21d5a6b4a98042d1cdb7b6edad52..748c2506781a237641b25b426876be14c8b7ba82 100644
--- a/ui/shell_dialogs/select_file_dialog_linux_kde.cc
+++ b/ui/shell_dialogs/select_file_dialog_linux_kde.cc
@@ -468,7 +468,7 @@ void SelectFileDialogLinuxKde::CreateSelectFolderDialog(
@@ -154,9 +154,20 @@ class SelectFileDialogLinuxKde : public SelectFileDialogLinux {
void OnSelectMultiFileDialogResponse(
gfx::AcceleratedWidget parent,
std::unique_ptr<KDialogOutputParams> results);
+
+ // Common function for OnSelectSingleFolderDialogResponse and
+ // OnSelectMultiFileDialogResponse.
+ void SelectMultiFileDialogHelper(
+ bool allow_folder,
+ gfx::AcceleratedWidget parent,
+ std::unique_ptr<KDialogOutputParams> results);
+
void OnSelectSingleFolderDialogResponse(
gfx::AcceleratedWidget parent,
std::unique_ptr<KDialogOutputParams> results);
+ void OnSelectMultiFolderDialogResponse(
+ gfx::AcceleratedWidget parent,
+ std::unique_ptr<KDialogOutputParams> results);
// Should be either DESKTOP_ENVIRONMENT_KDE3, KDE4, KDE5, or KDE6.
base::nix::DesktopEnvironment desktop_;
@@ -461,6 +472,7 @@ void SelectFileDialogLinuxKde::CreateSelectFolderDialog(
int title_message_id = (type == SELECT_UPLOAD_FOLDER)
? IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE
: IDS_SELECT_FOLDER_DIALOG_TITLE;
+ bool multiple_selection = allow_multiple_selection();
pipe_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE,
base::BindOnce(
@@ -468,10 +480,12 @@ void SelectFileDialogLinuxKde::CreateSelectFolderDialog(
KDialogParams(
"--getexistingdirectory", GetTitle(title, title_message_id),
default_path.empty() ? *last_opened_path() : default_path, parent,
- false, false)),
+ false, allow_multiple_selection())),
+ false, multiple_selection)),
base::BindOnce(
&SelectFileDialogLinuxKde::OnSelectSingleFolderDialogResponse, this,
parent));
- &SelectFileDialogLinuxKde::OnSelectSingleFolderDialogResponse, this,
- parent));
+ multiple_selection
+ ? &SelectFileDialogLinuxKde::OnSelectMultiFolderDialogResponse
+ : &SelectFileDialogLinuxKde::OnSelectSingleFolderDialogResponse,
+ this, parent));
}
void SelectFileDialogLinuxKde::CreateFileOpenDialog(
@@ -561,7 +575,8 @@ void SelectFileDialogLinuxKde::OnSelectSingleFolderDialogResponse(
SelectSingleFileHelper(true, std::move(results));
}
-void SelectFileDialogLinuxKde::OnSelectMultiFileDialogResponse(
+void SelectFileDialogLinuxKde::SelectMultiFileDialogHelper(
+ bool allow_folder,
gfx::AcceleratedWidget parent,
std::unique_ptr<KDialogOutputParams> results) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
@@ -579,7 +594,7 @@ void SelectFileDialogLinuxKde::OnSelectMultiFileDialogResponse(
base::SplitStringPiece(results->output, "\n", base::KEEP_WHITESPACE,
base::SPLIT_WANT_NONEMPTY)) {
base::FilePath path(line);
- if (CallDirectoryExistsOnUIThread(path))
+ if (!allow_folder && CallDirectoryExistsOnUIThread(path))
continue;
filenames_fp.push_back(path);
}
@@ -591,4 +606,16 @@ void SelectFileDialogLinuxKde::OnSelectMultiFileDialogResponse(
MultiFilesSelected(filenames_fp);
}
+void SelectFileDialogLinuxKde::OnSelectMultiFolderDialogResponse(
+ gfx::AcceleratedWidget parent,
+ std::unique_ptr<KDialogOutputParams> results) {
+ SelectMultiFileDialogHelper(true, parent, std::move(results));
+}
+
+void SelectFileDialogLinuxKde::OnSelectMultiFileDialogResponse(
+ gfx::AcceleratedWidget parent,
+ std::unique_ptr<KDialogOutputParams> results) {
+ SelectMultiFileDialogHelper(false, parent, std::move(results));
+}
+
} // namespace ui
diff --git a/ui/shell_dialogs/select_file_dialog_linux_portal.cc b/ui/shell_dialogs/select_file_dialog_linux_portal.cc
index 9780c80ffff7bdb715a9adcb656e5d33be974db6..cf6edf5c68a8e2f8ffda119b58c6283bc43199c0 100644
--- a/ui/shell_dialogs/select_file_dialog_linux_portal.cc

View File

@@ -0,0 +1,26 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Cezary Kulakowski <cezary@openfin.co>
Date: Mon, 22 Jul 2024 16:23:13 +0200
Subject: fix: add method which disables headless mode on native widget
We need this method as we create window in headless mode and we
switch it back to normal mode only after inital paint is done in
order to get some events like WebContents.beginFrameSubscription.
If we don't set `is_headless_` to false then some child windows
e.g. autofill popups will be created in headless mode leading to
ui problems (like dissapearing popup during typing in html's
input list.
diff --git a/ui/views/widget/widget.h b/ui/views/widget/widget.h
index 30d0ea6633cb0f7f9aab37951a38be9b0482a12a..734e91e6d50c8d3afd20b39167c6254e934e7c1e 100644
--- a/ui/views/widget/widget.h
+++ b/ui/views/widget/widget.h
@@ -1144,6 +1144,8 @@ class VIEWS_EXPORT Widget : public internal::NativeWidgetDelegate,
// True if widget was created in headless mode.
bool is_headless() const { return is_headless_; }
+ void DisableHeadlessMode() { is_headless_ = false; }
+
// True if the window size will follow the content preferred size.
bool is_autosized() const { return is_autosized_; }

View File

@@ -0,0 +1,36 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Micha=C5=82=20Pichli=C5=84ski?=
<michal.pichlinski@openfin.co>
Date: Tue, 29 Oct 2024 21:16:29 +0100
Subject: fix: Put NSVisualEffectView before ViewsCompositorSuperview
Upstreamed at https://chromium-review.googlesource.com/c/chromium/src/+/6030552
Otherwise when using `vibrancy` in `BrowserWindow` NSVisualEffectView
will hide content displayed by the compositor.
diff --git a/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm b/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm
index 07c3997e6565cf77362ee73959c4d21da4fefe96..3353a7847df90b58eec34ea4d6ff8fb19617f5cc 100644
--- a/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm
+++ b/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm
@@ -223,8 +223,19 @@ NSComparisonResult SubviewSorter(__kindof NSView* lhs,
void* rank_as_void) {
DCHECK_NE(lhs, rhs);
- if ([lhs isKindOfClass:[ViewsCompositorSuperview class]])
+
+ // Put NSVisualEffectView before ViewsCompositorSuperview otherwise when using
+ // `vibrancy` in `BrowserWindow` NSVisualEffectView will hide content
+ // displayed by the compositor.
+ if ([lhs isKindOfClass:[NSVisualEffectView class]]) {
return NSOrderedAscending;
+ }
+ if ([lhs isKindOfClass:[ViewsCompositorSuperview class]]) {
+ if ([rhs isKindOfClass:[NSVisualEffectView class]]) {
+ return NSOrderedDescending;
+ }
+ return NSOrderedAscending;
+ }
const RankMap* rank = static_cast<const RankMap*>(rank_as_void);
auto left_rank = rank->find(lhs);

View File

@@ -604,6 +604,19 @@ index 402be34ab888cdf834d0fb65de0832e9a8021ced..82ddc92a35d824926c30279e660cc4e8
}
#if BUILDFLAG(IS_CHROMEOS)
diff --git a/chrome/browser/printing/printer_query_oop.cc b/chrome/browser/printing/printer_query_oop.cc
index e271d17b3261c47f3dbeaf9be0b3c4229ee27181..ed19764250d9125915f0f948896acd7eae7911a6 100644
--- a/chrome/browser/printing/printer_query_oop.cc
+++ b/chrome/browser/printing/printer_query_oop.cc
@@ -127,7 +127,7 @@ void PrinterQueryOop::OnDidAskUserForSettings(
std::unique_ptr<PrintSettings> new_settings,
mojom::ResultCode result) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- if (result == mojom::ResultCode::kSuccess) {
+ if (result == mojom::ResultCode::kSuccess && query_with_ui_client_id_) {
// Want the same PrintBackend service as the query so that we use the same
// device context.
print_document_client_id_ =
diff --git a/components/printing/browser/print_manager.cc b/components/printing/browser/print_manager.cc
index 21c81377d32ae8d4185598a7eba88ed1d2063ef0..0767f4e9369e926b1cea99178c1a1975941f1765 100644
--- a/components/printing/browser/print_manager.cc
@@ -653,7 +666,7 @@ index 6809c4576c71bc1e1a6ad4e0a37707272a9a10f4..3aad10424a6a31dab2ca393d00149ec6
PrintingFailed(int32 cookie, PrintFailureReason reason);
diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc
index 18a8d64167b66d0de67c0c89779af90814b827c6..33079deee8720a447e2b4e1f3601542b59e1cf16 100644
index 18a8d64167b66d0de67c0c89779af90814b827c6..52b95469f0392fbb108bef3f6d5ea0f8a81410fd 100644
--- a/components/printing/renderer/print_render_frame_helper.cc
+++ b/components/printing/renderer/print_render_frame_helper.cc
@@ -52,6 +52,7 @@
@@ -771,7 +784,7 @@ index 18a8d64167b66d0de67c0c89779af90814b827c6..33079deee8720a447e2b4e1f3601542b
// Check if `this` is still valid.
if (!self)
return;
@@ -2359,29 +2374,37 @@ void PrintRenderFrameHelper::IPCProcessed() {
@@ -2359,29 +2374,43 @@ void PrintRenderFrameHelper::IPCProcessed() {
}
bool PrintRenderFrameHelper::InitPrintSettings(blink::WebLocalFrame* frame,
@@ -803,10 +816,18 @@ index 18a8d64167b66d0de67c0c89779af90814b827c6..33079deee8720a447e2b4e1f3601542b
bool center_on_paper = !IsPrintingPdfFrame(frame, node);
- settings.params->print_scaling_option =
+ settings->params->print_scaling_option =
center_on_paper ? mojom::PrintScalingOption::kCenterShrinkToFitPaper
: mojom::PrintScalingOption::kSourceSize;
- center_on_paper ? mojom::PrintScalingOption::kCenterShrinkToFitPaper
- : mojom::PrintScalingOption::kSourceSize;
- RecordDebugEvent(settings.params->printed_doc_type ==
+ bool silent = new_settings.FindBool("silent").value_or(false);
+ if (silent) {
+ settings->params->print_scaling_option = mojom::PrintScalingOption::kFitToPrintableArea;
+ } else {
+ settings->params->print_scaling_option =
+ center_on_paper ? mojom::PrintScalingOption::kCenterShrinkToFitPaper
+ : mojom::PrintScalingOption::kSourceSize;
+ }
+
+ RecordDebugEvent(settings->params->printed_doc_type ==
mojom::SkiaDocumentType::kMSKP
? DebugEvent::kSetPrintSettings5

View File

@@ -369,9 +369,6 @@ def main():
patch_file.close()
os.unlink(patch_file.name)
else:
print(
'To patch these files, run:',
f"$ git apply {patch_file.name}", sep='\n')
filename=patch_file.name
print(f"\nTo patch these files, run:\n$ git apply {filename}\n")

View File

@@ -250,8 +250,8 @@ int NodeMain() {
uint64_t env_flags = node::EnvironmentFlags::kDefaultFlags |
node::EnvironmentFlags::kHideConsoleWindows;
env = node::CreateEnvironment(
isolate_data, isolate->GetCurrentContext(), result->args(),
env = electron::util::CreateEnvironment(
isolate, isolate_data, isolate->GetCurrentContext(), result->args(),
result->exec_args(),
static_cast<node::EnvironmentFlags::Flags>(env_flags));
CHECK_NE(nullptr, env);

View File

@@ -5,6 +5,7 @@
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <utility>
#include "base/files/file_util.h"
@@ -20,6 +21,7 @@
#include "shell/common/node_includes.h"
using content::TracingController;
using namespace std::literals;
namespace gin {
@@ -69,9 +71,9 @@ void StopTracing(gin_helper::Promise<base::FilePath> promise,
std::optional<base::FilePath> file_path) {
auto resolve_or_reject = base::BindOnce(
[](gin_helper::Promise<base::FilePath> promise,
const base::FilePath& path, std::optional<std::string> error) {
if (error) {
promise.RejectWithErrorMessage(error.value());
const base::FilePath& path, const std::string_view error) {
if (!std::empty(error)) {
promise.RejectWithErrorMessage(error);
} else {
promise.Resolve(path);
}
@@ -81,21 +83,17 @@ void StopTracing(gin_helper::Promise<base::FilePath> promise,
auto* instance = TracingController::GetInstance();
if (!instance->IsTracing()) {
std::move(resolve_or_reject)
.Run(std::make_optional(
"Failed to stop tracing - no trace in progress"));
.Run("Failed to stop tracing - no trace in progress"sv);
} else if (file_path) {
auto split_callback = base::SplitOnceCallback(std::move(resolve_or_reject));
auto endpoint = TracingController::CreateFileEndpoint(
*file_path,
base::BindOnce(std::move(split_callback.first), std::nullopt));
*file_path, base::BindOnce(std::move(split_callback.first), ""sv));
if (!instance->StopTracing(endpoint)) {
std::move(split_callback.second)
.Run(std::make_optional("Failed to stop tracing"));
std::move(split_callback.second).Run("Failed to stop tracing"sv);
}
} else {
std::move(resolve_or_reject)
.Run(std::make_optional(
"Failed to create temporary file for trace data"));
.Run("Failed to create temporary file for trace data"sv);
}
}

View File

@@ -236,6 +236,10 @@ const char* Notification::GetTypeName() {
return GetClassName();
}
void Notification::WillBeDestroyed() {
ClearWeak();
}
} // namespace electron::api
namespace {

View File

@@ -57,6 +57,9 @@ class Notification final : public gin::Wrappable<Notification>,
static gin::WrapperInfo kWrapperInfo;
const char* GetTypeName() override;
// gin_helper::CleanedUpAtExit
void WillBeDestroyed() override;
// disable copy
Notification(const Notification&) = delete;
Notification& operator=(const Notification&) = delete;

View File

@@ -13,11 +13,18 @@
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "shell/browser/api/electron_api_service_worker_main.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/javascript_environment.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/service_worker_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/node_util.h"
using ServiceWorkerStatus =
content::ServiceWorkerRunningInfo::ServiceWorkerVersionStatus;
namespace electron::api {
@@ -72,8 +79,8 @@ gin::WrapperInfo ServiceWorkerContext::kWrapperInfo = {gin::kEmbedderNativeGin};
ServiceWorkerContext::ServiceWorkerContext(
v8::Isolate* isolate,
ElectronBrowserContext* browser_context) {
service_worker_context_ =
browser_context->GetDefaultStoragePartition()->GetServiceWorkerContext();
storage_partition_ = browser_context->GetDefaultStoragePartition();
service_worker_context_ = storage_partition_->GetServiceWorkerContext();
service_worker_context_->AddObserver(this);
}
@@ -81,6 +88,23 @@ ServiceWorkerContext::~ServiceWorkerContext() {
service_worker_context_->RemoveObserver(this);
}
void ServiceWorkerContext::OnRunningStatusChanged(
int64_t version_id,
blink::EmbeddedWorkerStatus running_status) {
ServiceWorkerMain* worker =
ServiceWorkerMain::FromVersionID(version_id, storage_partition_);
if (worker)
worker->OnRunningStatusChanged(running_status);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
EmitWithoutEvent("running-status-changed",
gin::DataObjectBuilder(isolate)
.Set("versionId", version_id)
.Set("runningStatus", running_status)
.Build());
}
void ServiceWorkerContext::OnReportConsoleMessage(
int64_t version_id,
const GURL& scope,
@@ -105,6 +129,32 @@ void ServiceWorkerContext::OnRegistrationCompleted(const GURL& scope) {
gin::DataObjectBuilder(isolate).Set("scope", scope).Build());
}
void ServiceWorkerContext::OnVersionRedundant(int64_t version_id,
const GURL& scope) {
ServiceWorkerMain* worker =
ServiceWorkerMain::FromVersionID(version_id, storage_partition_);
if (worker)
worker->OnVersionRedundant();
}
void ServiceWorkerContext::OnVersionStartingRunning(int64_t version_id) {
OnRunningStatusChanged(version_id, blink::EmbeddedWorkerStatus::kStarting);
}
void ServiceWorkerContext::OnVersionStartedRunning(
int64_t version_id,
const content::ServiceWorkerRunningInfo& running_info) {
OnRunningStatusChanged(version_id, blink::EmbeddedWorkerStatus::kRunning);
}
void ServiceWorkerContext::OnVersionStoppingRunning(int64_t version_id) {
OnRunningStatusChanged(version_id, blink::EmbeddedWorkerStatus::kStopping);
}
void ServiceWorkerContext::OnVersionStoppedRunning(int64_t version_id) {
OnRunningStatusChanged(version_id, blink::EmbeddedWorkerStatus::kStopped);
}
void ServiceWorkerContext::OnDestruct(content::ServiceWorkerContext* context) {
if (context == service_worker_context_) {
delete this;
@@ -124,7 +174,7 @@ v8::Local<v8::Value> ServiceWorkerContext::GetAllRunningWorkerInfo(
return builder.Build();
}
v8::Local<v8::Value> ServiceWorkerContext::GetWorkerInfoFromID(
v8::Local<v8::Value> ServiceWorkerContext::GetInfoFromVersionID(
gin_helper::ErrorThrower thrower,
int64_t version_id) {
const base::flat_map<int64_t, content::ServiceWorkerRunningInfo>& info_map =
@@ -138,6 +188,87 @@ v8::Local<v8::Value> ServiceWorkerContext::GetWorkerInfoFromID(
std::move(iter->second));
}
v8::Local<v8::Value> ServiceWorkerContext::GetFromVersionID(
gin_helper::ErrorThrower thrower,
int64_t version_id) {
util::EmitWarning(thrower.isolate(),
"The session.serviceWorkers.getFromVersionID API is "
"deprecated, use "
"session.serviceWorkers.getInfoFromVersionID instead.",
"ServiceWorkersDeprecateGetFromVersionID");
return GetInfoFromVersionID(thrower, version_id);
}
v8::Local<v8::Value> ServiceWorkerContext::GetWorkerFromVersionID(
v8::Isolate* isolate,
int64_t version_id) {
return ServiceWorkerMain::From(isolate, service_worker_context_,
storage_partition_, version_id)
.ToV8();
}
gin::Handle<ServiceWorkerMain>
ServiceWorkerContext::GetWorkerFromVersionIDIfExists(v8::Isolate* isolate,
int64_t version_id) {
ServiceWorkerMain* worker =
ServiceWorkerMain::FromVersionID(version_id, storage_partition_);
if (!worker)
return gin::Handle<ServiceWorkerMain>();
return gin::CreateHandle(isolate, worker);
}
v8::Local<v8::Promise> ServiceWorkerContext::StartWorkerForScope(
v8::Isolate* isolate,
GURL scope) {
auto shared_promise =
std::make_shared<gin_helper::Promise<v8::Local<v8::Value>>>(isolate);
v8::Local<v8::Promise> handle = shared_promise->GetHandle();
blink::StorageKey storage_key =
blink::StorageKey::CreateFirstParty(url::Origin::Create(scope));
service_worker_context_->StartWorkerForScope(
scope, storage_key,
base::BindOnce(&ServiceWorkerContext::DidStartWorkerForScope,
weak_ptr_factory_.GetWeakPtr(), shared_promise),
base::BindOnce(&ServiceWorkerContext::DidFailToStartWorkerForScope,
weak_ptr_factory_.GetWeakPtr(), shared_promise));
return handle;
}
void ServiceWorkerContext::DidStartWorkerForScope(
std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>> shared_promise,
int64_t version_id,
int process_id,
int thread_id) {
v8::Isolate* isolate = shared_promise->isolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Value> service_worker_main =
GetWorkerFromVersionID(isolate, version_id);
shared_promise->Resolve(service_worker_main);
shared_promise.reset();
}
void ServiceWorkerContext::DidFailToStartWorkerForScope(
std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>> shared_promise,
content::StatusCodeResponse status) {
shared_promise->RejectWithErrorMessage("Failed to start service worker.");
shared_promise.reset();
}
v8::Local<v8::Promise> ServiceWorkerContext::StopAllWorkers(
v8::Isolate* isolate) {
auto promise = gin_helper::Promise<void>(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
service_worker_context_->StopAllServiceWorkers(base::BindOnce(
[](gin_helper::Promise<void> promise) { promise.Resolve(); },
std::move(promise)));
return handle;
}
// static
gin::Handle<ServiceWorkerContext> ServiceWorkerContext::Create(
v8::Isolate* isolate,
@@ -153,8 +284,16 @@ gin::ObjectTemplateBuilder ServiceWorkerContext::GetObjectTemplateBuilder(
ServiceWorkerContext>::GetObjectTemplateBuilder(isolate)
.SetMethod("getAllRunning",
&ServiceWorkerContext::GetAllRunningWorkerInfo)
.SetMethod("getFromVersionID",
&ServiceWorkerContext::GetWorkerInfoFromID);
.SetMethod("getFromVersionID", &ServiceWorkerContext::GetFromVersionID)
.SetMethod("getInfoFromVersionID",
&ServiceWorkerContext::GetInfoFromVersionID)
.SetMethod("getWorkerFromVersionID",
&ServiceWorkerContext::GetWorkerFromVersionID)
.SetMethod("_getWorkerFromVersionIDIfExists",
&ServiceWorkerContext::GetWorkerFromVersionIDIfExists)
.SetMethod("startWorkerForScope",
&ServiceWorkerContext::StartWorkerForScope)
.SetMethod("_stopAllWorkers", &ServiceWorkerContext::StopAllWorkers);
}
const char* ServiceWorkerContext::GetTypeName() {

View File

@@ -10,18 +10,30 @@
#include "content/public/browser/service_worker_context_observer.h"
#include "gin/wrappable.h"
#include "shell/browser/event_emitter_mixin.h"
#include "third_party/blink/public/common/service_worker/embedded_worker_status.h"
namespace content {
class StoragePartition;
}
namespace gin {
template <typename T>
class Handle;
} // namespace gin
namespace gin_helper {
template <typename T>
class Promise;
} // namespace gin_helper
namespace electron {
class ElectronBrowserContext;
namespace api {
class ServiceWorkerMain;
class ServiceWorkerContext final
: public gin::Wrappable<ServiceWorkerContext>,
public gin_helper::EventEmitterMixin<ServiceWorkerContext>,
@@ -32,14 +44,39 @@ class ServiceWorkerContext final
ElectronBrowserContext* browser_context);
v8::Local<v8::Value> GetAllRunningWorkerInfo(v8::Isolate* isolate);
v8::Local<v8::Value> GetWorkerInfoFromID(gin_helper::ErrorThrower thrower,
int64_t version_id);
v8::Local<v8::Value> GetInfoFromVersionID(gin_helper::ErrorThrower thrower,
int64_t version_id);
v8::Local<v8::Value> GetFromVersionID(gin_helper::ErrorThrower thrower,
int64_t version_id);
v8::Local<v8::Value> GetWorkerFromVersionID(v8::Isolate* isolate,
int64_t version_id);
gin::Handle<ServiceWorkerMain> GetWorkerFromVersionIDIfExists(
v8::Isolate* isolate,
int64_t version_id);
v8::Local<v8::Promise> StartWorkerForScope(v8::Isolate* isolate, GURL scope);
void DidStartWorkerForScope(
std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>> shared_promise,
int64_t version_id,
int process_id,
int thread_id);
void DidFailToStartWorkerForScope(
std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>> shared_promise,
content::StatusCodeResponse status);
void StopWorkersForScope(GURL scope);
v8::Local<v8::Promise> StopAllWorkers(v8::Isolate* isolate);
// content::ServiceWorkerContextObserver
void OnReportConsoleMessage(int64_t version_id,
const GURL& scope,
const content::ConsoleMessage& message) override;
void OnRegistrationCompleted(const GURL& scope) override;
void OnVersionStartingRunning(int64_t version_id) override;
void OnVersionStartedRunning(
int64_t version_id,
const content::ServiceWorkerRunningInfo& running_info) override;
void OnVersionStoppingRunning(int64_t version_id) override;
void OnVersionStoppedRunning(int64_t version_id) override;
void OnVersionRedundant(int64_t version_id, const GURL& scope) override;
void OnDestruct(content::ServiceWorkerContext* context) override;
// gin::Wrappable
@@ -58,8 +95,15 @@ class ServiceWorkerContext final
~ServiceWorkerContext() override;
private:
void OnRunningStatusChanged(int64_t version_id,
blink::EmbeddedWorkerStatus running_status);
raw_ptr<content::ServiceWorkerContext> service_worker_context_;
// Service worker registration and versions are unique to a storage partition.
// Keep a reference to the storage partition to be used for lookups.
raw_ptr<content::StoragePartition> storage_partition_;
base::WeakPtrFactory<ServiceWorkerContext> weak_ptr_factory_{this};
};

View File

@@ -0,0 +1,359 @@
// Copyright (c) 2025 Salesforce, 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_service_worker_main.h"
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "base/logging.h"
#include "base/no_destructor.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h" // nogncheck
#include "content/browser/service_worker/service_worker_version.h" // nogncheck
#include "electron/shell/common/api/api.mojom.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/javascript_environment.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/node_includes.h"
#include "shell/common/v8_util.h"
namespace {
// Use private API to get the live version of the service worker. This will
// exist while in starting, stopping, or stopped running status.
content::ServiceWorkerVersion* GetLiveVersion(
content::ServiceWorkerContext* service_worker_context,
int64_t version_id) {
auto* wrapper = static_cast<content::ServiceWorkerContextWrapper*>(
service_worker_context);
return wrapper->GetLiveVersion(version_id);
}
// Get a public ServiceWorkerVersionBaseInfo object directly from the service
// worker.
std::optional<content::ServiceWorkerVersionBaseInfo> GetLiveVersionInfo(
content::ServiceWorkerContext* service_worker_context,
int64_t version_id) {
auto* version = GetLiveVersion(service_worker_context, version_id);
if (version) {
return version->GetInfo();
}
return std::nullopt;
}
} // namespace
namespace electron::api {
// ServiceWorkerKey -> ServiceWorkerMain*
typedef std::unordered_map<ServiceWorkerKey,
ServiceWorkerMain*,
ServiceWorkerKey::Hasher>
VersionIdMap;
VersionIdMap& GetVersionIdMap() {
static base::NoDestructor<VersionIdMap> instance;
return *instance;
}
ServiceWorkerMain* FromServiceWorkerKey(const ServiceWorkerKey& key) {
VersionIdMap& version_map = GetVersionIdMap();
auto iter = version_map.find(key);
auto* service_worker = iter == version_map.end() ? nullptr : iter->second;
return service_worker;
}
// static
ServiceWorkerMain* ServiceWorkerMain::FromVersionID(
int64_t version_id,
const content::StoragePartition* storage_partition) {
ServiceWorkerKey key(version_id, storage_partition);
return FromServiceWorkerKey(key);
}
gin::WrapperInfo ServiceWorkerMain::kWrapperInfo = {gin::kEmbedderNativeGin};
ServiceWorkerMain::ServiceWorkerMain(content::ServiceWorkerContext* sw_context,
int64_t version_id,
const ServiceWorkerKey& key)
: version_id_(version_id), key_(key), service_worker_context_(sw_context) {
GetVersionIdMap().emplace(key_, this);
InvalidateVersionInfo();
}
ServiceWorkerMain::~ServiceWorkerMain() {
Destroy();
}
void ServiceWorkerMain::Destroy() {
version_destroyed_ = true;
InvalidateVersionInfo();
MaybeDisconnectRemote();
GetVersionIdMap().erase(key_);
Unpin();
}
void ServiceWorkerMain::MaybeDisconnectRemote() {
if (remote_.is_bound() &&
(version_destroyed_ ||
(!service_worker_context_->IsLiveStartingServiceWorker(version_id_) &&
!service_worker_context_->IsLiveRunningServiceWorker(version_id_)))) {
remote_.reset();
}
}
mojom::ElectronRenderer* ServiceWorkerMain::GetRendererApi() {
if (!remote_.is_bound()) {
if (!service_worker_context_->IsLiveRunningServiceWorker(version_id_)) {
return nullptr;
}
service_worker_context_->GetRemoteAssociatedInterfaces(version_id_)
.GetInterface(&remote_);
}
return remote_.get();
}
void ServiceWorkerMain::Send(v8::Isolate* isolate,
bool internal,
const std::string& channel,
v8::Local<v8::Value> args) {
blink::CloneableMessage message;
if (!gin::ConvertFromV8(isolate, args, &message)) {
isolate->ThrowException(v8::Exception::Error(
gin::StringToV8(isolate, "Failed to serialize arguments")));
return;
}
auto* renderer_api_remote = GetRendererApi();
if (!renderer_api_remote) {
return;
}
renderer_api_remote->Message(internal, channel, std::move(message));
}
void ServiceWorkerMain::InvalidateVersionInfo() {
if (version_info_ != nullptr) {
version_info_.reset();
}
if (version_destroyed_)
return;
auto version_info = GetLiveVersionInfo(service_worker_context_, version_id_);
if (version_info) {
version_info_ =
std::make_unique<content::ServiceWorkerVersionBaseInfo>(*version_info);
} else {
// When ServiceWorkerContextCore::RemoveLiveVersion is called, it posts a
// task to notify that the service worker has stopped. At this point, the
// live version will no longer exist.
Destroy();
}
}
void ServiceWorkerMain::OnRunningStatusChanged(
blink::EmbeddedWorkerStatus running_status) {
// Disconnect remote when content::ServiceWorkerHost has terminated.
MaybeDisconnectRemote();
InvalidateVersionInfo();
// Redundant worker has been marked for deletion. Now that it's stopped, let's
// destroy our wrapper.
if (redundant_ && running_status == blink::EmbeddedWorkerStatus::kStopped) {
Destroy();
}
}
void ServiceWorkerMain::OnVersionRedundant() {
// Redundant service workers have been either unregistered or replaced. A new
// ServiceWorkerMain will need to be created.
// Set internal state to mark it for deletion once it has fully stopped.
redundant_ = true;
}
bool ServiceWorkerMain::IsDestroyed() const {
return version_destroyed_;
}
const blink::StorageKey ServiceWorkerMain::GetStorageKey() {
GURL scope = version_info_ ? version_info()->scope : GURL::EmptyGURL();
return blink::StorageKey::CreateFirstParty(url::Origin::Create(scope));
}
gin_helper::Dictionary ServiceWorkerMain::StartExternalRequest(
v8::Isolate* isolate,
bool has_timeout) {
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
if (version_destroyed_) {
isolate->ThrowException(v8::Exception::TypeError(
gin::StringToV8(isolate, "ServiceWorkerMain is destroyed")));
return details;
}
auto request_uuid = base::Uuid::GenerateRandomV4();
auto timeout_type =
has_timeout
? content::ServiceWorkerExternalRequestTimeoutType::kDefault
: content::ServiceWorkerExternalRequestTimeoutType::kDoesNotTimeout;
content::ServiceWorkerExternalRequestResult start_result =
service_worker_context_->StartingExternalRequest(
version_id_, timeout_type, request_uuid);
details.Set("id", request_uuid.AsLowercaseString());
details.Set("ok",
start_result == content::ServiceWorkerExternalRequestResult::kOk);
return details;
}
void ServiceWorkerMain::FinishExternalRequest(v8::Isolate* isolate,
std::string uuid) {
base::Uuid request_uuid = base::Uuid::ParseLowercase(uuid);
if (!request_uuid.is_valid()) {
isolate->ThrowException(v8::Exception::TypeError(
gin::StringToV8(isolate, "Invalid external request UUID")));
return;
}
DCHECK(service_worker_context_);
if (!service_worker_context_)
return;
content::ServiceWorkerExternalRequestResult result =
service_worker_context_->FinishedExternalRequest(version_id_,
request_uuid);
std::string error;
switch (result) {
case content::ServiceWorkerExternalRequestResult::kOk:
break;
case content::ServiceWorkerExternalRequestResult::kBadRequestId:
error = "Unknown external request UUID";
break;
case content::ServiceWorkerExternalRequestResult::kWorkerNotRunning:
error = "Service worker is no longer running";
break;
case content::ServiceWorkerExternalRequestResult::kWorkerNotFound:
error = "Service worker was not found";
break;
case content::ServiceWorkerExternalRequestResult::kNullContext:
default:
error = "Service worker context is unavailable and may be shutting down";
break;
}
if (!error.empty()) {
isolate->ThrowException(
v8::Exception::TypeError(gin::StringToV8(isolate, error)));
}
}
size_t ServiceWorkerMain::CountExternalRequestsForTest() {
if (version_destroyed_)
return 0;
auto& storage_key = GetStorageKey();
return service_worker_context_->CountExternalRequestsForTest(storage_key);
}
int64_t ServiceWorkerMain::VersionID() const {
return version_id_;
}
GURL ServiceWorkerMain::ScopeURL() const {
if (version_destroyed_)
return GURL::EmptyGURL();
return version_info()->scope;
}
// static
gin::Handle<ServiceWorkerMain> ServiceWorkerMain::New(v8::Isolate* isolate) {
return gin::Handle<ServiceWorkerMain>();
}
// static
gin::Handle<ServiceWorkerMain> ServiceWorkerMain::From(
v8::Isolate* isolate,
content::ServiceWorkerContext* sw_context,
const content::StoragePartition* storage_partition,
int64_t version_id) {
ServiceWorkerKey service_worker_key(version_id, storage_partition);
auto* service_worker = FromServiceWorkerKey(service_worker_key);
if (service_worker)
return gin::CreateHandle(isolate, service_worker);
// Ensure ServiceWorkerVersion exists and is not redundant (pending deletion)
auto* live_version = GetLiveVersion(sw_context, version_id);
if (!live_version || live_version->is_redundant()) {
return gin::Handle<ServiceWorkerMain>();
}
auto handle = gin::CreateHandle(
isolate,
new ServiceWorkerMain(sw_context, version_id, service_worker_key));
// Prevent garbage collection of worker until it has been deleted internally.
handle->Pin(isolate);
return handle;
}
// static
void ServiceWorkerMain::FillObjectTemplate(
v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin_helper::ObjectTemplateBuilder(isolate, templ)
.SetMethod("_send", &ServiceWorkerMain::Send)
.SetMethod("isDestroyed", &ServiceWorkerMain::IsDestroyed)
.SetMethod("_startExternalRequest",
&ServiceWorkerMain::StartExternalRequest)
.SetMethod("_finishExternalRequest",
&ServiceWorkerMain::FinishExternalRequest)
.SetMethod("_countExternalRequests",
&ServiceWorkerMain::CountExternalRequestsForTest)
.SetProperty("versionId", &ServiceWorkerMain::VersionID)
.SetProperty("scope", &ServiceWorkerMain::ScopeURL)
.Build();
}
const char* ServiceWorkerMain::GetTypeName() {
return GetClassName();
}
} // namespace electron::api
namespace {
using electron::api::ServiceWorkerMain;
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("ServiceWorkerMain", ServiceWorkerMain::GetConstructor(context));
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_service_worker_main,
Initialize)

View File

@@ -0,0 +1,178 @@
// Copyright (c) 2025 Salesforce, 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_SERVICE_WORKER_MAIN_H_
#define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SERVICE_WORKER_MAIN_H_
#include <optional>
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/process/process.h"
#include "content/public/browser/global_routing_id.h"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/service_worker_version_base_info.h"
#include "gin/wrappable.h"
#include "mojo/public/cpp/bindings/associated_receiver.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 "shell/browser/event_emitter_mixin.h"
#include "shell/common/api/api.mojom.h"
#include "shell/common/gin_helper/constructible.h"
#include "shell/common/gin_helper/pinnable.h"
#include "third_party/blink/public/common/service_worker/embedded_worker_status.h"
class GURL;
namespace content {
class StoragePartition;
}
namespace gin {
class Arguments;
} // namespace gin
namespace gin_helper {
class Dictionary;
template <typename T>
class Handle;
template <typename T>
class Promise;
} // namespace gin_helper
namespace electron::api {
// Key to uniquely identify a ServiceWorkerMain by its Version ID within the
// associated StoragePartition.
struct ServiceWorkerKey {
int64_t version_id;
raw_ptr<const content::StoragePartition> storage_partition;
ServiceWorkerKey(int64_t id, const content::StoragePartition* partition)
: version_id(id), storage_partition(partition) {}
bool operator<(const ServiceWorkerKey& other) const {
return std::tie(version_id, storage_partition) <
std::tie(other.version_id, other.storage_partition);
}
bool operator==(const ServiceWorkerKey& other) const {
return version_id == other.version_id &&
storage_partition == other.storage_partition;
}
struct Hasher {
std::size_t operator()(const ServiceWorkerKey& key) const {
return std::hash<const content::StoragePartition*>()(
key.storage_partition) ^
std::hash<int64_t>()(key.version_id);
}
};
};
// Creates a wrapper to align with the lifecycle of the non-public
// content::ServiceWorkerVersion. Object instances are pinned for the lifetime
// of the underlying SW such that registered IPC handlers continue to dispatch.
//
// Instances are uniquely identified by pairing their version ID and the
// StoragePartition in which they're registered. In Electron, this is always
// the default StoragePartition for the associated BrowserContext.
class ServiceWorkerMain final
: public gin::Wrappable<ServiceWorkerMain>,
public gin_helper::EventEmitterMixin<ServiceWorkerMain>,
public gin_helper::Pinnable<ServiceWorkerMain>,
public gin_helper::Constructible<ServiceWorkerMain> {
public:
// Create a new ServiceWorkerMain and return the V8 wrapper of it.
static gin::Handle<ServiceWorkerMain> New(v8::Isolate* isolate);
static gin::Handle<ServiceWorkerMain> From(
v8::Isolate* isolate,
content::ServiceWorkerContext* sw_context,
const content::StoragePartition* storage_partition,
int64_t version_id);
static ServiceWorkerMain* FromVersionID(
int64_t version_id,
const content::StoragePartition* storage_partition);
// gin_helper::Constructible
static void FillObjectTemplate(v8::Isolate*, v8::Local<v8::ObjectTemplate>);
static const char* GetClassName() { return "ServiceWorkerMain"; }
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
const char* GetTypeName() override;
// disable copy
ServiceWorkerMain(const ServiceWorkerMain&) = delete;
ServiceWorkerMain& operator=(const ServiceWorkerMain&) = delete;
void OnRunningStatusChanged(blink::EmbeddedWorkerStatus running_status);
void OnVersionRedundant();
protected:
explicit ServiceWorkerMain(content::ServiceWorkerContext* sw_context,
int64_t version_id,
const ServiceWorkerKey& key);
~ServiceWorkerMain() override;
private:
void Destroy();
void MaybeDisconnectRemote();
const blink::StorageKey GetStorageKey();
// Increments external requests for the service worker to keep it alive.
gin_helper::Dictionary StartExternalRequest(v8::Isolate* isolate,
bool has_timeout);
void FinishExternalRequest(v8::Isolate* isolate, std::string uuid);
size_t CountExternalRequestsForTest();
// Get or create a Mojo connection to the renderer process.
mojom::ElectronRenderer* GetRendererApi();
// Send a message to the renderer process.
void Send(v8::Isolate* isolate,
bool internal,
const std::string& channel,
v8::Local<v8::Value> args);
void InvalidateVersionInfo();
const content::ServiceWorkerVersionBaseInfo* version_info() const {
return version_info_.get();
}
bool IsDestroyed() const;
int64_t VersionID() const;
GURL ScopeURL() const;
// Version ID unique only to the StoragePartition.
int64_t version_id_;
// Unique identifier pairing the Version ID and StoragePartition.
ServiceWorkerKey key_;
// Whether the Service Worker version has been destroyed.
bool version_destroyed_ = false;
// Whether the Service Worker version's state is redundant.
bool redundant_ = false;
// Store copy of version info so it's accessible when not running.
std::unique_ptr<content::ServiceWorkerVersionBaseInfo> version_info_;
raw_ptr<content::ServiceWorkerContext> service_worker_context_;
mojo::AssociatedRemote<mojom::ElectronRenderer> remote_;
std::unique_ptr<gin_helper::Promise<void>> start_worker_promise_;
base::WeakPtrFactory<ServiceWorkerMain> weak_factory_{this};
};
} // namespace electron::api
#endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SERVICE_WORKER_MAIN_H_

View File

@@ -1065,16 +1065,72 @@ void Session::CreateInterruptedDownload(const gin_helper::Dictionary& options) {
base::Time::FromSecondsSinceUnixEpoch(start_time)));
}
void Session::SetPreloads(const std::vector<base::FilePath>& preloads) {
std::string Session::RegisterPreloadScript(
gin_helper::ErrorThrower thrower,
const PreloadScript& new_preload_script) {
auto* prefs = SessionPreferences::FromBrowserContext(browser_context());
DCHECK(prefs);
prefs->set_preloads(preloads);
auto& preload_scripts = prefs->preload_scripts();
auto it = std::find_if(preload_scripts.begin(), preload_scripts.end(),
[&new_preload_script](const PreloadScript& script) {
return script.id == new_preload_script.id;
});
if (it != preload_scripts.end()) {
thrower.ThrowError(base::StringPrintf(
"Cannot register preload script with existing ID '%s'",
new_preload_script.id.c_str()));
return "";
}
if (!new_preload_script.file_path.IsAbsolute()) {
// Deprecated preload scripts logged error without throwing.
if (new_preload_script.deprecated) {
LOG(ERROR) << "preload script must have absolute path: "
<< new_preload_script.file_path;
} else {
thrower.ThrowError(
base::StringPrintf("Preload script must have absolute path: %s",
new_preload_script.file_path.value().c_str()));
return "";
}
}
preload_scripts.push_back(new_preload_script);
return new_preload_script.id;
}
std::vector<base::FilePath> Session::GetPreloads() const {
void Session::UnregisterPreloadScript(gin_helper::ErrorThrower thrower,
const std::string& script_id) {
auto* prefs = SessionPreferences::FromBrowserContext(browser_context());
DCHECK(prefs);
return prefs->preloads();
auto& preload_scripts = prefs->preload_scripts();
// Find the preload script by its ID
auto it = std::find_if(preload_scripts.begin(), preload_scripts.end(),
[&script_id](const PreloadScript& script) {
return script.id == script_id;
});
// If the script is found, erase it from the vector
if (it != preload_scripts.end()) {
preload_scripts.erase(it);
return;
}
// If the script is not found, throw an error
thrower.ThrowError(base::StringPrintf(
"Cannot unregister preload script with non-existing ID '%s'",
script_id.c_str()));
}
std::vector<PreloadScript> Session::GetPreloadScripts() const {
auto* prefs = SessionPreferences::FromBrowserContext(browser_context());
DCHECK(prefs);
return prefs->preload_scripts();
}
/**
@@ -1800,8 +1856,9 @@ void Session::FillObjectTemplate(v8::Isolate* isolate,
.SetMethod("downloadURL", &Session::DownloadURL)
.SetMethod("createInterruptedDownload",
&Session::CreateInterruptedDownload)
.SetMethod("setPreloads", &Session::SetPreloads)
.SetMethod("getPreloads", &Session::GetPreloads)
.SetMethod("registerPreloadScript", &Session::RegisterPreloadScript)
.SetMethod("unregisterPreloadScript", &Session::UnregisterPreloadScript)
.SetMethod("getPreloadScripts", &Session::GetPreloadScripts)
.SetMethod("getSharedDictionaryUsageInfo",
&Session::GetSharedDictionaryUsageInfo)
.SetMethod("getSharedDictionaryInfo", &Session::GetSharedDictionaryInfo)
@@ -1852,6 +1909,10 @@ const char* Session::GetTypeName() {
return GetClassName();
}
void Session::WillBeDestroyed() {
ClearWeak();
}
} // namespace electron::api
namespace {

View File

@@ -57,6 +57,7 @@ class ProxyConfig;
namespace electron {
class ElectronBrowserContext;
struct PreloadScript;
namespace api {
@@ -102,6 +103,9 @@ class Session final : public gin::Wrappable<Session>,
static const char* GetClassName() { return "Session"; }
const char* GetTypeName() override;
// gin_helper::CleanedUpAtExit
void WillBeDestroyed() override;
// Methods.
v8::Local<v8::Promise> ResolveHost(
std::string host,
@@ -138,8 +142,11 @@ class Session final : public gin::Wrappable<Session>,
const std::string& uuid);
void DownloadURL(const GURL& url, gin::Arguments* args);
void CreateInterruptedDownload(const gin_helper::Dictionary& options);
void SetPreloads(const std::vector<base::FilePath>& preloads);
std::vector<base::FilePath> GetPreloads() const;
std::string RegisterPreloadScript(gin_helper::ErrorThrower thrower,
const PreloadScript& new_preload_script);
void UnregisterPreloadScript(gin_helper::ErrorThrower thrower,
const std::string& script_id);
std::vector<PreloadScript> GetPreloadScripts() const;
v8::Local<v8::Promise> GetSharedDictionaryInfo(
const gin_helper::Dictionary& options);
v8::Local<v8::Promise> GetSharedDictionaryUsageInfo();

View File

@@ -431,6 +431,10 @@ const char* Tray::GetTypeName() {
return GetClassName();
}
void Tray::WillBeDestroyed() {
ClearWeak();
}
} // namespace electron::api
namespace {

View File

@@ -58,6 +58,9 @@ class Tray final : public gin::Wrappable<Tray>,
static gin::WrapperInfo kWrapperInfo;
const char* GetTypeName() override;
// gin_helper::CleanedUpAtExit
void WillBeDestroyed() override;
// disable copy
Tray(const Tray&) = delete;
Tray& operator=(const Tray&) = delete;

View File

@@ -3757,16 +3757,15 @@ void WebContents::DoGetZoomLevel(
std::move(callback).Run(GetZoomLevel());
}
std::vector<base::FilePath> WebContents::GetPreloadPaths() const {
auto result = SessionPreferences::GetValidPreloads(GetBrowserContext());
std::optional<PreloadScript> WebContents::GetPreloadScript() const {
if (auto* web_preferences = WebContentsPreferences::From(web_contents())) {
if (auto preload = web_preferences->GetPreloadPath()) {
result.emplace_back(*preload);
auto preload_script = PreloadScript{
"", PreloadScript::ScriptType::kWebFrame, preload.value()};
return preload_script;
}
}
return result;
return std::nullopt;
}
v8::Local<v8::Value> WebContents::GetLastWebPreferences(
@@ -4520,7 +4519,7 @@ void WebContents::FillObjectTemplate(v8::Isolate* isolate,
.SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
.SetMethod("getZoomFactor", &WebContents::GetZoomFactor)
.SetMethod("getType", &WebContents::type)
.SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths)
.SetMethod("_getPreloadScript", &WebContents::GetPreloadScript)
.SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences)
.SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
.SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
@@ -4570,6 +4569,10 @@ const char* WebContents::GetTypeName() {
return GetClassName();
}
void WebContents::WillBeDestroyed() {
ClearWeak();
}
ElectronBrowserContext* WebContents::GetBrowserContext() const {
return static_cast<ElectronBrowserContext*>(
web_contents()->GetBrowserContext());

View File

@@ -40,6 +40,7 @@
#include "shell/browser/event_emitter_mixin.h"
#include "shell/browser/extended_web_contents_observer.h"
#include "shell/browser/osr/osr_paint_event.h"
#include "shell/browser/preload_script.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"
@@ -179,6 +180,9 @@ class WebContents final : public ExclusiveAccessContext,
static gin::WrapperInfo kWrapperInfo;
const char* GetTypeName() override;
// gin_helper::CleanedUpAtExit
void WillBeDestroyed() override;
void Destroy();
void Close(std::optional<gin_helper::Dictionary> options);
base::WeakPtr<WebContents> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
@@ -341,8 +345,8 @@ class WebContents final : public ExclusiveAccessContext,
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 preload script of current WebContents.
std::optional<PreloadScript> GetPreloadScript() const;
// Returns the web preferences of current WebContents.
v8::Local<v8::Value> GetLastWebPreferences(v8::Isolate* isolate) const;

View File

@@ -27,29 +27,14 @@
#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
: View(web_contents->inspectable_web_contents()->GetView()),
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,

View File

@@ -306,6 +306,10 @@ const char* MessagePort::GetTypeName() {
return "MessagePort";
}
void MessagePort::WillBeDestroyed() {
ClearWeak();
}
} // namespace electron
namespace {

View File

@@ -61,6 +61,9 @@ class MessagePort final : public gin::Wrappable<MessagePort>,
v8::Isolate* isolate) override;
const char* GetTypeName() override;
// gin_helper::CleanedUpAtExit
void WillBeDestroyed() override;
private:
MessagePort();

View File

@@ -405,9 +405,9 @@ void ElectronBrowserClient::OverrideWebkitPrefs(
prefs->javascript_enabled = true;
prefs->web_security_enabled = true;
prefs->plugins_enabled = true;
prefs->dom_paste_enabled = true;
prefs->dom_paste_enabled = false;
prefs->javascript_can_access_clipboard = false;
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 =

View File

@@ -490,14 +490,8 @@ std::unique_ptr<UserScript> ParseUserScript(
ConvertRegisteredContentScriptToSerializedUserScript(
std::move(content_script));
std::unique_ptr<UserScript> user_script =
script_serialization::ParseSerializedUserScript(
serialized_script, extension, allowed_in_incognito, error);
if (!user_script) {
return nullptr; // Parsing failed.
}
return user_script;
return script_serialization::ParseSerializedUserScript(
serialized_script, extension, allowed_in_incognito, error);
}
// Converts a UserScript object to a api::scripting::RegisteredContentScript

View File

@@ -651,7 +651,16 @@ bool TabsUpdateFunction::UpdateURL(const std::string& url_string,
// will stay in the omnibox - see https://crbug.com/1085779.
load_params.transition_type = ui::PAGE_TRANSITION_FROM_API;
web_contents_->GetController().LoadURLWithParams(load_params);
base::WeakPtr<content::NavigationHandle> navigation_handle =
web_contents_->GetController().LoadURLWithParams(load_params);
// Navigation can fail for any number of reasons at the content layer.
// Unfortunately, we can't provide a detailed error message here, because
// there are too many possible triggers. At least notify the extension that
// the update failed.
if (!navigation_handle) {
*error = "Navigation rejected.";
return false;
}
DCHECK_EQ(url,
web_contents_->GetController().GetPendingEntry()->GetVirtualURL());

View File

@@ -461,7 +461,7 @@ FileSystemAccessPermissionContext::GetReadPermissionGrant(
// but that is exactly what we want.
auto& origin_state = active_permissions_map_[origin];
auto*& existing_grant = origin_state.read_grants[path_info.path];
scoped_refptr<PermissionGrantImpl> new_grant;
scoped_refptr<PermissionGrantImpl> grant;
if (existing_grant && existing_grant->handle_type() != handle_type) {
// |path| changed from being a directory to being a file or vice versa,
@@ -471,18 +471,21 @@ FileSystemAccessPermissionContext::GetReadPermissionGrant(
existing_grant = nullptr;
}
if (!existing_grant) {
new_grant = base::MakeRefCounted<PermissionGrantImpl>(
bool creating_new_grant = !existing_grant;
if (creating_new_grant) {
grant = base::MakeRefCounted<PermissionGrantImpl>(
weak_factory_.GetWeakPtr(), origin, path_info, handle_type,
GrantType::kRead, user_action);
existing_grant = new_grant.get();
existing_grant = grant.get();
} else {
grant = existing_grant;
}
// If a parent directory is already readable this new grant should also be
// readable.
if (new_grant &&
if (creating_new_grant &&
AncestorHasActivePermission(origin, path_info.path, GrantType::kRead)) {
existing_grant->SetStatus(PermissionStatus::GRANTED);
grant->SetStatus(PermissionStatus::GRANTED);
} else {
switch (user_action) {
case UserAction::kOpen:
@@ -494,7 +497,7 @@ FileSystemAccessPermissionContext::GetReadPermissionGrant(
[[fallthrough]];
case UserAction::kDragAndDrop:
// Drag&drop grants read access for all handles.
existing_grant->SetStatus(PermissionStatus::GRANTED);
grant->SetStatus(PermissionStatus::GRANTED);
break;
case UserAction::kLoadFromStorage:
case UserAction::kNone:
@@ -502,7 +505,7 @@ FileSystemAccessPermissionContext::GetReadPermissionGrant(
}
}
return existing_grant;
return grant;
}
scoped_refptr<content::FileSystemAccessPermissionGrant>
@@ -516,7 +519,7 @@ FileSystemAccessPermissionContext::GetWritePermissionGrant(
// but that is exactly what we want.
auto& origin_state = active_permissions_map_[origin];
auto*& existing_grant = origin_state.write_grants[path_info.path];
scoped_refptr<PermissionGrantImpl> new_grant;
scoped_refptr<PermissionGrantImpl> grant;
if (existing_grant && existing_grant->handle_type() != handle_type) {
// |path| changed from being a directory to being a file or vice versa,
@@ -526,23 +529,26 @@ FileSystemAccessPermissionContext::GetWritePermissionGrant(
existing_grant = nullptr;
}
if (!existing_grant) {
new_grant = base::MakeRefCounted<PermissionGrantImpl>(
bool creating_new_grant = !existing_grant;
if (creating_new_grant) {
grant = base::MakeRefCounted<PermissionGrantImpl>(
weak_factory_.GetWeakPtr(), origin, path_info, handle_type,
GrantType::kWrite, user_action);
existing_grant = new_grant.get();
existing_grant = grant.get();
} else {
grant = existing_grant;
}
// If a parent directory is already writable this new grant should also be
// writable.
if (new_grant &&
if (creating_new_grant &&
AncestorHasActivePermission(origin, path_info.path, GrantType::kWrite)) {
existing_grant->SetStatus(PermissionStatus::GRANTED);
grant->SetStatus(PermissionStatus::GRANTED);
} else {
switch (user_action) {
case UserAction::kSave:
// Only automatically grant write access for save dialogs.
existing_grant->SetStatus(PermissionStatus::GRANTED);
grant->SetStatus(PermissionStatus::GRANTED);
break;
case UserAction::kOpen:
case UserAction::kDragAndDrop:
@@ -552,7 +558,7 @@ FileSystemAccessPermissionContext::GetWritePermissionGrant(
}
}
return existing_grant;
return grant;
}
bool FileSystemAccessPermissionContext::IsFileTypeDangerous(
@@ -588,7 +594,7 @@ void FileSystemAccessPermissionContext::ConfirmSensitiveEntryAccess(
content::GlobalRenderFrameHostId frame_id,
base::OnceCallback<void(SensitiveEntryResult)> callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
callback_ = std::move(callback);
callback_map_.try_emplace(path_info.path, std::move(callback));
auto after_blocklist_check_callback = base::BindOnce(
&FileSystemAccessPermissionContext::DidCheckPathAgainstBlocklist,
@@ -632,16 +638,18 @@ void FileSystemAccessPermissionContext::PerformAfterWriteChecks(
}
void FileSystemAccessPermissionContext::RunRestrictedPathCallback(
const base::FilePath& file_path,
SensitiveEntryResult result) {
if (callback_)
std::move(callback_).Run(result);
if (auto val = callback_map_.extract(file_path))
std::move(val.mapped()).Run(result);
}
void FileSystemAccessPermissionContext::OnRestrictedPathResult(
const base::FilePath& file_path,
gin::Arguments* args) {
SensitiveEntryResult result = SensitiveEntryResult::kAbort;
args->GetNext(&result);
RunRestrictedPathCallback(result);
RunRestrictedPathCallback(file_path, result);
}
void FileSystemAccessPermissionContext::DidCheckPathAgainstBlocklist(
@@ -654,8 +662,9 @@ void FileSystemAccessPermissionContext::DidCheckPathAgainstBlocklist(
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (user_action == UserAction::kNone) {
RunRestrictedPathCallback(should_block ? SensitiveEntryResult::kAbort
: SensitiveEntryResult::kAllowed);
auto result = should_block ? SensitiveEntryResult::kAbort
: SensitiveEntryResult::kAllowed;
RunRestrictedPathCallback(path_info.path, result);
return;
}
@@ -674,11 +683,11 @@ void FileSystemAccessPermissionContext::DidCheckPathAgainstBlocklist(
"file-system-access-restricted", details,
base::BindRepeating(
&FileSystemAccessPermissionContext::OnRestrictedPathResult,
weak_factory_.GetWeakPtr()));
weak_factory_.GetWeakPtr(), path_info.path));
return;
}
RunRestrictedPathCallback(SensitiveEntryResult::kAllowed);
RunRestrictedPathCallback(path_info.path, SensitiveEntryResult::kAllowed);
}
void FileSystemAccessPermissionContext::MaybeEvictEntries(
@@ -866,12 +875,22 @@ void FileSystemAccessPermissionContext::RevokeActiveGrants(
auto origin_it = active_permissions_map_.find(origin);
if (origin_it != active_permissions_map_.end()) {
OriginState& origin_state = origin_it->second;
for (auto& grant : origin_state.read_grants) {
for (auto grant_iter = origin_state.read_grants.begin(),
grant_end = origin_state.read_grants.end();
grant_iter != grant_end;) {
// The grant may be removed from `read_grants`, so increase the iterator
// before continuing.
auto& grant = *(grant_iter++);
if (file_path.empty() || grant.first == file_path) {
grant.second->SetStatus(PermissionStatus::ASK);
}
}
for (auto& grant : origin_state.write_grants) {
for (auto grant_iter = origin_state.write_grants.begin(),
grant_end = origin_state.write_grants.end();
grant_iter != grant_end;) {
// The grant may be removed from `write_grants`, so increase the iterator
// before continuing.
auto& grant = *(grant_iter++);
if (file_path.empty() || grant.first == file_path) {
grant.second->SetStatus(PermissionStatus::ASK);
}

View File

@@ -144,9 +144,11 @@ class FileSystemAccessPermissionContext
content::GlobalRenderFrameHostId frame_id,
bool should_block);
void RunRestrictedPathCallback(SensitiveEntryResult result);
void RunRestrictedPathCallback(const base::FilePath& file_path,
SensitiveEntryResult result);
void OnRestrictedPathResult(gin::Arguments* args);
void OnRestrictedPathResult(const base::FilePath& file_path,
gin::Arguments* args);
void MaybeEvictEntries(base::Value::Dict& dict);
@@ -170,7 +172,8 @@ class FileSystemAccessPermissionContext
std::map<url::Origin, base::Value::Dict> id_pathinfo_map_;
base::OnceCallback<void(SensitiveEntryResult)> callback_;
std::map<base::FilePath, base::OnceCallback<void(SensitiveEntryResult)>>
callback_map_;
base::WeakPtrFactory<FileSystemAccessPermissionContext> weak_factory_{this};
};

View File

@@ -132,11 +132,16 @@ v8::Isolate* JavascriptEnvironment::GetIsolate() {
void JavascriptEnvironment::CreateMicrotasksRunner() {
DCHECK(!microtasks_runner_);
microtasks_runner_ = std::make_unique<MicrotasksRunner>(isolate());
isolate_holder_.WillCreateMicrotasksRunner();
base::CurrentThread::Get()->AddTaskObserver(microtasks_runner_.get());
}
void JavascriptEnvironment::DestroyMicrotasksRunner() {
DCHECK(microtasks_runner_);
// Should be called before running gin_helper::CleanedUpAtExit::DoCleanup.
// This helps to signal wrappable finalizer callbacks to not act on freed
// parameters.
isolate_holder_.WillDestroyMicrotasksRunner();
{
v8::HandleScope scope(isolate_);
gin_helper::CleanedUpAtExit::DoCleanup();

View File

@@ -169,9 +169,6 @@ class NativeWindowMac : public NativeWindow,
void NotifyWindowDidFailToEnterFullScreen();
void NotifyWindowWillLeaveFullScreen();
// views::WidgetDelegate:
views::View* GetContentsView() override;
// 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.
@@ -223,6 +220,7 @@ class NativeWindowMac : public NativeWindow,
protected:
// views::WidgetDelegate:
views::View* GetContentsView() override;
bool CanMaximize() const override;
std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView(
views::Widget* widget) override;

View File

@@ -194,6 +194,8 @@ NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options,
params.bounds = bounds;
params.delegate = this;
params.type = views::Widget::InitParams::TYPE_WINDOW;
// Allow painting before shown, to be later disabled in ElectronNSWindow.
params.headless_mode = true;
params.native_widget =
new ElectronNativeWidgetMac(this, windowType, styleMask, widget());
widget()->Init(std::move(params));
@@ -1674,6 +1676,7 @@ void NativeWindowMac::Cleanup() {
DCHECK(!IsClosed());
ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this);
display::Screen::GetScreen()->RemoveObserver(this);
[window_ cleanup];
}
class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac {

View File

@@ -27,6 +27,7 @@
#include "content/public/browser/desktop_media_id.h"
#include "content/public/common/color_parser.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/ui/views/root_view.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_view_manager.h"

View File

@@ -0,0 +1,104 @@
// Copyright (c) 2025 Salesforce, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_PRELOAD_SCRIPT_H_
#define ELECTRON_SHELL_BROWSER_PRELOAD_SCRIPT_H_
#include <string_view>
#include "base/containers/fixed_flat_map.h"
#include "base/files/file_path.h"
#include "base/uuid.h"
#include "gin/converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_helper/dictionary.h"
namespace electron {
struct PreloadScript {
enum class ScriptType { kWebFrame, kServiceWorker };
std::string id;
ScriptType script_type;
base::FilePath file_path;
// If set, use the deprecated validation behavior of Session.setPreloads
bool deprecated = false;
};
} // namespace electron
namespace gin {
using electron::PreloadScript;
template <>
struct Converter<PreloadScript::ScriptType> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const PreloadScript::ScriptType& in) {
using Val = PreloadScript::ScriptType;
static constexpr auto Lookup =
base::MakeFixedFlatMap<Val, std::string_view>({
{Val::kWebFrame, "frame"},
{Val::kServiceWorker, "service-worker"},
});
return StringToV8(isolate, Lookup.at(in));
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
PreloadScript::ScriptType* out) {
using Val = PreloadScript::ScriptType;
static constexpr auto Lookup =
base::MakeFixedFlatMap<std::string_view, Val>({
{"frame", Val::kWebFrame},
{"service-worker", Val::kServiceWorker},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<PreloadScript> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const PreloadScript& script) {
gin::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("filePath", script.file_path.AsUTF8Unsafe());
dict.Set("id", script.id);
dict.Set("type", script.script_type);
return ConvertToV8(isolate, dict).As<v8::Object>();
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
PreloadScript* out) {
gin_helper::Dictionary options;
if (!ConvertFromV8(isolate, val, &options))
return false;
if (PreloadScript::ScriptType script_type;
options.Get("type", &script_type)) {
out->script_type = script_type;
} else {
return false;
}
if (base::FilePath file_path; options.Get("filePath", &file_path)) {
out->file_path = file_path;
} else {
return false;
}
if (std::string id; options.Get("id", &id)) {
out->id = id;
} else {
out->id = base::Uuid::GenerateRandomV4().AsLowercaseString();
}
if (bool deprecated; options.Get("_deprecated", &deprecated)) {
out->deprecated = deprecated;
}
return true;
}
};
} // namespace gin
#endif // ELECTRON_SHELL_BROWSER_PRELOAD_SCRIPT_H_

View File

@@ -64,5 +64,7 @@
<string>${DEFAULT_APP_ASAR_HEADER_SHA}</string>
</dict>
</dict>
<key>NSPrefersDisplaySafeAreaCompatibilityMode</key>
<false/>
</dict>
</plist>

View File

@@ -30,22 +30,4 @@ SessionPreferences* SessionPreferences::FromBrowserContext(
return static_cast<SessionPreferences*>(context->GetUserData(&kLocatorKey));
}
// static
std::vector<base::FilePath> SessionPreferences::GetValidPreloads(
content::BrowserContext* context) {
std::vector<base::FilePath> result;
if (auto* self = FromBrowserContext(context)) {
for (const auto& preload : self->preloads()) {
if (preload.IsAbsolute()) {
result.emplace_back(preload);
} else {
LOG(ERROR) << "preload script must have absolute path: " << preload;
}
}
}
return result;
}
} // namespace electron

View File

@@ -9,6 +9,7 @@
#include "base/files/file_path.h"
#include "base/supports_user_data.h"
#include "shell/browser/preload_script.h"
namespace content {
class BrowserContext;
@@ -20,17 +21,12 @@ class SessionPreferences : public base::SupportsUserData::Data {
public:
static SessionPreferences* FromBrowserContext(
content::BrowserContext* context);
static std::vector<base::FilePath> GetValidPreloads(
content::BrowserContext* context);
static void CreateForBrowserContext(content::BrowserContext* context);
~SessionPreferences() override;
void set_preloads(const std::vector<base::FilePath>& preloads) {
preloads_ = preloads;
}
const std::vector<base::FilePath>& preloads() const { return preloads_; }
std::vector<PreloadScript>& preload_scripts() { return preload_scripts_; }
private:
SessionPreferences();
@@ -38,7 +34,7 @@ class SessionPreferences : public base::SupportsUserData::Data {
// The user data key.
static int kLocatorKey;
std::vector<base::FilePath> preloads_;
std::vector<PreloadScript> preload_scripts_;
};
} // namespace electron

View File

@@ -1,33 +0,0 @@
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_UI_COCOA_DELAYED_NATIVE_VIEW_HOST_H_
#define ELECTRON_SHELL_BROWSER_UI_COCOA_DELAYED_NATIVE_VIEW_HOST_H_
#include "ui/views/controls/native/native_view_host.h"
namespace electron {
// Automatically attach the native view after the NativeViewHost is attached to
// a widget. (Attaching it directly would cause crash.)
class DelayedNativeViewHost : public views::NativeViewHost {
public:
explicit DelayedNativeViewHost(gfx::NativeView native_view);
~DelayedNativeViewHost() override;
// disable copy
DelayedNativeViewHost(const DelayedNativeViewHost&) = delete;
DelayedNativeViewHost& operator=(const DelayedNativeViewHost&) = delete;
// views::View:
void ViewHierarchyChanged(
const views::ViewHierarchyChangedDetails& details) override;
private:
gfx::NativeView native_view_;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_UI_COCOA_DELAYED_NATIVE_VIEW_HOST_H_

View File

@@ -1,23 +0,0 @@
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/ui/cocoa/delayed_native_view_host.h"
namespace electron {
DelayedNativeViewHost::DelayedNativeViewHost(gfx::NativeView native_view)
: native_view_(native_view) {}
DelayedNativeViewHost::~DelayedNativeViewHost() = default;
void DelayedNativeViewHost::ViewHierarchyChanged(
const views::ViewHierarchyChangedDetails& details) {
if (!details.is_add && native_view())
Detach();
NativeViewHost::ViewHierarchyChanged(details);
if (details.is_add && GetWidget() && !native_view())
Attach(native_view_);
}
} // namespace electron

View File

@@ -1,54 +0,0 @@
// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#ifndef ELECTRON_SHELL_BROWSER_UI_COCOA_ELECTRON_INSPECTABLE_WEB_CONTENTS_VIEW_H_
#define ELECTRON_SHELL_BROWSER_UI_COCOA_ELECTRON_INSPECTABLE_WEB_CONTENTS_VIEW_H_
#import <AppKit/AppKit.h>
#include "base/apple/owned_objc.h"
#include "base/memory/raw_ptr.h"
#include "chrome/browser/devtools/devtools_contents_resizing_strategy.h"
#include "ui/base/cocoa/base_view.h"
namespace electron {
class InspectableWebContentsViewMac;
}
using electron::InspectableWebContentsViewMac;
@interface NSView (WebContentsView)
- (void)setMouseDownCanMoveWindow:(BOOL)can_move;
@end
@interface ElectronInspectableWebContentsView : BaseView <NSWindowDelegate> {
@private
raw_ptr<electron::InspectableWebContentsViewMac> inspectableWebContentsView_;
NSView* __strong fake_view_;
NSWindow* __strong devtools_window_;
BOOL devtools_visible_;
BOOL devtools_docked_;
BOOL devtools_is_first_responder_;
BOOL attached_to_window_;
DevToolsContentsResizingStrategy strategy_;
}
- (instancetype)initWithInspectableWebContentsViewMac:
(InspectableWebContentsViewMac*)view;
- (void)notifyDevToolsFocused;
- (void)setCornerRadii:(CGFloat)cornerRadius;
- (void)setDevToolsVisible:(BOOL)visible activate:(BOOL)activate;
- (BOOL)isDevToolsVisible;
- (BOOL)isDevToolsFocused;
- (void)setIsDocked:(BOOL)docked activate:(BOOL)activate;
- (void)setContentsResizingStrategy:
(const DevToolsContentsResizingStrategy&)strategy;
- (void)setTitle:(NSString*)title;
- (NSString*)getTitle;
@end
#endif // ELECTRON_SHELL_BROWSER_UI_COCOA_ELECTRON_INSPECTABLE_WEB_CONTENTS_VIEW_H_

View File

@@ -1,337 +0,0 @@
// Copyright (c) 2014 The Chromium Authors. 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/cocoa/electron_inspectable_web_contents_view.h"
#include "content/public/browser/render_widget_host_view.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/ui/cocoa/event_dispatching_window.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view_delegate.h"
#include "shell/browser/ui/inspectable_web_contents_view_mac.h"
#include "ui/base/cocoa/base_view.h"
#include "ui/gfx/mac/scoped_cocoa_disable_screen_updates.h"
@implementation ElectronInspectableWebContentsView
- (instancetype)initWithInspectableWebContentsViewMac:
(InspectableWebContentsViewMac*)view {
self = [super init];
if (!self)
return nil;
inspectableWebContentsView_ = view;
devtools_visible_ = NO;
devtools_docked_ = NO;
devtools_is_first_responder_ = NO;
attached_to_window_ = NO;
if (inspectableWebContentsView_->inspectable_web_contents()->is_guest()) {
fake_view_ = [[NSView alloc] init];
[fake_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[self addSubview:fake_view_];
} else {
auto* contents = inspectableWebContentsView_->inspectable_web_contents()
->GetWebContents();
auto* contentsView = contents->GetNativeView().GetNativeNSView();
[contentsView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[self addSubview:contentsView];
}
// See https://code.google.com/p/chromium/issues/detail?id=348490.
[self setWantsLayer:YES];
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)resizeSubviewsWithOldSize:(NSSize)oldBoundsSize {
[self adjustSubviews];
}
- (void)viewDidMoveToWindow {
if (attached_to_window_ && !self.window) {
attached_to_window_ = NO;
[[NSNotificationCenter defaultCenter] removeObserver:self];
} else if (!attached_to_window_ && self.window) {
attached_to_window_ = YES;
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(viewDidBecomeFirstResponder:)
name:kViewDidBecomeFirstResponder
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(parentWindowBecameMain:)
name:NSWindowDidBecomeMainNotification
object:nil];
}
}
- (IBAction)showDevTools:(id)sender {
inspectableWebContentsView_->inspectable_web_contents()->ShowDevTools(true);
}
- (void)notifyDevToolsFocused {
if (inspectableWebContentsView_->GetDelegate())
inspectableWebContentsView_->GetDelegate()->DevToolsFocused();
}
- (void)setCornerRadii:(CGFloat)cornerRadius {
auto* inspectable_web_contents =
inspectableWebContentsView_->inspectable_web_contents();
DCHECK(inspectable_web_contents);
auto* webContents = inspectable_web_contents->GetWebContents();
if (!webContents)
return;
auto* webContentsView = webContents->GetNativeView().GetNativeNSView();
webContentsView.wantsLayer = YES;
webContentsView.layer.cornerRadius = cornerRadius;
}
- (void)notifyDevToolsResized {
// When devtools is opened, resizing devtools would not trigger
// UpdateDraggableRegions for WebContents, so we have to notify the window
// to do an update of draggable regions.
if (inspectableWebContentsView_->GetDelegate())
inspectableWebContentsView_->GetDelegate()->DevToolsResized();
}
- (void)setDevToolsVisible:(BOOL)visible activate:(BOOL)activate {
if (visible == devtools_visible_)
return;
auto* inspectable_web_contents =
inspectableWebContentsView_->inspectable_web_contents();
auto* devToolsWebContents =
inspectable_web_contents->GetDevToolsWebContents();
auto* devToolsView = devToolsWebContents->GetNativeView().GetNativeNSView();
devtools_visible_ = visible;
if (devtools_docked_) {
if (visible) {
// Place the devToolsView under contentsView, notice that we didn't set
// sizes for them until the setContentsResizingStrategy message.
[self addSubview:devToolsView positioned:NSWindowBelow relativeTo:nil];
[self adjustSubviews];
// Focus on web view.
devToolsWebContents->RestoreFocus();
} else {
gfx::ScopedCocoaDisableScreenUpdates disabler;
[devToolsView removeFromSuperview];
[self adjustSubviews];
[self notifyDevToolsResized];
}
} else {
if (visible) {
if (activate) {
[devtools_window_ makeKeyAndOrderFront:nil];
} else {
[devtools_window_ orderBack:nil];
}
} else {
[devtools_window_ setDelegate:nil];
[devtools_window_ close];
devtools_window_ = nil;
}
}
}
- (BOOL)isDevToolsVisible {
return devtools_visible_;
}
- (BOOL)isDevToolsFocused {
if (devtools_docked_) {
return [[self window] isKeyWindow] && devtools_is_first_responder_;
} else {
return [devtools_window_ isKeyWindow];
}
}
// TODO: remove NSWindowStyleMaskTexturedBackground.
// https://github.com/electron/electron/issues/43125
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (void)setIsDocked:(BOOL)docked activate:(BOOL)activate {
// Revert to no-devtools state.
[self setDevToolsVisible:NO activate:NO];
// Switch to new state.
devtools_docked_ = docked;
auto* inspectable_web_contents =
inspectableWebContentsView_->inspectable_web_contents();
auto* devToolsWebContents =
inspectable_web_contents->GetDevToolsWebContents();
auto devToolsView = devToolsWebContents->GetNativeView().GetNativeNSView();
if (!docked) {
auto styleMask = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
NSWindowStyleMaskMiniaturizable |
NSWindowStyleMaskResizable |
NSWindowStyleMaskTexturedBackground |
NSWindowStyleMaskUnifiedTitleAndToolbar;
devtools_window_ = [[EventDispatchingWindow alloc]
initWithContentRect:NSMakeRect(0, 0, 800, 600)
styleMask:styleMask
backing:NSBackingStoreBuffered
defer:YES];
[devtools_window_ setDelegate:self];
[devtools_window_ setFrameAutosaveName:@"electron.devtools"];
[devtools_window_ setTitle:@"Developer Tools"];
[devtools_window_ setReleasedWhenClosed:NO];
[devtools_window_ setAutorecalculatesContentBorderThickness:NO
forEdge:NSMaxYEdge];
[devtools_window_ setContentBorderThickness:24 forEdge:NSMaxYEdge];
NSView* contentView = [devtools_window_ contentView];
devToolsView.frame = contentView.bounds;
devToolsView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
[contentView addSubview:devToolsView];
[devToolsView setMouseDownCanMoveWindow:NO];
} else {
[devToolsView setMouseDownCanMoveWindow:YES];
}
[self setDevToolsVisible:YES activate:activate];
}
// -Wdeprecated-declarations
#pragma clang diagnostic pop
- (void)setContentsResizingStrategy:
(const DevToolsContentsResizingStrategy&)strategy {
strategy_.CopyFrom(strategy);
[self adjustSubviews];
}
- (void)adjustSubviews {
if (![[self subviews] count])
return;
if (![self isDevToolsVisible] || devtools_window_) {
DCHECK_EQ(1u, [[self subviews] count]);
NSView* contents = [[self subviews] objectAtIndex:0];
[contents setFrame:[self bounds]];
return;
}
NSView* devToolsView = [[self subviews] objectAtIndex:0];
NSView* contentsView = [[self subviews] objectAtIndex:1];
DCHECK_EQ(2u, [[self subviews] count]);
gfx::Rect new_devtools_bounds;
gfx::Rect new_contents_bounds;
ApplyDevToolsContentsResizingStrategy(
strategy_, gfx::Size(NSSizeToCGSize([self bounds].size)),
&new_devtools_bounds, &new_contents_bounds);
[devToolsView setFrame:[self flipRectToNSRect:new_devtools_bounds]];
[contentsView setFrame:[self flipRectToNSRect:new_contents_bounds]];
// Move mask to the devtools area to exclude it from dragging.
NSRect cf = contentsView.frame;
NSRect sb = [self bounds];
NSRect devtools_frame;
if (cf.size.height < sb.size.height) { // bottom docked
devtools_frame.origin.x = 0;
devtools_frame.origin.y = 0;
devtools_frame.size.width = sb.size.width;
devtools_frame.size.height = sb.size.height - cf.size.height;
} else { // left or right docked
if (cf.origin.x > 0) // left docked
devtools_frame.origin.x = 0;
else // right docked.
devtools_frame.origin.x = cf.size.width;
devtools_frame.origin.y = 0;
devtools_frame.size.width = sb.size.width - cf.size.width;
devtools_frame.size.height = sb.size.height;
}
[self notifyDevToolsResized];
}
- (void)setTitle:(NSString*)title {
[devtools_window_ setTitle:title];
}
- (NSString*)getTitle {
return [devtools_window_ title];
}
- (void)viewDidBecomeFirstResponder:(NSNotification*)notification {
auto* inspectable_web_contents =
inspectableWebContentsView_->inspectable_web_contents();
DCHECK(inspectable_web_contents);
auto* webContents = inspectable_web_contents->GetWebContents();
if (!webContents)
return;
auto* webContentsView = webContents->GetNativeView().GetNativeNSView();
NSView* view = [notification object];
if ([[webContentsView subviews] containsObject:view]) {
devtools_is_first_responder_ = NO;
return;
}
auto* devToolsWebContents =
inspectable_web_contents->GetDevToolsWebContents();
if (!devToolsWebContents)
return;
auto devToolsView = devToolsWebContents->GetNativeView().GetNativeNSView();
if ([[devToolsView subviews] containsObject:view]) {
devtools_is_first_responder_ = YES;
[self notifyDevToolsFocused];
}
}
- (void)parentWindowBecameMain:(NSNotification*)notification {
NSWindow* parentWindow = [notification object];
if ([self window] == parentWindow && devtools_docked_ &&
devtools_is_first_responder_)
[self notifyDevToolsFocused];
}
#pragma mark - NSWindowDelegate
- (void)windowWillClose:(NSNotification*)notification {
inspectableWebContentsView_->inspectable_web_contents()->CloseDevTools();
}
- (void)windowDidBecomeMain:(NSNotification*)notification {
content::WebContents* web_contents =
inspectableWebContentsView_->inspectable_web_contents()
->GetDevToolsWebContents();
if (!web_contents)
return;
web_contents->RestoreFocus();
content::RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
if (rwhv)
rwhv->SetActive(true);
[self notifyDevToolsFocused];
}
- (void)windowDidResignMain:(NSNotification*)notification {
content::WebContents* web_contents =
inspectableWebContentsView_->inspectable_web_contents()
->GetDevToolsWebContents();
if (!web_contents)
return;
web_contents->StoreFocus();
content::RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
if (rwhv)
rwhv->SetActive(false);
}
@end

View File

@@ -29,6 +29,8 @@ class ScopedDisableResize {
} // namespace electron
class ElectronNativeWindowObserver;
@interface ElectronNSWindow : NativeWidgetMacNSWindow {
@private
raw_ptr<electron::NativeWindowMac> shell_;
@@ -41,6 +43,7 @@ class ScopedDisableResize {
@property(nonatomic, retain) NSImage* cornerMask;
- (id)initWithShell:(electron::NativeWindowMac*)shell
styleMask:(NSUInteger)styleMask;
- (void)cleanup;
- (electron::NativeWindowMac*)shell;
- (id)accessibilityFocusedUIElement;
- (NSRect)originalContentRectForFrameRect:(NSRect)frameRect;

View File

@@ -8,8 +8,6 @@
#include "electron/mas.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/native_window_mac.h"
#include "shell/browser/ui/cocoa/delayed_native_view_host.h"
#include "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.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"
@@ -113,6 +111,7 @@ void SwizzleSwipeWithEvent(NSView* view, SEL swiz_selector) {
method_getImplementation(new_swipe_with_event));
}
#endif
} // namespace
@implementation ElectronNSWindow
@@ -168,6 +167,10 @@ void SwizzleSwipeWithEvent(NSView* view, SEL swiz_selector) {
return self;
}
- (void)cleanup {
shell_ = nullptr;
}
- (electron::NativeWindowMac*)shell {
return shell_;
}
@@ -255,6 +258,17 @@ void SwizzleSwipeWithEvent(NSView* view, SEL swiz_selector) {
[super setFrame:windowFrame display:displayViews];
}
- (void)orderWindow:(NSWindowOrderingMode)place relativeTo:(NSInteger)otherWin {
if (shell_) {
// We initialize the window in headless mode to allow painting before it is
// shown, but we don't want the headless behavior of allowing the window to
// be placed unconstrained.
self.isHeadless = false;
shell_->widget()->DisableHeadlessMode();
}
[super orderWindow:place relativeTo:otherWin];
}
- (id)accessibilityAttributeValue:(NSString*)attribute {
if ([attribute isEqual:NSAccessibilityEnabledAttribute])
return [NSNumber numberWithBool:YES];

View File

@@ -365,6 +365,19 @@ using FullScreenTransitionState =
shell_->GetNativeWindow());
auto* bridged_view = bridge_host->GetInProcessNSWindowBridge();
bridged_view->OnWindowWillClose();
// Native widget and its compositor have been destroyed upon close. We need
// to detach contents view in order to prevent reusing its layer without
// compositor in the `WebContentsViewMac::CreateViewForWidget`, leading to
// `DCHECK` failure in `BrowserCompositorMac::SetParentUiLayer`.
auto* contents_view =
static_cast<views::WidgetDelegate*>(shell_)->GetContentsView();
if (contents_view) {
auto* parent = contents_view->parent();
if (parent) {
parent->RemoveChildView(contents_view);
}
}
}
- (BOOL)windowShouldClose:(id)window {

View File

@@ -297,11 +297,6 @@ class InspectableWebContents::NetworkResourceLoader
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,
@@ -317,7 +312,7 @@ InspectableWebContents::InspectableWebContents(
: pref_service_(pref_service),
web_contents_(std::move(web_contents)),
is_guest_(is_guest),
view_(CreateInspectableContentsView(this)) {
view_(new InspectableWebContentsView(this)) {
const base::Value* bounds_dict =
&pref_service_->GetValue(kDevToolsBoundsPref);
if (bounds_dict->is_dict()) {

View File

@@ -5,12 +5,250 @@
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include <memory>
#include <utility>
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "shell/browser/ui/drag_util.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 "ui/base/models/image_model.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"
namespace electron {
namespace {
class DevToolsWindowDelegate : public views::ClientView,
public views::WidgetDelegate {
public:
DevToolsWindowDelegate(InspectableWebContentsView* shell,
views::View* view,
views::Widget* widget)
: views::ClientView(widget, view),
shell_(shell),
view_(view),
widget_(widget) {
SetOwnedByWidget(true);
set_owned_by_client();
if (shell->GetDelegate())
icon_ = shell->GetDelegate()->GetDevToolsWindowIcon();
}
~DevToolsWindowDelegate() override = default;
// disable copy
DevToolsWindowDelegate(const DevToolsWindowDelegate&) = delete;
DevToolsWindowDelegate& operator=(const DevToolsWindowDelegate&) = delete;
// views::WidgetDelegate:
views::View* GetInitiallyFocusedView() override { return view_; }
std::u16string GetWindowTitle() const override { return shell_->GetTitle(); }
ui::ImageModel GetWindowAppIcon() override { return GetWindowIcon(); }
ui::ImageModel GetWindowIcon() override { return icon_; }
views::Widget* GetWidget() override { return widget_; }
const views::Widget* GetWidget() const override { return widget_; }
views::View* GetContentsView() override { return view_; }
views::ClientView* CreateClientView(views::Widget* widget) override {
return this;
}
// views::ClientView:
views::CloseRequestResult OnWindowCloseRequested() override {
shell_->inspectable_web_contents()->CloseDevTools();
return views::CloseRequestResult::kCannotClose;
}
private:
raw_ptr<InspectableWebContentsView> shell_;
raw_ptr<views::View> view_;
raw_ptr<views::Widget> widget_;
ui::ImageModel icon_;
};
} // namespace
InspectableWebContentsView::InspectableWebContentsView(
InspectableWebContents* inspectable_web_contents)
: inspectable_web_contents_(inspectable_web_contents) {}
: inspectable_web_contents_(inspectable_web_contents),
devtools_web_view_(new views::WebView(nullptr)),
title_(u"Developer Tools") {
if (!inspectable_web_contents_->is_guest() &&
inspectable_web_contents_->GetWebContents()->GetNativeView()) {
auto* contents_web_view = new views::WebView(nullptr);
contents_web_view->SetWebContents(
inspectable_web_contents_->GetWebContents());
contents_web_view_ = contents_web_view;
} else {
no_contents_view_ = new views::Label(u"No content under offscreen mode");
}
InspectableWebContentsView::~InspectableWebContentsView() = default;
devtools_web_view_->SetVisible(false);
AddChildView(devtools_web_view_.get());
AddChildView(GetContentsView());
}
InspectableWebContentsView::~InspectableWebContentsView() {
if (devtools_window_)
inspectable_web_contents()->SaveDevToolsBounds(
devtools_window_->GetWindowBoundsInScreen());
}
void InspectableWebContentsView::SetCornerRadii(
const gfx::RoundedCornersF& corner_radii) {
// WebView won't exist for offscreen rendering.
if (contents_web_view_) {
contents_web_view_->holder()->SetCornerRadii(corner_radii);
}
}
void InspectableWebContentsView::ShowDevTools(bool activate) {
if (devtools_visible_)
return;
devtools_visible_ = true;
if (devtools_window_) {
devtools_window_web_view_->SetWebContents(
inspectable_web_contents_->GetDevToolsWebContents());
devtools_window_->SetBounds(inspectable_web_contents()->dev_tools_bounds());
if (activate) {
devtools_window_->Show();
} else {
devtools_window_->ShowInactive();
}
// Update draggable regions to account for the new dock position.
if (GetDelegate())
GetDelegate()->DevToolsResized();
} else {
devtools_web_view_->SetVisible(true);
devtools_web_view_->SetWebContents(
inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_view_->RequestFocus();
DeprecatedLayoutImmediately();
}
}
void InspectableWebContentsView::CloseDevTools() {
if (!devtools_visible_)
return;
devtools_visible_ = false;
if (devtools_window_) {
auto save_bounds = devtools_window_->IsMinimized()
? devtools_window_->GetRestoredBounds()
: devtools_window_->GetWindowBoundsInScreen();
inspectable_web_contents()->SaveDevToolsBounds(save_bounds);
devtools_window_.reset();
devtools_window_web_view_ = nullptr;
devtools_window_delegate_ = nullptr;
} else {
devtools_web_view_->SetVisible(false);
devtools_web_view_->SetWebContents(nullptr);
DeprecatedLayoutImmediately();
}
}
bool InspectableWebContentsView::IsDevToolsViewShowing() {
return devtools_visible_;
}
bool InspectableWebContentsView::IsDevToolsViewFocused() {
if (devtools_window_web_view_)
return devtools_window_web_view_->HasFocus();
else if (devtools_web_view_)
return devtools_web_view_->HasFocus();
else
return false;
}
void InspectableWebContentsView::SetIsDocked(bool docked, bool activate) {
CloseDevTools();
if (!docked) {
devtools_window_ = std::make_unique<views::Widget>();
devtools_window_web_view_ = new views::WebView(nullptr);
devtools_window_delegate_ = new DevToolsWindowDelegate(
this, devtools_window_web_view_, devtools_window_.get());
views::Widget::InitParams params(
views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET,
views::Widget::InitParams::TYPE_WINDOW);
params.delegate = devtools_window_delegate_;
params.bounds = inspectable_web_contents()->dev_tools_bounds();
#if BUILDFLAG(IS_LINUX)
params.wm_role_name = "devtools";
if (GetDelegate())
GetDelegate()->GetDevToolsWindowWMClass(&params.wm_class_name,
&params.wm_class_class);
#endif
devtools_window_->Init(std::move(params));
devtools_window_->UpdateWindowIcon();
devtools_window_->widget_delegate()->SetHasWindowSizeControls(true);
}
ShowDevTools(activate);
}
void InspectableWebContentsView::SetContentsResizingStrategy(
const DevToolsContentsResizingStrategy& strategy) {
strategy_.CopyFrom(strategy);
DeprecatedLayoutImmediately();
}
void InspectableWebContentsView::SetTitle(const std::u16string& title) {
if (devtools_window_) {
title_ = title;
devtools_window_->UpdateWindowTitle();
}
}
const std::u16string InspectableWebContentsView::GetTitle() {
return title_;
}
void InspectableWebContentsView::Layout(PassKey) {
if (!devtools_web_view_->GetVisible()) {
GetContentsView()->SetBoundsRect(GetContentsBounds());
// Propagate layout call to all children, for example browser views.
LayoutSuperclass<View>(this);
return;
}
gfx::Size container_size(width(), height());
gfx::Rect new_devtools_bounds;
gfx::Rect new_contents_bounds;
ApplyDevToolsContentsResizingStrategy(
strategy_, container_size, &new_devtools_bounds, &new_contents_bounds);
// DevTools cares about the specific position, so we have to compensate RTL
// layout here.
new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds));
new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds));
devtools_web_view_->SetBoundsRect(new_devtools_bounds);
GetContentsView()->SetBoundsRect(new_contents_bounds);
// Propagate layout call to all children, for example browser views.
LayoutSuperclass<View>(this);
if (GetDelegate())
GetDelegate()->DevToolsResized();
}
views::View* InspectableWebContentsView::GetContentsView() const {
DCHECK(contents_web_view_ || no_contents_view_);
return contents_web_view_ ? contents_web_view_ : no_contents_view_;
}
} // namespace electron

View File

@@ -9,13 +9,9 @@
#include <string>
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
#include "ui/views/view.h"
#else
#include "chrome/browser/devtools/devtools_contents_resizing_strategy.h"
#include "ui/gfx/native_widget_types.h"
#endif
#include "ui/views/view.h"
class DevToolsContentsResizingStrategy;
@@ -23,23 +19,22 @@ namespace gfx {
class RoundedCornersF;
} // namespace gfx
#if defined(TOOLKIT_VIEWS)
namespace views {
class View;
class WebView;
class Widget;
class WidgetDelegate;
} // namespace views
#endif
namespace electron {
class InspectableWebContents;
class InspectableWebContentsViewDelegate;
class InspectableWebContentsView {
class InspectableWebContentsView : public views::View {
public:
explicit InspectableWebContentsView(
InspectableWebContents* inspectable_web_contents);
virtual ~InspectableWebContentsView();
~InspectableWebContentsView() override;
InspectableWebContents* inspectable_web_contents() {
return inspectable_web_contents_;
@@ -51,32 +46,40 @@ class InspectableWebContentsView {
}
InspectableWebContentsViewDelegate* GetDelegate() const { return delegate_; }
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
// Returns the container control, which has devtools view attached.
virtual views::View* GetView() = 0;
#else
virtual gfx::NativeView GetNativeView() const = 0;
#endif
void SetCornerRadii(const gfx::RoundedCornersF& corner_radii);
virtual void ShowDevTools(bool activate) = 0;
virtual void SetCornerRadii(const gfx::RoundedCornersF& corner_radii) = 0;
// Hide the DevTools view.
virtual void CloseDevTools() = 0;
virtual bool IsDevToolsViewShowing() = 0;
virtual bool IsDevToolsViewFocused() = 0;
virtual void SetIsDocked(bool docked, bool activate) = 0;
virtual void SetContentsResizingStrategy(
const DevToolsContentsResizingStrategy& strategy) = 0;
virtual void SetTitle(const std::u16string& title) = 0;
virtual const std::u16string GetTitle() = 0;
void ShowDevTools(bool activate);
void CloseDevTools();
bool IsDevToolsViewShowing();
bool IsDevToolsViewFocused();
void SetIsDocked(bool docked, bool activate);
void SetContentsResizingStrategy(
const DevToolsContentsResizingStrategy& strategy);
void SetTitle(const std::u16string& title);
const std::u16string GetTitle();
// views::View:
void Layout(PassKey) override;
private:
views::View* GetContentsView() const;
protected:
// Owns us.
raw_ptr<InspectableWebContents> inspectable_web_contents_;
private:
raw_ptr<InspectableWebContentsViewDelegate> delegate_ =
nullptr; // weak references.
std::unique_ptr<views::Widget> devtools_window_;
raw_ptr<views::WebView> devtools_window_web_view_ = nullptr;
raw_ptr<views::WebView> contents_web_view_ = nullptr;
raw_ptr<views::View> no_contents_view_ = nullptr;
raw_ptr<views::WebView> devtools_web_view_ = nullptr;
DevToolsContentsResizingStrategy strategy_;
bool devtools_visible_ = false;
raw_ptr<views::WidgetDelegate> devtools_window_delegate_ = nullptr;
std::u16string title_;
};
} // namespace electron

View File

@@ -1,42 +0,0 @@
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2013 Adam Roben <adam@roben.org>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#ifndef ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_VIEW_MAC_H_
#define ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_VIEW_MAC_H_
#include "shell/browser/ui/inspectable_web_contents_view.h"
@class ElectronInspectableWebContentsView;
namespace electron {
class InspectableWebContentsViewMac : public InspectableWebContentsView {
public:
explicit InspectableWebContentsViewMac(
InspectableWebContents* inspectable_web_contents);
InspectableWebContentsViewMac(const InspectableWebContentsViewMac&) = delete;
InspectableWebContentsViewMac& operator=(
const InspectableWebContentsViewMac&) = delete;
~InspectableWebContentsViewMac() override;
gfx::NativeView GetNativeView() const override;
void SetCornerRadii(const gfx::RoundedCornersF& corner_radii) override;
void ShowDevTools(bool activate) override;
void CloseDevTools() override;
bool IsDevToolsViewShowing() override;
bool IsDevToolsViewFocused() override;
void SetIsDocked(bool docked, bool activate) override;
void SetContentsResizingStrategy(
const DevToolsContentsResizingStrategy& strategy) override;
void SetTitle(const std::u16string& title) override;
const std::u16string GetTitle() override;
private:
ElectronInspectableWebContentsView* __strong view_;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_VIEW_MAC_H_

View File

@@ -1,75 +0,0 @@
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2013 Adam Roben <adam@roben.org>. 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_view_mac.h"
#include "base/strings/sys_string_conversions.h"
#import "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view_delegate.h"
#include "ui/gfx/geometry/rounded_corners_f.h"
namespace electron {
InspectableWebContentsView* CreateInspectableContentsView(
InspectableWebContents* inspectable_web_contents) {
return new InspectableWebContentsViewMac(inspectable_web_contents);
}
InspectableWebContentsViewMac::InspectableWebContentsViewMac(
InspectableWebContents* inspectable_web_contents)
: InspectableWebContentsView(inspectable_web_contents),
view_([[ElectronInspectableWebContentsView alloc]
initWithInspectableWebContentsViewMac:this]) {}
InspectableWebContentsViewMac::~InspectableWebContentsViewMac() {
[[NSNotificationCenter defaultCenter] removeObserver:view_];
CloseDevTools();
}
gfx::NativeView InspectableWebContentsViewMac::GetNativeView() const {
return view_;
}
void InspectableWebContentsViewMac::SetCornerRadii(
const gfx::RoundedCornersF& corner_radii) {
// We can assume all four values are identical.
[view_ setCornerRadii:corner_radii.upper_left()];
}
void InspectableWebContentsViewMac::ShowDevTools(bool activate) {
[view_ setDevToolsVisible:YES activate:activate];
}
void InspectableWebContentsViewMac::CloseDevTools() {
[view_ setDevToolsVisible:NO activate:NO];
}
bool InspectableWebContentsViewMac::IsDevToolsViewShowing() {
return [view_ isDevToolsVisible];
}
bool InspectableWebContentsViewMac::IsDevToolsViewFocused() {
return [view_ isDevToolsFocused];
}
void InspectableWebContentsViewMac::SetIsDocked(bool docked, bool activate) {
[view_ setIsDocked:docked activate:activate];
}
void InspectableWebContentsViewMac::SetContentsResizingStrategy(
const DevToolsContentsResizingStrategy& strategy) {
[view_ setContentsResizingStrategy:strategy];
}
void InspectableWebContentsViewMac::SetTitle(const std::u16string& title) {
[view_ setTitle:base::SysUTF16ToNSString(title)];
}
const std::u16string InspectableWebContentsViewMac::GetTitle() {
return base::SysNSStringToUTF16([view_ getTitle]);
}
} // namespace electron

View File

@@ -5,6 +5,8 @@
#include "shell/browser/ui/views/frameless_view.h"
#include "shell/browser/native_window_views.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "ui/aura/window.h"
#include "ui/base/hit_test.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/views/widget/widget.h"

View File

@@ -1,257 +0,0 @@
// Copyright (c) 2014 The Chromium Authors. 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/views/inspectable_web_contents_view_views.h"
#include <memory>
#include <utility>
#include "base/memory/raw_ptr.h"
#include "shell/browser/ui/drag_util.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 "ui/base/models/image_model.h"
#include "ui/gfx/geometry/rounded_corners_f.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"
namespace electron {
namespace {
class DevToolsWindowDelegate : public views::ClientView,
public views::WidgetDelegate {
public:
DevToolsWindowDelegate(InspectableWebContentsViewViews* shell,
views::View* view,
views::Widget* widget)
: views::ClientView(widget, view),
shell_(shell),
view_(view),
widget_(widget) {
SetOwnedByWidget(true);
set_owned_by_client();
if (shell->GetDelegate())
icon_ = shell->GetDelegate()->GetDevToolsWindowIcon();
}
~DevToolsWindowDelegate() override = default;
// disable copy
DevToolsWindowDelegate(const DevToolsWindowDelegate&) = delete;
DevToolsWindowDelegate& operator=(const DevToolsWindowDelegate&) = delete;
// views::WidgetDelegate:
views::View* GetInitiallyFocusedView() override { return view_; }
std::u16string GetWindowTitle() const override { return shell_->GetTitle(); }
ui::ImageModel GetWindowAppIcon() override { return GetWindowIcon(); }
ui::ImageModel GetWindowIcon() override { return icon_; }
views::Widget* GetWidget() override { return widget_; }
const views::Widget* GetWidget() const override { return widget_; }
views::View* GetContentsView() override { return view_; }
views::ClientView* CreateClientView(views::Widget* widget) override {
return this;
}
// views::ClientView:
views::CloseRequestResult OnWindowCloseRequested() override {
shell_->inspectable_web_contents()->CloseDevTools();
return views::CloseRequestResult::kCannotClose;
}
private:
raw_ptr<InspectableWebContentsViewViews> shell_;
raw_ptr<views::View> view_;
raw_ptr<views::Widget> widget_;
ui::ImageModel icon_;
};
} // namespace
InspectableWebContentsView* CreateInspectableContentsView(
InspectableWebContents* inspectable_web_contents) {
return new InspectableWebContentsViewViews(inspectable_web_contents);
}
InspectableWebContentsViewViews::InspectableWebContentsViewViews(
InspectableWebContents* inspectable_web_contents)
: InspectableWebContentsView(inspectable_web_contents),
devtools_web_view_(new views::WebView(nullptr)),
title_(u"Developer Tools") {
if (!inspectable_web_contents_->is_guest() &&
inspectable_web_contents_->GetWebContents()->GetNativeView()) {
auto* contents_web_view = new views::WebView(nullptr);
contents_web_view->SetWebContents(
inspectable_web_contents_->GetWebContents());
contents_view_ = contents_web_view_ = contents_web_view;
} else {
contents_view_ = new views::Label(u"No content under offscreen mode");
}
devtools_web_view_->SetVisible(false);
AddChildView(devtools_web_view_.get());
AddChildView(contents_view_.get());
}
InspectableWebContentsViewViews::~InspectableWebContentsViewViews() {
if (devtools_window_)
inspectable_web_contents()->SaveDevToolsBounds(
devtools_window_->GetWindowBoundsInScreen());
}
views::View* InspectableWebContentsViewViews::GetView() {
return this;
}
void InspectableWebContentsViewViews::SetCornerRadii(
const gfx::RoundedCornersF& corner_radii) {
// WebView won't exist for offscreen rendering.
if (contents_web_view_) {
contents_web_view_->holder()->SetCornerRadii(
gfx::RoundedCornersF(corner_radii));
}
}
void InspectableWebContentsViewViews::ShowDevTools(bool activate) {
if (devtools_visible_)
return;
devtools_visible_ = true;
if (devtools_window_) {
devtools_window_web_view_->SetWebContents(
inspectable_web_contents_->GetDevToolsWebContents());
devtools_window_->SetBounds(inspectable_web_contents()->dev_tools_bounds());
if (activate) {
devtools_window_->Show();
} else {
devtools_window_->ShowInactive();
}
// Update draggable regions to account for the new dock position.
if (GetDelegate())
GetDelegate()->DevToolsResized();
} else {
devtools_web_view_->SetVisible(true);
devtools_web_view_->SetWebContents(
inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_view_->RequestFocus();
DeprecatedLayoutImmediately();
}
}
void InspectableWebContentsViewViews::CloseDevTools() {
if (!devtools_visible_)
return;
devtools_visible_ = false;
if (devtools_window_) {
auto save_bounds = devtools_window_->IsMinimized()
? devtools_window_->GetRestoredBounds()
: devtools_window_->GetWindowBoundsInScreen();
inspectable_web_contents()->SaveDevToolsBounds(save_bounds);
devtools_window_.reset();
devtools_window_web_view_ = nullptr;
devtools_window_delegate_ = nullptr;
} else {
devtools_web_view_->SetVisible(false);
devtools_web_view_->SetWebContents(nullptr);
DeprecatedLayoutImmediately();
}
}
bool InspectableWebContentsViewViews::IsDevToolsViewShowing() {
return devtools_visible_;
}
bool InspectableWebContentsViewViews::IsDevToolsViewFocused() {
if (devtools_window_web_view_)
return devtools_window_web_view_->HasFocus();
else if (devtools_web_view_)
return devtools_web_view_->HasFocus();
else
return false;
}
void InspectableWebContentsViewViews::SetIsDocked(bool docked, bool activate) {
CloseDevTools();
if (!docked) {
devtools_window_ = std::make_unique<views::Widget>();
devtools_window_web_view_ = new views::WebView(nullptr);
devtools_window_delegate_ = new DevToolsWindowDelegate(
this, devtools_window_web_view_, devtools_window_.get());
views::Widget::InitParams params{
views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET};
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.delegate = devtools_window_delegate_;
params.bounds = inspectable_web_contents()->dev_tools_bounds();
#if BUILDFLAG(IS_LINUX)
params.wm_role_name = "devtools";
if (GetDelegate())
GetDelegate()->GetDevToolsWindowWMClass(&params.wm_class_name,
&params.wm_class_class);
#endif
devtools_window_->Init(std::move(params));
devtools_window_->UpdateWindowIcon();
devtools_window_->widget_delegate()->SetHasWindowSizeControls(true);
}
ShowDevTools(activate);
}
void InspectableWebContentsViewViews::SetContentsResizingStrategy(
const DevToolsContentsResizingStrategy& strategy) {
strategy_.CopyFrom(strategy);
DeprecatedLayoutImmediately();
}
void InspectableWebContentsViewViews::SetTitle(const std::u16string& title) {
if (devtools_window_) {
title_ = title;
devtools_window_->UpdateWindowTitle();
}
}
const std::u16string InspectableWebContentsViewViews::GetTitle() {
return title_;
}
void InspectableWebContentsViewViews::Layout(PassKey) {
if (!devtools_web_view_->GetVisible()) {
contents_view_->SetBoundsRect(GetContentsBounds());
// Propagate layout call to all children, for example browser views.
LayoutSuperclass<View>(this);
return;
}
gfx::Size container_size(width(), height());
gfx::Rect new_devtools_bounds;
gfx::Rect new_contents_bounds;
ApplyDevToolsContentsResizingStrategy(
strategy_, container_size, &new_devtools_bounds, &new_contents_bounds);
// DevTools cares about the specific position, so we have to compensate RTL
// layout here.
new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds));
new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds));
devtools_web_view_->SetBoundsRect(new_devtools_bounds);
contents_view_->SetBoundsRect(new_contents_bounds);
// Propagate layout call to all children, for example browser views.
LayoutSuperclass<View>(this);
if (GetDelegate())
GetDelegate()->DevToolsResized();
}
} // namespace electron

View File

@@ -1,63 +0,0 @@
// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#ifndef ELECTRON_SHELL_BROWSER_UI_VIEWS_INSPECTABLE_WEB_CONTENTS_VIEW_VIEWS_H_
#define ELECTRON_SHELL_BROWSER_UI_VIEWS_INSPECTABLE_WEB_CONTENTS_VIEW_VIEWS_H_
#include <memory>
#include "base/compiler_specific.h"
#include "base/memory/raw_ptr.h"
#include "chrome/browser/devtools/devtools_contents_resizing_strategy.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "ui/views/view.h"
namespace views {
class WebView;
class Widget;
class WidgetDelegate;
} // namespace views
namespace electron {
class InspectableWebContentsViewViews : public InspectableWebContentsView,
public views::View {
public:
explicit InspectableWebContentsViewViews(
InspectableWebContents* inspectable_web_contents);
~InspectableWebContentsViewViews() override;
// InspectableWebContentsView:
views::View* GetView() override;
void ShowDevTools(bool activate) override;
void SetCornerRadii(const gfx::RoundedCornersF& corner_radii) override;
void CloseDevTools() override;
bool IsDevToolsViewShowing() override;
bool IsDevToolsViewFocused() override;
void SetIsDocked(bool docked, bool activate) override;
void SetContentsResizingStrategy(
const DevToolsContentsResizingStrategy& strategy) override;
void SetTitle(const std::u16string& title) override;
const std::u16string GetTitle() override;
// views::View:
void Layout(PassKey) override;
private:
std::unique_ptr<views::Widget> devtools_window_;
raw_ptr<views::WebView> devtools_window_web_view_ = nullptr;
raw_ptr<views::WebView> contents_web_view_ = nullptr;
raw_ptr<views::View> contents_view_ = nullptr;
raw_ptr<views::WebView> devtools_web_view_ = nullptr;
DevToolsContentsResizingStrategy strategy_;
bool devtools_visible_ = false;
raw_ptr<views::WidgetDelegate> devtools_window_delegate_ = nullptr;
std::u16string title_;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_UI_VIEWS_INSPECTABLE_WEB_CONTENTS_VIEW_VIEWS_H_

View File

@@ -819,4 +819,8 @@ const char* SimpleURLLoaderWrapper::GetTypeName() {
return "SimpleURLLoaderWrapper";
}
void SimpleURLLoaderWrapper::WillBeDestroyed() {
ClearWeak();
}
} // namespace electron::api

View File

@@ -66,6 +66,9 @@ class SimpleURLLoaderWrapper final
v8::Isolate* isolate) override;
const char* GetTypeName() override;
// gin_helper::CleanedUpAtExit
void WillBeDestroyed() override;
private:
SimpleURLLoaderWrapper(ElectronBrowserContext* browser_context,
std::unique_ptr<network::ResourceRequest> request,

View File

@@ -0,0 +1,25 @@
// Copyright (c) 2025 Salesforce, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/common/gin_converters/service_worker_converter.h"
#include "base/containers/fixed_flat_map.h"
namespace gin {
// static
v8::Local<v8::Value> Converter<blink::EmbeddedWorkerStatus>::ToV8(
v8::Isolate* isolate,
const blink::EmbeddedWorkerStatus& val) {
static constexpr auto Lookup =
base::MakeFixedFlatMap<blink::EmbeddedWorkerStatus, std::string_view>({
{blink::EmbeddedWorkerStatus::kStarting, "starting"},
{blink::EmbeddedWorkerStatus::kRunning, "running"},
{blink::EmbeddedWorkerStatus::kStopping, "stopping"},
{blink::EmbeddedWorkerStatus::kStopped, "stopped"},
});
return StringToV8(isolate, Lookup.at(val));
}
} // namespace gin

View File

@@ -0,0 +1,21 @@
// Copyright (c) 2025 Salesforce, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_COMMON_GIN_CONVERTERS_SERVICE_WORKER_CONVERTER_H_
#define ELECTRON_SHELL_COMMON_GIN_CONVERTERS_SERVICE_WORKER_CONVERTER_H_
#include "gin/converter.h"
#include "third_party/blink/public/common/service_worker/embedded_worker_status.h"
namespace gin {
template <>
struct Converter<blink::EmbeddedWorkerStatus> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const blink::EmbeddedWorkerStatus& val);
};
} // namespace gin
#endif // ELECTRON_SHELL_COMMON_GIN_CONVERTERS_SERVICE_WORKER_CONVERTER_H_

View File

@@ -27,11 +27,14 @@ CleanedUpAtExit::~CleanedUpAtExit() {
std::erase(GetDoomed(), this);
}
void CleanedUpAtExit::WillBeDestroyed() {}
// static
void CleanedUpAtExit::DoCleanup() {
auto& doomed = GetDoomed();
while (!doomed.empty()) {
CleanedUpAtExit* next = doomed.back();
next->WillBeDestroyed();
delete next;
}
}

View File

@@ -19,6 +19,8 @@ class CleanedUpAtExit {
CleanedUpAtExit();
virtual ~CleanedUpAtExit();
virtual void WillBeDestroyed();
static void DoCleanup();
};

View File

@@ -4,6 +4,7 @@
#include "shell/common/gin_helper/wrappable.h"
#include "gin/public/isolate_holder.h"
#include "shell/common/gin_helper/dictionary.h"
#include "v8/include/v8-function.h"
@@ -60,8 +61,10 @@ void WrappableBase::InitWith(v8::Isolate* isolate,
// static
void WrappableBase::FirstWeakCallback(
const v8::WeakCallbackInfo<WrappableBase>& data) {
auto* wrappable = static_cast<WrappableBase*>(data.GetInternalField(0));
if (wrappable) {
WrappableBase* wrappable = data.GetParameter();
auto* wrappable_from_field =
static_cast<WrappableBase*>(data.GetInternalField(0));
if (wrappable && wrappable == wrappable_from_field) {
wrappable->wrapper_.Reset();
data.SetSecondPassCallback(SecondWeakCallback);
}
@@ -70,6 +73,9 @@ void WrappableBase::FirstWeakCallback(
// static
void WrappableBase::SecondWeakCallback(
const v8::WeakCallbackInfo<WrappableBase>& data) {
if (gin::IsolateHolder::DestroyedMicrotasksRunner()) {
return;
}
delete static_cast<WrappableBase*>(data.GetInternalField(0));
}

View File

@@ -49,39 +49,40 @@
#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) \
#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_service_worker_main) \
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) \
@@ -649,7 +650,6 @@ std::shared_ptr<node::Environment> NodeBindings::CreateEnvironment(
context->SetAlignedPointerInEmbedderData(kElectronContextEmbedderDataIndex,
static_cast<void*>(isolate_data));
node::Environment* env;
uint64_t env_flags = node::EnvironmentFlags::kDefaultFlags |
node::EnvironmentFlags::kHideConsoleWindows |
node::EnvironmentFlags::kNoGlobalSearchPaths |
@@ -675,24 +675,10 @@ std::shared_ptr<node::Environment> NodeBindings::CreateEnvironment(
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;
}
}
node::Environment* env = electron::util::CreateEnvironment(
isolate, static_cast<node::IsolateData*>(isolate_data), context, args,
exec_args, static_cast<node::EnvironmentFlags::Flags>(env_flags),
process_type);
DCHECK(env);
node::IsolateSettings is;

View File

@@ -5,7 +5,12 @@
#include "shell/common/node_util.h"
#include "base/compiler_specific.h"
#include "base/containers/to_value_list.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "gin/converter.h"
#include "gin/dictionary.h"
#include "shell/browser/javascript_environment.h"
@@ -76,4 +81,51 @@ base::span<uint8_t> as_byte_span(v8::Local<v8::Value> node_buffer) {
return UNSAFE_BUFFERS(base::span{data, size});
}
node::Environment* CreateEnvironment(v8::Isolate* isolate,
node::IsolateData* isolate_data,
v8::Local<v8::Context> context,
const std::vector<std::string>& args,
const std::vector<std::string>& exec_args,
node::EnvironmentFlags::Flags env_flags,
std::string_view process_type) {
v8::TryCatch try_catch{isolate};
node::Environment* env = node::CreateEnvironment(isolate_data, context, args,
exec_args, env_flags);
if (auto message = try_catch.Message(); !message.IsEmpty()) {
base::Value::Dict dict;
if (std::string str; gin::ConvertFromV8(isolate, message->Get(), &str))
dict.Set("message", std::move(str));
if (std::string str; gin::ConvertFromV8(
isolate, message->GetScriptOrigin().ResourceName(), &str)) {
const auto line_num = message->GetLineNumber(context).FromJust();
const auto line_str = base::NumberToString(line_num);
dict.Set("location", base::StrCat({", at ", str, ":", line_str}));
}
if (std::string str; gin::ConvertFromV8(
isolate, message->GetSourceLine(context).ToLocalChecked(), &str))
dict.Set("source_line", std::move(str));
if (!std::empty(process_type))
dict.Set("process_type", process_type);
if (auto list = base::ToValueList(args); !std::empty(list))
dict.Set("args", std::move(list));
if (auto list = base::ToValueList(exec_args); !std::empty(list))
dict.Set("exec_args", std::move(list));
std::string errstr = "Failed to initialize Node.js.";
if (std::optional<std::string> jsonstr = base::WriteJsonWithOptions(
dict, base::JsonOptions::OPTIONS_PRETTY_PRINT))
errstr += base::StrCat({" ", *jsonstr});
LOG(ERROR) << errstr;
}
return env;
}
} // namespace electron::util

View File

@@ -5,6 +5,7 @@
#ifndef ELECTRON_SHELL_COMMON_NODE_UTIL_H_
#define ELECTRON_SHELL_COMMON_NODE_UTIL_H_
#include <string>
#include <string_view>
#include <vector>
@@ -13,7 +14,13 @@
namespace node {
class Environment;
class IsolateData;
struct ThreadId;
namespace EnvironmentFlags {
enum Flags : uint64_t;
}
} // namespace node
namespace electron::util {
@@ -37,6 +44,15 @@ v8::MaybeLocal<v8::Value> CompileAndCall(
std::vector<v8::Local<v8::String>>* parameters,
std::vector<v8::Local<v8::Value>>* arguments);
// Wrapper for node::CreateEnvironment that logs failure
node::Environment* CreateEnvironment(v8::Isolate* isolate,
node::IsolateData* isolate_data,
v8::Local<v8::Context> context,
const std::vector<std::string>& args,
const std::vector<std::string>& exec_args,
node::EnvironmentFlags::Flags env_flags,
std::string_view process_type = "");
// Convenience function to view a Node buffer's data as a base::span().
// Analogous to base::as_byte_span()
[[nodiscard]] base::span<uint8_t> as_byte_span(

Some files were not shown because too many files have changed in this diff Show More