* refactor: use main in release-notes
* fix: use default_branch in release-notes (#29415)
Co-authored-by: Jeremy Rose <nornagon@nornagon.net>
Co-authored-by: Jeremy Rose <jeremya@chromium.org>
* build: include mksnapshot args in arm64 mksnapshot.zip
* get gen/v8/embedded.S from proper location
(cherry picked from commit d0b9a931cc)
Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org>
All the other argument headers were h3 (`###`) but `--force-fieldtrials` was h2 (`##`) for some reason.
I changed it to make it consistent with the others.
Co-authored-by: Noelle Leigh <5957867+noelleleigh@users.noreply.github.com>
* build: use goma for all release builds
* Make sure goma is setup everywhere it is needed
* Show ninja stats on release builds
Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org>
* fix: allow Node.js to manage microtasks queue
When `uv_run()` resulted in invocation of JS functions the microtask
queue checkpoint in Node's CallbackScope was a no-op because the
expected microtask queue policy was `kExplicit` and Electron ran under
`kScoped` policy. This change switches policy to `kExplicit` right
before `uv_run()` and reverts it back to original value after `uv_run()`
completes to provide better compatibility with Node.
* add comment
Co-authored-by: Fedor Indutny <fedor@indutny.com>
This page is just a table writing out the contents of an array in
the Chromium source code. We don't actively maintain it, and
it's only referenced in one API, so it makes sense to just
link directly to the code here.
Co-authored-by: Erick Zhao <erick@hotmail.ca>
When creating a widget on linux the bounds are restricted to the screen
size, when calling SetSize / SetBounds they are not. This fixes this
initialization issue by calling SetBounds after widget creation.
Noticed this issue while running linux tests on xvfb with a screen size
smaller than the default electron window size (resulted in a failed
test).
Co-authored-by: Samuel Attard <samuel.r.attard@gmail.com>
This fixes a flake on linux CI which started recently where the "write"
promise is being rejected after the request has been aborted /
cancelled. In this case we should drop the error to the floor but
instead we pass it down the stack where it eventually emits a now
unhandled error event.
Example failure: https://app.circleci.com/pipelines/github/electron/electron/38072/workflows/c1faf19b-aa41-4f99-a564-165729222859/jobs/838813
Verified fix by running the test that caused it 10000 times before fix
and 10000 times after. ~50 failures before, 0 after.
Co-authored-by: Samuel Attard <samuel.r.attard@gmail.com>
* fix: move widget maximization check
* fix linting error
* change workaround to only effect transparent windows
* disable menu maximize and restore for transparent windows
* disable double clicking title bar max/unmax for transparent windows
* add docs change and address review
Co-authored-by: Michaela Laurencin <35157522+mlaurencin@users.noreply.github.com>
* fix: call `UnregisterIsolate` consistently
`JavascriptEnvironment` is the class that calls `RegisterIsolate()`
so it should be the one to call `UnregisterIsolate`, and this can happen
right before disposing the aforementioned `isolate`.
See: https://github.com/electron/electron/pull/28468
* fix
Co-authored-by: Fedor Indutny <fedor@indutny.com>
* fix: reject task when description exceeds 260 characters
* Switched out wcslen() for size() [linear -> constant time]
* Included comment describing the need for the additional check
* Added information about character limit to documentation
* Added newline character to end of jump-list-category.md
Co-authored-by: SushiJackal <weingaben@gmail.com>
This seems to just have been missing here, leaking memory
(and breaking the API contract for Node.js embedding).
Co-authored-by: Anna Henningsen <anna@addaleax.net>
* Fix custom scheme not registered as service worker scheme
* ServiceWorker loaders do not have WebContents associated
* Add test for service worker
* Revert "Fix custom scheme not registered as service worker scheme"
This reverts commit a249235b22.
* Add scheme to ServiceWorkerSchemes
* Errors are not catched in executeJavaScript
Co-authored-by: Cheng Zhao <zcbenz@gmail.com>
desktopCapture.getSources() returns a promise which should resolve
when capturing finishes. Internally it creates an instance of
DesktopCapturer which is responsible for resolving or rejecting
the promise.
Between the time DesktopCapturer starts capturing frames and when
it finishes, it's possible for its handle to be GC'd leading to
it never resolving.
These changes pin the instance of DesktopCapturer until it either
finishes or errors.
fixes#25595
Co-authored-by: samuelmaddock <samuel.maddock@gmail.com>
* fix: handle a nil backgroundColor in win.getBackgroundColor()
* spec: add crash case
* fix: update to fix native_views transparent color
* chore: fix lint
Co-authored-by: Samuel Attard <sattard@slack-corp.com>
Co-authored-by: Samuel Attard <sam@electronjs.org>
* Add a condition to crashReporter deprecate log
When developer set submitURL to '' crash reports will be saved at `...\AppData\Roaming\...\Crashpad\reports`, will not be uploaded to the server.
So at this time `deprecate.log('Sending uncompressed crash reports....')` is unnecessary.
* Update lib/browser/api/crash-reporter.ts
change to check uploadToServer
Co-authored-by: Jeremy Rose <nornagon@nornagon.net>
Co-authored-by: liulun <xland@live.cn>
Co-authored-by: Jeremy Rose <nornagon@nornagon.net>
Move it from LoadURL to RenderViewCreated which is present
in all window creation cases and is called early enough to be
relevant from user prespective and after RenderWidgetHostView
is already present.
Co-authored-by: marekharanczyk <48673767+marekharanczyk@users.noreply.github.com>
* fix: replace default frameName title with null check (#27521)
* refactor: replace default frameName title with null check
* add isNativeWindowOpen check in makeBrowserWindowOptions
* modify snapshot test files
* replace title with frame-name again for proxy - not native open
* modify proxy snapshot title key-value to come after height key-value
* add nativewindowopen check to null title
* fix lint and json formatting
* reformat test cases for this branch
the merged changes included some rearrangements to the json items that
do not apply to this branch, so the items were reordered according to
this branch's previous files.
* remove default frameName title for native open call and modify test txts
* feat: Raise a browser view via `BrowserWindow.setTopBrowserView()`.
This is similar to removing and re-adding a browser view, but avoids a visible flicker as the browser view is not removed from the window when using `setTopBrowserView`. Note: if the given browser view is not attached to the window, it will be added.
This commit contains the macOS implementation.
* feat: setTopBrowserView support for Windows and Linux
* docs: add info about setTopBrowserView
* docs: Clarify behavior when browserView is not yet attached.
* fix: throw en error when browserView is not attached to the window
* fix: build error
* fix: test
* fix: add test case
* fix: tests
* fix: reparenting
* fix: close second window in tests
Co-authored-by: sentialx <sentialx@gmail.com>
Co-authored-by: Stewart Lord <stew@offbynone.com>
* docs: update menu example to avoid remote
* Update menu.md
* lint
Co-authored-by: Jeremy Rose <nornagon@nornagon.net>
Co-authored-by: Jeremy Rose <jeremya@chromium.org>
* Use std::forward_list instead of base::LinkedList for better perf,
more consistent memory management. Better than std::list because we
don't need the double-linked-list behavior of std::list
* Use std::unordered_map instead of std::map for the v8 hash table
Co-authored-by: Samuel Attard <sattard@slack-corp.com>
* fix: only run display check on restored wndow if minimized
* fix: don't run display check on hidden, non-minimized windows
Co-authored-by: VerteDinde <keeleymhammond@gmail.com>
base::LinkedList does not delete its members on destruction. We need to
manually ensure the linkedlist is empty when the ObjectCache is
destroyed.
Fixes#27039
Notes: Fixed memory leak when sending non-primitives over the context
bridge
Co-authored-by: Samuel Attard <sattard@slack-corp.com>
The call stack for one of our top crashes looks like this:
```
node::Abort (node_errors.cc:241)
node::Assert (node_errors.cc:256)
node::MakeCallback (callback.cc:226)
gin_helper::internal::CallMethodWithArgs (event_emitter_caller.cc:23)
gin_helper::EmitEvent<T> (event_emitter_caller.h:51)
gin_helper::EventEmitterMixin<T>::Emit<T> (event_emitter_mixin.h:81)
electron::api::DownloadItem::OnDownloadUpdated (electron_api_download_item.cc:115)
download::DownloadItemImpl::UpdateObservers (download_item_impl.cc:482)
content::DownloadManagerImpl::Shutdown (download_manager_impl.cc:508)
content::BrowserContext::~BrowserContext (browser_context.cc:476)
```
Full stack here: https://sentry.io/share/issue/9b030a0601b547188181b543c16ecda2/
During browser shutdown, the `DownloadManager` was being cleaned up
*after* the Node environment had already been destroyed. This caused the
`DownloadItem::OnDownloadUpdated` callback to crash when trying to emit
the JS `done` event.
To prevent this, we now manually shut down the `DownloadManager`
earlier. This is also mentioned in the comment on
`DownloadManager::Shutdown`:
```
// Shutdown the download manager. Content calls this when BrowserContext is
// being destructed. If the embedder needs this to be called earlier, it can
// call it. In that case, the delegate's Shutdown() method will only be called
// once.
```
Co-authored-by: Biru Mohanathas <birunthan@mohanathas.com>
* fix: prevent crash when destroyed widget receives keyboard event
Activating a key to close a window will cause a silent crash. Handling the keyboard
event will lead to a nullptr dereferenced in Chromium code if the window widget has
already been destroyed.
* test: ensure BrowserWindow doesn't crash from keyboard events during close
Co-authored-by: samuelmaddock <samuel.maddock@gmail.com>
* docs: update devtools extension tutorial
* Update docs/tutorial/devtools-extension.md
Co-authored-by: Jeremy Rose <nornagon@nornagon.net>
* update
Co-authored-by: Jeremy Rose <nornagon@nornagon.net>
Co-authored-by: Jeremy Rose <nornagon@nornagon.net>
* fix: Avoid crashing in NativeViewHost::SetParentAccessible on Windows
This fixes#26905. The patch was obtained from @deepak1556, who in turn
got it from the Microsoft Teams folks.
I believe the crash started happening due to the changes in
5c6c8e994b%5E!/#F15
This affects Electron 9 and later.
Notes: Fix occasional crash on Windows
* update patches
Co-authored-by: Biru Mohanathas <birunthan@mohanathas.com>
Co-authored-by: Electron Bot <electron@github.com>
This restores accessibility of screen methods via remote.screen.
Fixes#26610.
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
Co-authored-by: Anders Kaseorg <andersk@mit.edu>
* fix: use public APIs in place of private CTFontDescriptorIsSystemUIFont in ui/gfx
* Update .patches
Co-authored-by: Samuel Attard <samuel.r.attard@gmail.com>
Co-authored-by: Samuel Attard <sam@electronjs.org>
* build: fix usage of octokit/rest and make uploading better
* Pull in change from #26414
* Update with changes from #26425
Co-authored-by: Samuel Attard <samuel.r.attard@gmail.com>
Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org>
* fix: renderer crash on setImmediate
* spec: add a crash case
* fix: ensure env exists
* Update spec-main/fixtures/crash-cases/setimmediate-renderer-crash/index.js
Co-authored-by: Jeremy Rose <jeremya@chromium.org>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
Co-authored-by: Jeremy Rose <jeremya@chromium.org>
* chore: bump chromium in DEPS to 87.0.4280.47
* update patches
* Make sure angle has full git info
Co-authored-by: Electron Bot <anonymous@electronjs.org>
Co-authored-by: John Kleinschmidt <jkleinsc@github.com>
* fix: re-enable the spellchecker when new language list set
Chromium recently added prefs logic to disable the spellchecker if the list of languages is empty, but the logic to re-enable if the languages are provided again lives in another part of Chromium. This change makes it so our API re-enables the spellchecker correctly when required.
* chore: fix lint
* disable CalculateNativeWinOcclusion on win ci
* Update appveyor.yml
* disable CalculateNativeWinOcclusion for woa
Co-authored-by: Jeremy Rose <nornagon@nornagon.net>
Co-authored-by: Jeremy Rose <jeremya@chromium.org>
* Backport changes for notification timeout neber to version 11
* fix: notifications successfully never timeout with included flag
* Add back SetXmlAudioSilent
Co-authored-by: mlaurencin <mlaurencin@microsoft.com>
If speculative render view host is deleted during naviagation to
page we try to open with call to window.open window is destroyed
right after it is created. It may happen when naviagation triggers
redirect from http to https. To void that we should emit event
current-render-view-deleted only when render view host which was
destroyed is the current webcontent's rvh.
Co-authored-by: Cezary Kulakowski <cezary@openfin.co>
* feat: add webContents.crashProcess() to forcefully terminate a renderer process
* chore: fix up docs and tests
Co-authored-by: Samuel Attard <samuel.r.attard@gmail.com>
`chrome://flash` doesn't seem to exist anymore, but similar information
appears at `chrome://version`.
Co-authored-by: Joe Duncko <JoeDuncko@users.noreply.github.com>
* fix: prevent destroyed view references from causing crashes
* Remove extraneous comments
* Relocate crash test to proper location
* Add WebContentsObserver
* Add nullptr check and inspectable observer
* Remote initial test file
* Add test cases to test file
* Rename and move testing file
* Fix linting errors
* Make functions exit early on check
* Fix setBackgroundColor function call in test file
* Fix styling of test file
* Fix mac name mismatch and make variable name more clear
Co-authored-by: Michaela Laurencin <mlaurencin@microsoft.com>
* fix: call node::Stop on exit
* also call Stop in node_main
* oop, we were already calling set_can_call_into_js(false)??
Co-authored-by: Jeremy Rose <nornagon@nornagon.net>
* Ensure electron delay loads the appropriate modules as chromium on windows
This change adds the same module delay load list that chromium uses for electron. Some modules were already getting delay loaded from other build files in chromium but not the main list via //build/config/win:delayloads. We do not include the list of delay loads in delayloads_not_for_child_dll as those have issues being loaded in sandboxes processes. This will reduce the overall reference set impact of the electron processes.
* fix: Ensure win modules are properly delayloaded
* chore: fix linting
Co-authored-by: Chris Davis <chrisdavis@outlook.com>
Co-authored-by: Samuel Attard <samuel.r.attard@gmail.com>
refactor(extensions): remove unused InitWithBrowserContext method
fix(extensions): release background page WebContents to avoid crash
The background page WebContents instance is managed by the ExtensionHost.
fix(extensions): open background page devtools detached by default
test(extensions): add background page devtools test
chore: test fix for null web_contents()
fix: close background page devtools in test after opening
Co-authored-by: samuelmaddock <samuel.maddock@gmail.com>
* chore: graceful handling of notes with sub-lists
Handle multine release notes that contain their own bullet points.
Also, if a release note begins with a bullet point, remove it because it
will confuse the markdown parser to have two bullet points.
* chore: make lint happy
* test: add tests for release note changes
* chore: only target current octokit
* chore: add commits to release-notes test cache
No behavior change; just includes files that ought to be cached to prevent
hitting octokit for them.
Co-authored-by: Charles Kerr <charles@charleskerr.com>
* ci: cleanup up test app directories
* ci: use electron prefix for a testing apps so that the can be cleaned up
* Revert "ci: cleanup up test app directories"
This reverts commit a47daba812.
* fixup test due to app name change
Co-authored-by: John Kleinschmidt <jkleinsc@github.com>
* docs: add restricted header info to docs
* docs: clarify header language
Co-authored-by: Jeremy Rose <nornagon@nornagon.net>
Co-authored-by: Jeremy Rose <nornagon@nornagon.net>
* tests: fix failing WOA tests
tests: fix startDrag for WOA
tests: fix early-in-memory-session-create crash test on WOA
ci: cleanup user app data directories on WOA
* tests: disable nativeImage.createFromBuffer tests on WOA
* disable failing nativeImage.createFromPath on WOA
* disable another nativeImage test for WOA
* initial commit, mac implementation
* add documentation
* convert createThumbnailFromPath to async function
* windows impl protoype
* add tests
* added test
* fix
* fix test
* clean up
* update docs
* cleaning up code
* fix test
* retrigger CI
* retrigger CI
* refactor from app to native_image
* windows build
* lint
* lint
* add smart pointers, fix test
* change tests and update docs
* fix test, remove nolint
* add renderer-main process routing to fix tests
* lint
* thanks sam
* thanks sam
* feat: add optional font type to macOS tray title
* test: add tests for tray font type
* docs: update API reference for Tray setTitle
* review: change API to use an options object
* review: fix string enum in docs
Co-authored-by: Samuel Attard <samuel.r.attard@gmail.com>
* review: return after throwing errors
* review: don't need thrower anymore now that we have args
Co-authored-by: Samuel Attard <samuel.r.attard@gmail.com>
* build: more space on arm64 builds, running out of ideas here
* build: well this is kinda nuts but off we go
* chore: rollback thingy
* chore: build snapshot for realz
* chore: do not delete hunspell
* build: use the new magic extra-disk-space circle image
* build: remove existing file, it is not a tree
removes an outdated reference to Node Security Project, which was acquired by npm some time ago. The new workflow for the same process (now the npm advisories page) has been added.
* refactor: use js instead of boto for s3put
* replace merge-electron-checksums.py with js, remove boto
* fix auth
* actually pass the env to execute()
* fix: export libuv symbols
* add test for linux and windows
* mac linker flags
* assuming same foo.so path for macos
* use --whole-archive flag for mac as well
* use force_load for mac
* refactor: use napi c api directly
Co-authored-by: Cheng Zhao <zcbenz@gmail.com>
* fix: increase max crash key value length
* chore: fix linting
* chore: fix linux
* Update spec-main/api-crash-reporter-spec.ts
Co-authored-by: Jeremy Rose <jeremya@chromium.org>
Co-authored-by: Samuel Attard <samuel.r.attard@gmail.com>
Co-authored-by: Samuel Attard <sattard@slack-corp.com>
* fix: generate dumps under crashDumps folder in linux
* Update spec-main/api-crash-reporter-spec.ts
Co-authored-by: Jeremy Rose <jeremya@chromium.org>
Co-authored-by: Jeremy Rose <jeremya@chromium.org>
Trop annotations are in the form of "(Also in 7.3, 8, 9)" with links to
the sibling branches.
Previously seen in b43e601b83 but is now
free of optional chaining and nullish coalescing, to run on Node < 14 :)
* feat: add worldSafe flag for executeJS results
* chore: do not log warning for webContents.executeJS
* Apply suggestions from code review
Co-authored-by: Jeremy Rose <jeremya@chromium.org>
* chore: apply PR feedback
* chore: split logic a bit
* chore: allow primitives through the world safe checl
* chore: clean up per PR feedback
* chore: flip boolean logic
* chore: update per PR feedback
* chore: fix typo
* chore: fix spec
Co-authored-by: Jeremy Rose <jeremya@chromium.org>
* fix: Use ElectronAdaptedContentView
* fix: Actually, nevermind, it's "BrowserAccessebilityCocoa"
* chore: Remove things instead of manually keeping them
* perf: do not convert object keys in ctx bridge as they are always primitives
* Update shell/renderer/api/electron_api_context_bridge.cc
Co-authored-by: Jeremy Rose <jeremya@chromium.org>
Co-authored-by: Jeremy Rose <jeremya@chromium.org>
* build: add arm64 macOS publish jobs
* update ci-release-build to run new arm64 macOS publish jobs
* fixup circleci config validate issues
Co-authored-by: John Kleinschmidt <jkleinsc@github.com>
* fix: use Node.js isolate setup logic in bindings
* Flags should be more process-specific
* Remove redundant isolate function setting
* Remove old SetFatalErrorHandler call
* chore: add patches to prevent installation of non-arm pip packages
* chore: add patches for apple-silicon
* build: add apple silicon build
* ci: add testing of new arm binary
* chore: remove / update for upstreamed patches
* Skip content tracing on macos on arm
* build: ensure that spec native modules are rebuilt for arm64 on apple-silicon
* chore: fix patches
* chore: fix broken patch
* chore: fix arm64 DCHECK
* build: add MAS arm64 build
* build: disable arm2 tests
* chore: update patches
* build: actually build MAS version of apple silicon app
Co-authored-by: John Kleinschmidt <jkleinsc@github.com>
Address incorrect typing for isEnabled. The root cause of this was due
to missing backticks which caused the docs parser to think that the
return type of the `isEnabled` function was null, where it was supposed
to be a boolean type.
The side effect of this was that the generated typescript typings were
incorrect for this function.
Fixes#24409
* build: build squirrel and its dependencies from source
* chore: do not use fork for squirrel.mac
* build: do not ship headers with dependency frameworks
* Update BUILD.gn
* chore: s/striped/stripped
* chore: update as per feedback
* chore: use ARC and fix build errors
* chore: fix ARC Squirrel self retainer
* chore: add deprecation warning for the default of contextIsolation
* chore: add to breaking changes
* Update docs/breaking-changes.md
Co-authored-by: Jeremy Apthorp <jeremya@chromium.org>
* chore: fix specs on windows
Co-authored-by: Jeremy Apthorp <jeremya@chromium.org>
This PR improves the Electron REPL experience. It adds a welcome message to the REPL to let users know what versions of Node.js and Electron they're running, as well as overriding the completer function in the REPL to preload and add tab autocompletion for Electron's own modules.
* fix: let Node.js perform microtask checkpoint in the main process
* fix: don't specify v8::MicrotasksScope for explicit policy
* fix: remove checkpoint from some call-sites
We already perform checkpoint at the end of a task,
either through MicrotaskRunner or through NodeBindings.
There isn't a need to add them again when calling into JS
except when dealing with promises.
* fix: remove checkpoint from some call-sites
We already perform checkpoint at the end of a task,
either through MicrotaskRunner or through NodeBindings.
There isn't a need to add them again when calling into JS
except when dealing with promises.
* fix incorrect specs
* default constructor arguments are considered for explicit mark
* add regression spec
* chore: ensure release notes always come from Clerk
Now with tests!
* chore: move sinon devDependency into `spec-main`
* refactor: tweak note-spec variable for readability
* fix: notify URLLoaderClient about redirect inside intercepted protocol's handler
* fix: update new_request's site_for_coookies
* fix: Unound client, so it an be passed to sub-methods
The devtools profiler is not attached at the point we run out init scripts (or our apps preload scripts), we do not really want to change when we run these init scripts but for when a dev is doing performance work it makes sense to give them an option to make the devtools profiler actually work on both our init scripts and their preload script. This PR adds that logic behind an environment variable ELECTRON_PROFILE_INIT_SCRIPTS.
* chore: bump chromium in DEPS to db7d7b3e7cb2bc925f2abfde526280cfdfc21a41
* Update patches
* chore: bump chromium in DEPS to 5613e1b99a44fcbe22f3910f803ca76903a77ec1
* Update patches
* Network service: Remove primary_network_context bool.
https://chromium-review.googlesource.com/c/chromium/src/+/2204678
* WebContentsObserver now implements OnRendererResponsive
https://chromium-review.googlesource.com/c/chromium/src/+/2211066
* update patches
* Fixup printing patch
* chore: bump chromium in DEPS to e387b972cdd7160c416fa6c64a724e2258aa0218
* update patches
* [printing] Move PrintHostMsg_DidPrintContent_Params to print.mojom
https://chromium-review.googlesource.com/c/chromium/src/+/2212110
* [XProto] Move items from ::x11::XProto to ::x11
https://chromium-review.googlesource.com/c/chromium/src/+/2218476
* revert Add IChromeAccessible
This was added in https://chromium-review.googlesource.com/c/chromium/src/+/2206224 but it breaks WOA builds because third_party/win_build_output/midl/ui/accessibility/platform/arm64 does not exist. The link above says that the new interface is behind a feature flag which is disabled by default so it is safe to remove for now.
* rebaseline ichromeaccessible for Windows arm64
This patch will not be needed once we get the next roll.
* Update to 1b9e01844e8bf1aaafc4a52c0c62af7f56d9637b to get arm64 fix
* update patches
* chore: bump chromium in DEPS to 096aefa04092ea00f7b68d8d19345883f20db3c3
* chore: bump chromium in DEPS to a524a45ffd1d6fd46a7a86138fe2b22df5b6651a
* chore: update patches
* Window Placement: Gate cross-screen fullscreen behavior on permission
https://chromium-review.googlesource.com/c/chromium/src/+/2203268
* chore: add spec for https://crbug.com/1085836
* chore: bump chromium in DEPS to ff6c4f4b826d66c2e32380bf5d1eb5e1fe37faef
* update patches
Co-authored-by: John Kleinschmidt <jkleinsc@github.com>
Co-authored-by: Electron Bot <anonymous@electronjs.org>
Co-authored-by: deepak1556 <hop2deep@gmail.com>
When application is activated thru macOS app switcher (cmd+tab) the
App's activate event is note emitted. The reason is that
`applicationShouldHandleReopen:hasVisibleWindows:` is sent only when app
is activated via Dock. Using `applicationDidBecomeActive:` is handling
all cases properly.
Co-authored-by: Lukas Weber <luweber@microsoft.com>
* chore: tsify more of lib
* Update lib/browser/api/session.ts
Co-authored-by: Jeremy Apthorp <jeremya@chromium.org>
Co-authored-by: Jeremy Apthorp <jeremya@chromium.org>
* feat: Add Secure Keyboard Entry APIs in macOS
Add methods:
- app.isSecureInputEnabled()
- app.setSecureInputEnabled(enabled)
These enable to prevent other process listens keyboard input events.
* fix: lint error in app.md for #20678
* fix: crash app.setSecureInputEnabled() in password textfield
* fix: export Secure keyboard Entry API to only macOS
* fix: lint error in browser_mac.mm for #20678
* test: add test for app.setSecureKeyboardEntryEnabled in macOS
We weren't serializing nativeImages properly in the remote module, leading to gin conversion errors when trying to, for example, create a new context menu in the renderer with icons using nativeImage. This fixes that by adding a new special case to handle them.
PR numbers are almost always listed parenthetically in the commit message;
but when something is committed manually, it could be missing. This change
uses octokit's listPullRequestsAssociatedWithCommit() as a second approach
to finding a commit's PR.
Last night's Releases WG meeting noted that "re-enable pdf viewer" was
missing from the notes. This PR fixes that omission.
In order for `badgeCount` to properly update the dock icon on
macOS, the application needs to have the permissions to display
notifications.
Cross-refs #22715.
- [ ] PR title follows semantic [commit guidelines](https://github.com/electron/electron/blob/master/docs/development/pull-requests.md#commit-message-guidelines)
- [ ] [PR release notes](https://github.com/electron/clerk/blob/master/README.md) describe the change in a way relevant to app developers, and are [capitalized, punctuated, and past tense](https://github.com/electron/clerk/blob/master/README.md#examples).
- [ ] This is **NOT A BREAKING CHANGE**. Breaking changes may not be merged to master until 11-x-y is branched.
View these docs in other languages at [electron/i18n](https://github.com/electron/i18n/tree/master/content/).
The Electron framework lets you write cross-platform desktop applications
@@ -28,15 +28,12 @@ The preferred method is to install Electron as a development dependency in your
app:
```sh
npm install electron --save-dev[--save-exact]
npm install electron --save-dev
```
The `--save-exact` flag is recommended for Electron prior to version 2, as it does not follow semantic
versioning. As of version 2.0.0, Electron follows semver, so you don't need `--save-exact` flag. For info on how to manage Electron versions in your apps, see
@@ -6,7 +6,11 @@ To report a security issue, email [security@electronjs.org](mailto:security@elec
The Electron team will send a response indicating the next steps in handling your report. After the initial reply to your report, the security team will keep you informed of the progress towards a fix and full announcement, and may ask for additional information or guidance.
Report security bugs in third-party modules to the person or team maintaining the module. You can also report a vulnerability through the [Node Security Project](https://nodesecurity.io/report).
Report security bugs in third-party modules to the person or team maintaining the module. You can also report a vulnerability through the [npm contact form](https://www.npmjs.com/support) by selecting "I'm reporting a security vulnerability".
## The Electron Security Notification Process
For context on Electron's security notification process, please see the [Notifications](https://github.com/electron/governance/blob/master/wg-security/membership-and-notifications.md#notifications) section of the Security WG's [Membership and Notifications](https://github.com/electron/governance/blob/master/wg-security/membership-and-notifications.md) Governance document.
## Learning More About Security
To learn more about securing an Electron application, please see the [security tutorial](docs/tutorial/security.md).
- if "%RUN_TESTS%"=="true" ( echo Running test suite & node script/yarn test -- --enable-logging)
# CalculateNativeWinOcclusion is disabled due to https://bugs.chromium.org/p/chromium/issues/detail?id=1139022
- if "%RUN_TESTS%"=="true" ( echo Running test suite & node script/yarn test -- --trace-uncaught --enable-logging --disable-features=CalculateNativeWinOcclusion )
- cd ..
- if "%RUN_TESTS%"=="true" ( echo Verifying non proprietary ffmpeg & python electron\script\verify-ffmpeg.py --build-dir out\Default --source-root %cd% --ffmpeg-path out\ffmpeg )
- echo "About to verify mksnapshot"
- if "%RUN_TESTS%"=="true" ( gn desc out\Default v8:run_mksnapshot_default args > out\Default\mksnapshot_args )
@@ -608,8 +678,10 @@ Returns `String` - The current application directory.
*`music` Directory for a user's music.
*`pictures` Directory for a user's pictures.
*`videos` Directory for a user's videos.
*`recent` Directory for the user's recent files (Windows only).
*`logs` Directory for your app's log folder.
*`pepperFlashSystemPlugin` Full path to the system version of the Pepper Flash plugin.
*`crashDumps` Directory where crash dumps are stored.
Returns `String` - A path to a special directory or file associated with `name`. On
failure, an `Error` is thrown.
@@ -677,7 +749,8 @@ Overrides the current application's name.
### `app.getLocale()`
Returns `String` - The current application locale. Possible return values are documented [here](locales.md).
Returns `String` - The current application locale, fetched using Chromium's `l10n_util` library.
Possible return values are documented [here](https://source.chromium.org/chromium/chromium/src/+/master:ui/base/l10n/l10n_util.cc).
To set the locale, you'll want to use a command line switch at app startup, which may be found [here](https://github.com/electron/electron/blob/master/docs/api/command-line-switches.md).
@@ -779,6 +852,20 @@ Returns `String` - Name of the application handling the protocol, or an empty
This method returns the application name of the default handler for the protocol
*`url` String - a URL with the protocol name to check. Unlike the other
methods in this family, this accepts an entire URL, including `://` at a
minimum (e.g. `https://`).
Returns `Promise<Object>` - Resolve with an object containing the following:
*`icon` NativeImage - the display icon of the app handling the protocol.
*`path` String - installation path of the app handling the protocol.
*`name` String - display name of the app handling the protocol.
This method returns a promise that contains the application name, icon and path of the default handler for the protocol
(aka URI scheme) of a URL.
### `app.setUserTasks(tasks)` _Windows_
*`tasks` [Task[]](structures/task.md) - Array of `Task` objects
@@ -838,6 +925,10 @@ re-add a removed item to a custom category earlier than that will result in the
entire custom category being omitted from the Jump List. The list of removed
items can be obtained using `app.getJumpListSettings()`.
**Note:** The maximum length of a Jump List item's `description` property is
260 characters. Beyond this limit, the item will not be added to the Jump
List, nor will it be displayed.
Here's a very simple example of creating a custom Jump List:
```javascript
@@ -940,6 +1031,7 @@ if (!gotTheLock) {
// Create myWindow, load the rest of the app, etc...
app.whenReady().then(()=>{
myWindow=createWindow()
})
}
```
@@ -1055,8 +1147,10 @@ For `infoType` equal to `complete`:
For `infoType` equal to `basic`:
Promise is fulfilled with `Object` containing fewer attributes than when requested with `complete`. Here's an example of basic response:
```js
{auxAttributes:
{amdSwitchable:true,
{
auxAttributes:
{
amdSwitchable:true,
canSupportThreadedTextureMailbox:false,
directComposition:false,
directRendering:true,
@@ -1069,12 +1163,14 @@ For `infoType` equal to `basic`:
sandboxed:false,
softwareRendering:false,
supportsOverlays:false,
videoDecodeAcceleratorFlags:0},
gpuDevice:
[{active:true,deviceId:26657,vendorId:4098},
{active:false,deviceId:3366,vendorId:32902}],
machineModelName:'MacBookPro',
machineModelVersion:'11.5'}
videoDecodeAcceleratorFlags:0
},
gpuDevice:
[{active:true,deviceId:26657,vendorId:4098},
{active:false,deviceId:3366,vendorId:32902}],
machineModelName:'MacBookPro',
machineModelVersion:'11.5'
}
```
Using `basic` should be preferred if only basic information like `vendorId` or `driverId` is needed.
@@ -1126,6 +1222,13 @@ Returns `Object`:
should restore the state from the previous session. This indicates that the
app should restore the windows that were open the last time the app was
closed. This setting is not available on [MAS builds][mas-builds].
* `executableWillLaunchAtLogin` Boolean _Windows_ - `true` if app is set to open at login and its run key is not deactivated. This differs from `openAtLogin` as it ignores the `args` option, this property will be true if the given executable would be launched at login with **any** arguments.
*`launchItems` Object[] _Windows_
*`name` String _Windows_ - name value of a registry entry.
*`path` String _Windows_ - The executable to an app that corresponds to a registry entry.
*`args` String[] _Windows_ - the command-line arguments to pass to the executable.
*`scope` String _Windows_ - one of `user` or `machine`. Indicates whether the registry entry is under `HKEY_CURRENT USER` or `HKEY_LOCAL_MACHINE`.
*`enabled` Boolean _Windows_ - `true` if the app registry key is startup approved and therefore shows as `enabled` in Task Manager and Windows settings.
*`args` String[] (optional) _Windows_ - The command-line arguments to pass to
the executable. Defaults to an empty array. Take care to wrap paths in
quotes.
*`enabled` Boolean (optional) _Windows_ - `true` will change the startup approved registry key and `enable / disable` the App in Task Manager and Windows Settings.
Defaults to `true`.
*`name` String (optional) _Windows_ - value name to write into registry. Defaults to the app's AppUserModelId().
Set the app's login item settings.
To work with Electron's `autoUpdater` on Windows, which uses [Squirrel][Squirrel-Windows],
@@ -1196,7 +1301,7 @@ Show the app's about panel options. These options can be overridden with `app.se
* `authors` String[] (optional) _Linux_ - List of app authors.
* `website` String (optional) _Linux_ - The app's website.
* `iconPath` String (optional) _Linux_ _Windows_ - Path to the app's icon. On Linux, will be shown as 64x64 pixels while retaining aspect ratio.
* `iconPath` String (optional) _Linux_ _Windows_ - Path to the app's icon in a JPEG or PNG file format. On Linux, will be shown as 64x64 pixels while retaining aspect ratio.
Set the about panel options. This will override the values defined in the app's `.plist` file on macOS. See the [Apple docs][about-panel-options] for more details. On Linux, values must be set in order to be shown; there are no defaults.
@@ -1241,7 +1346,7 @@ systems Application folder. Use in combination with `app.moveToApplicationsFolde
* `conflictHandler` Function<Boolean> (optional) - A handler for potential conflict in move failure.
* `conflictHandler` Function\<Boolean> (optional) - A handler for potential conflict in move failure.
* `conflictType` String - The type of move conflict encountered by the handler; can be `exists` or `existsAndRunning`, where `exists` means that an app of the same name is present in the Applications directory and `existsAndRunning` means both that it exists and that it's presently running.
Returns `Boolean` - Whether the move was successful. Please note that if
@@ -1257,7 +1362,7 @@ method returns false. If we fail to perform the copy, then this method will
throw an error. The message in the error should be informative and tell
you exactly what went wrong.
By default, if an app of the same name as the one being moved exists in the Applications directory and is _not_ running, the existing app will be trashed and the active app moved into its place. If it _is_ running, the pre-existing running app will assume focus and the the previously active app will quit itself. This behavior can be changed by providing the optional conflict handler, where the boolean returned by the handler determines whether or not the move conflict is resolved with default behavior. i.e. returning `false` will ensure no further action is taken, returning `true` will result in the default behavior and the method continuing.
By default, if an app of the same name as the one being moved exists in the Applications directory and is _not_ running, the existing app will be trashed and the active app moved into its place. If it _is_ running, the pre-existing running app will assume focus and the previously active app will quit itself. This behavior can be changed by providing the optional conflict handler, where the boolean returned by the handler determines whether or not the move conflict is resolved with default behavior. i.e. returning `false` will ensure no further action is taken, returning `true` will result in the default behavior and the method continuing.
Would mean that if an app already exists in the user directory, if the user chooses to 'Continue Move' then the function would continue with its default behavior and the existing app will be trashed and the active app moved into its place.
### `app.isSecureKeyboardEntryEnabled()` _macOS_
Returns `Boolean` - whether `Secure Keyboard Entry` is enabled.
@@ -207,11 +204,15 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
*`opacity` Number (optional) - Set the initial opacity of the window, between 0.0 (fully
transparent) and 1.0 (fully opaque). This is only implemented on Windows and macOS.
*`darkTheme` Boolean (optional) - Forces using dark theme for the window, only works on
some GTK desktop environments. Default is [`nativeTheme.shouldUseDarkColors`](native-theme.md).
some GTK+3 desktop environments. Default is `false`.
*`transparent` Boolean (optional) - Makes the window [transparent](frameless-window.md#transparent-window).
Default is `false`. On Windows, does not work unless the window is frameless.
*`type` String (optional) - The type of window, default is normal window. See more about
this below.
*`visualEffectState` String (optional) - Specify how the material appearance should reflect window activity state on macOS. Must be used with the `vibrancy` property. Possible values are:
*`followWindow` - The backdrop should automatically appear active when the window is active, and inactive when it is not. This is the default.
*`active` - The backdrop should always appear active.
*`inactive` - The backdrop should always appear inactive.
*`titleBarStyle` String (optional) - The style of window title bar.
Default is `default`. Possible values are:
*`default` - Results in the standard gray opaque Mac title
@@ -271,7 +272,7 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
the `nodeIntegration` option and the APIs available to the preload script
are more limited. Read more about the option [here](sandbox-option.md).
*`enableRemoteModule` Boolean (optional) - Whether to enable the [`remote`](remote.md) module.
Default is `true`.
Default is `false`.
*`session` [Session](session.md#class-session) (optional) - Sets the session used by the
page. Instead of passing the Session object directly, you can also choose to
use the `partition` option instead, which accepts a partition string. When
@@ -348,6 +349,9 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
You can access this context in the dev tools by selecting the
'Electron Isolated Context' entry in the combo box at the top of the
Console tab.
*`worldSafeExecuteJavaScript` Boolean (optional) - If true, values returned from `webFrame.executeJavaScript` will be sanitized to ensure JS values
can't unsafely cross between worlds when using `contextIsolation`. The default
is `false`. In Electron 12, the default will be changed to `true`. _Deprecated_
*`nativeWindowOpen` Boolean (optional) - Whether to use native
`window.open()`. Defaults to `false`. Child windows will always have node
integration disabled unless `nodeIntegrationInSubFrames` is true. **Note:** This option is currently
@@ -385,6 +389,15 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
visible to users.
*`spellcheck` Boolean (optional) - Whether to enable the builtin spellchecker.
Default is `true`.
*`enableWebSQL` Boolean (optional) - Whether to enable the [WebSQL api](https://www.w3.org/TR/webdatabase/).
Default is `true`.
*`v8CacheOptions` String (optional) - Enforces the v8 code caching policy
used by blink. Accepted values are
*`none` - Disables code caching
*`code` - Heuristic based code caching
*`bypassHeatCheck` - Bypass code caching heuristics but with lazy compilation
*`bypassHeatCheckAndEagerCompile` - Same as above except compilation is eager.
Default policy is `code`.
When setting minimum or maximum window size with `minWidth`/`maxWidth`/
`minHeight`/`maxHeight`, it only constrains the users. It won't prevent you from
@@ -525,6 +538,12 @@ Note that this is only emitted when the window is being resized manually. Resizi
Emitted after the window has been resized.
#### Event: 'resized' _macOS_ _Windows_
Emitted once when the window has finished being resized.
This is usually emitted when the window has been resized manually. On macOS, resizing the window with `setBounds`/`setSize` and setting the `animate` parameter to `true` will also emit this event once resizing has finished.
#### Event: 'will-move' _macOS_ _Windows_
Returns:
@@ -540,12 +559,12 @@ Note that this is only emitted when the window is being resized manually. Resizi
Emitted when the window is being moved to a new position.
__Note__: On macOS this event is an alias of `moved`.
#### Event: 'moved' _macOS_
#### Event: 'moved' _macOS_ _Windows_
Emitted once when the window is moved to a new position.
__Note__: On macOS this event is an alias of `move`.
#### Event: 'enter-full-screen'
Emitted when the window enters a full-screen state.
@@ -588,7 +607,7 @@ e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`.
```javascript
const{BrowserWindow}=require('electron')
letwin=newBrowserWindow()
constwin=newBrowserWindow()
win.on('app-command',(e,cmd)=>{
// Navigate the window back when the user hits their mouse back button
to monitor and report crashes. On Linux, Electron uses
[breakpad](https://chromium.googlesource.com/breakpad/breakpad/+/master/). This
is an implementation detail driven by Chromium, and it may change in future. In
particular, crashpad is newer and will likely eventually replace breakpad on
all platforms.
## Methods
@@ -43,45 +46,67 @@ The `crashReporter` module has the following methods:
### `crashReporter.start(options)`
*`options` Object
*`companyName` String
*`submitURL` String - URL that crash reports will be sent to as POST.
*`productName` String (optional) - Defaults to `app.name`.
*`uploadToServer` Boolean (optional) - Whether crash reports should be sent to the server. Default is `true`.
*`ignoreSystemCrashHandler` Boolean (optional) - Default is `false`.
*`companyName` String (optional) _Deprecated_ - Deprecated alias for
`{ globalExtra: { _companyName: ... } }`.
*`uploadToServer` Boolean (optional) - Whether crash reports should be sent
to the server. If false, crash reports will be collected and stored in the
crashes directory, but not uploaded. Default is `true`.
*`ignoreSystemCrashHandler` Boolean (optional) - If true, crashes generated
in the main process will not be forwarded to the system crash handler.
Default is `false`.
*`rateLimit` Boolean (optional) _macOS__Windows_ - If true, limit the
number of crashes uploaded to 1/hour. Default is `false`.
*`compress` Boolean (optional)_macOS__Windows_ - If true, crash reports
will be compressed and uploaded with `Content-Encoding: gzip`. Not all
collection servers support compressed payloads. Default is `false`.
*`extra` Record<String, String> (optional) - An object you can define that will be sent along with the
report. Only string properties are sent correctly. Nested objects are not
supported. When using Windows, the property names and values must be fewer than 64 characters.
*`crashesDirectory` String (optional) - Directory to store the crash reports temporarily (only used when the crash reporter is started via `process.crashReporter.start`).
*`compress` Boolean (optional) - If true, crash reports will be compressed
and uploaded with `Content-Encoding: gzip`. Default is `false`.
*`extra` Record<String, String> (optional) - Extra string key/value
annotations that will be sent along with crash reports that are generated
in the main process. Only string values are supported. Crashes generated in
child processes will not contain these extra
parameters to crash reports generated from child processes, call
[`addExtraParameter`](#crashreporteraddextraparameterkey-value) from the
child process.
*`globalExtra` Record<String, String> (optional) - Extra string key/value
annotations that will be sent along with any crash reports generated in any
process. These annotations cannot be changed once the crash reporter has
been started. If a key is present in both the global extra parameters and
the process-specific extra parameters, then the global one will take
precedence. By default, `productName` and the app version are included, as
well as the Electron version.
You are required to call this method before using any other `crashReporter` APIs
and in each process (main/renderer) from which you want to collect crash reports.
You can pass different options to `crashReporter.start` when calling from different processes.
This method must be called before using any other `crashReporter` APIs. Once
initialized this way, the crashpad handler collects crashes from all
subsequently created processes. The crash reporter cannot be disabled once
started.
**Note** Child processes created via the `child_process` module will not have access to the Electron modules.
Therefore, to collect crash reports from them, use `process.crashReporter.start` instead. Pass the same options as above
along with an additional one called `crashesDirectory` that should point to a directory to store the crash
reports temporarily. You can test this out by calling `process.crash()` to crash the child process.
This method should be called as early as possible in app startup, preferably
before`app.on('ready')`. If the crash reporter is not initialized at the time
a renderer process is created, then that renderer process will not be monitored
by the crash reporter.
**Note:**If you need send additional/updated `extra` parameters after your
first call `start` you can call `addExtraParameter` on macOS or call `start`
again with the new/updated `extra` parameters on Linux and Windows.
**Note:**You can test out the crash reporter by generating a crash using
`process.crash()`.
**Note:**On macOS and windows, Electron uses a new `crashpad` client for crash collection and reporting.
If you want to enable crash reporting, initializing `crashpad` from the main process using `crashReporter.start` is required
regardless of which process you want to collect crashes from. Once initialized this way, the crashpad handler collects
crashes from all processes. You still have to call `crashReporter.start` from the renderer or child process, otherwise crashes from
them will get reported without `companyName`, `productName` or any of the `extra` information.
**Note:**If you need to send additional/updated `extra` parameters after your
first call `start` you can call `addExtraParameter`.
**Note:** Parameters passed in `extra`, `globalExtra` or set with
`addExtraParameter` have limits on the length of the keys and values. Key names
must be at most 39 bytes long, and values must be no longer than 127 bytes.
Keys with names longer than the maximum will be silently ignored. Key values
longer than the maximum length will be truncated.
**Note:** Calling this method from the renderer process is deprecated.
Returns [`CrashReport`](structures/crash-report.md) - The date and ID of the
last crash report. Only crash reports that have been uploaded will be returned;
even if a crash report is present on disk it will not be returned until it is
uploaded. In the case that there are no uploaded reports, `null` is returned.
Returns the date and ID of the last crash report. Only crash reports that have been uploaded will be returned; even if a crash report is present on disk it will not be returned until it is uploaded. In the case that there are no uploaded reports, `null` is returned.
**Note:** Calling this method from the renderer process is deprecated.
*`key`String - Parameter key, must be less than 64 characters long.
*`value` String - Parameter value, must be less than 64 characters long.
Returns `String` - The directory where crashes are temporarily stored before being uploaded.
Set an extra parameter to be sent with the crash report. The values
specified here will be sent in addition to any values set via the `extra` option when `start` was called. This API is only available on macOS and windows, if you need to add/update extra parameters on Linux after your first call to `start` you can call `start` again with the updated `extra` options.
**Note:** This method is deprecated, use `app.getPath('crashDumps')` instead.
* The `blur` filter only applies to the web page, so there is no way to apply
blur effect to the content below the window (i.e. other applications open on
the user's system).
*On Windows operating systems, transparent windows will not work when DWM is
*The window will not be transparent when DevTools is opened.
* On Windows operating systems,
* transparent windows will not work when DWM is
disabled.
* transparent windows can not be maximized using the Windows system menu or by double clicking the title bar. The reasoning behind this can be seen on [this pull request](https://github.com/electron/electron/pull/28207).
* On Linux, users have to put `--enable-transparent-visuals --disable-gpu` in
the command line to disable GPU and allow ARGB to make transparent window,
this is caused by an upstream bug that [alpha channel doesn't work on some
@@ -100,7 +103,7 @@ API:
```javascript
const{BrowserWindow}=require('electron')
letwin=newBrowserWindow()
constwin=newBrowserWindow()
win.setIgnoreMouseEvents(true)
```
@@ -112,13 +115,19 @@ optional parameter can be used to forward mouse move messages to the web page,
allowing events such as `mouseleave` to be emitted:
@@ -22,8 +22,10 @@ Sets `menu` as the application menu on macOS. On Windows and Linux, the
Also on Windows and Linux, you can use a `&` in the top-level item name to
indicate which letter should get a generated accelerator. For example, using
`&File` for the file menu would result in a generated `Alt-F` accelerator that
opens the associated menu. The indicated character in the button label gets an
underline. The `&` character is not displayed on the button label.
opens the associated menu. The indicated character in the button label then gets an
underline, and the `&` character is not displayed on the button label.
In order to escape the `&` character in an item name, add a proceeding `&`. For example, `&&File` would result in `&File` displayed on the button label.
Passing `null` will suppress the default menu. On Windows and Linux,
this has the additional effect of removing the menu bar from the window.
@@ -96,7 +98,7 @@ Appends the `menuItem` to the menu.
*`id` String
Returns `MenuItem` the item with the specified `id`
Returns `MenuItem | null` the item with the specified `id`
#### `menu.insert(pos, menuItem)`
@@ -141,13 +143,7 @@ can have a submenu.
## Examples
The `Menu` class is only available in the main process, but you can also use it
in the render process via the [`remote`](remote.md) module.
### Main process
An example of creating the application menu in the main process with the
simple template API:
An example of creating the application menu with the simple template API:
The Electron team is currently undergoing an initiative to modernize our API in a few concrete ways. These include: updating our modules to use idiomatic JS properties instead of separate `getPropertyX` and `setpropertyX`, converting callbacks to promises, and removing some other anti-patterns present in our APIs. The current status of the Promise intiative can be tracked in the [promisification](promisification.md) tracking file.
As we work to perform these updates, we seek to create the least disruptive amount of change at any given time, so as many changes as possible will be introduced in a backward compatible manner and deprecated after enough time has passed to give users a chance to upgrade their API calls.
This document and its child documents will be updated to reflect the latest status of our API changes.
The Electron team is currently undergoing an initiative to convert separate getter and setter functions in Electron to bespoke properties with `get` and `set` functionality. During this transition period, both the new properties and old getters and setters of these functions will work correctly and be documented.
*`path` String - path to a file that we intend to construct a thumbnail out of.
*`maxSize` [Size](structures/size.md) - the maximum width and height (positive numbers) the thumbnail returned can be. The Windows implementation will ignore `maxSize.height` and scale the height according to `maxSize.width`.
Returns `Promise<NativeImage>` - fulfilled with the file's thumbnail preview image, which is a [NativeImage](native-image.md).
### `nativeImage.createFromPath(path)`
*`path` String
@@ -266,9 +273,13 @@ image instead of a copy, so you _must_ ensure that the associated
Returns `Boolean` - Whether the image is empty.
#### `image.getSize()`
#### `image.getSize([scaleFactor])`
Returns [`Size`](structures/size.md)
*`scaleFactor` Double (optional) - Defaults to 1.0.
Returns [`Size`](structures/size.md).
If `scaleFactor` is passed, this will return the size corresponding to the image representation most closely matching the passed value.
#### `image.setTemplateImage(option)`
@@ -303,10 +314,18 @@ Returns `NativeImage` - The resized image.
If only the `height` or the `width` are specified then the current aspect ratio
will be preserved in the resized image.
#### `image.getAspectRatio()`
#### `image.getAspectRatio([scaleFactor])`
*`scaleFactor` Double (optional) - Defaults to 1.0.
Returns `Float` - The image's aspect ratio.
If `scaleFactor` is passed, this will return the aspect ratio corresponding to the image representation most closely matching the passed value.
#### `image.getScaleFactors()`
Returns `Float[]` - An array of all scale factors corresponding to representations for a given nativeImage.
if(error)console.error('Failed to register protocol')
})
})
```
@@ -26,9 +24,15 @@ of the `app` module gets emitted.
## Using `protocol` with a custom `partition` or `session`
A protocol is registered to a specific Electron [`session`](./session.md) object. If you don't specify a session, then your `protocol` will be applied to the default session that Electron uses. However, if you define a `partition` or `session` on your `browserWindow`'s `webPreferences`, then that window will use a different session and your custom protocol will not work if you just use `electron.protocol.XXX`.
A protocol is registered to a specific Electron [`session`](./session.md)
object. If you don't specify a session, then your `protocol` will be applied to
the default session that Electron uses. However, if you define a `partition` or
`session` on your `browserWindow`'s `webPreferences`, then that window will use
a different session and your custom protocol will not work if you just use
`electron.protocol.XXX`.
To have your custom protocol work in combination with a custom session, you need to register it to that session explicitly.
To have your custom protocol work in combination with a custom session, you need
**Note:** This method can only be used before the `ready` event of the `app`
module gets emitted and can be called only once.
Registers the `scheme` as standard, secure, bypasses content security policy for resources,
allows registering ServiceWorker and supports fetch API.
Registers the `scheme` as standard, secure, bypasses content security policy for
resources, allows registering ServiceWorker, supports fetch API, and streaming
video/audio. Specify a privilege with the value of `true` to enable the capability.
Specify a privilege with the value of `true` to enable the capability.
An example of registering a privileged scheme, with bypassing Content Security Policy:
An example of registering a privileged scheme, that bypasses Content Security
Policy:
```javascript
const{protocol}=require('electron')
@@ -84,7 +80,7 @@ A standard scheme adheres to what RFC 3986 calls [generic URI
syntax](https://tools.ietf.org/html/rfc3986#section-3). For example `http` and
`https` are standard schemes, while `file` is not.
Registering a scheme as standard, will allow relative and absolute resources to
Registering a scheme as standard allows relative and absolute resources to
be resolved correctly when served. Otherwise the scheme will behave like the
`file` protocol, but without the ability to resolve relative URLs.
@@ -102,168 +98,107 @@ Registering a scheme as standard will allow access to files through the
[FileSystem API][file-system-api]. Otherwise the renderer will throw a security
error for the scheme.
By default web storage apis (localStorage, sessionStorage, webSQL, indexedDB, cookies)
are disabled for non standard schemes. So in general if you want to register a
custom protocol to replace the `http` protocol, you have to register it as a standard scheme.
By default web storage apis (localStorage, sessionStorage, webSQL, indexedDB,
cookies) are disabled for non standard schemes. So in general if you want to
register a custom protocol to replace the `http` protocol, you have to register
it as a standard scheme.
`protocol.registerSchemesAsPrivileged` can be used to replicate the functionality of the previous `protocol.registerStandardSchemes`, `webFrame.registerURLSchemeAs*` and `protocol.registerServiceWorkerSchemes` functions that existed prior to Electron 5.0.0, for example:
Protocols that use streams (http and stream protocols) should set `stream: true`.
The `<video>` and `<audio>` HTML elements expect protocols to buffer their
responses by default. The `stream` flag configures those elements to correctly
*`versionId` Number - The version ID of the service worker that sent the log message
*`source` String - The type of source for this message. Can be `javascript`, `xml`, `network`, `console-api`, `storage`, `app-cache`, `rendering`, `security`, `deprecation`, `worker`, `violation`, `intervention`, `recommendation` or `other`.
*`level` Number - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`.
*`level` Number - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`.
*`sourceUrl` String - The URL the message came from
*`lineNumber` Number - The line number of the source that triggered this console message
*`webContents` [WebContents](web-contents.md) - WebContents requesting the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin.
*`permission` String - Enum of 'media', 'geolocation', 'notifications', 'midiSysex',
'pointerLock', 'fullscreen', 'openExternal'.
*`permission` String - The type of requested permission.
*`clipboard-read` - Request access to read from the clipboard.
*`media` - Request access to media devices such as camera, microphone and speakers.
*`mediaKeySystem` - Request access to DRM protected content.
*`geolocation` - Request access to user's current location.
*`notifications` - Request notification creation and the ability to display them in the user's system tray.
*`midi` - Request MIDI access in the `webmidi` API.
*`midiSysex` - Request the use of system exclusive messages in the `webmidi` API.
*`pointerLock` - Request to directly interpret mouse movements as an input method. Click [here](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API) to know more.
*`fullscreen` - Request for the app to enter fullscreen mode.
*`openExternal` - Request to open links in external applications.
*`callback` Function
*`permissionGranted` Boolean - Allow or deny the permission.
*`details` Object - Some properties are only available on certain permission types.
*`webContents` [WebContents](web-contents.md) - WebContents checking the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin.
*`permission` String - Enum of 'media'.
*`requestingOrigin` String - The origin URL of the permission check
*`details` Object - Some properties are only available on certain permission types.
*`securityOrigin` String - The security orign of the `media` check.
*`securityOrigin` String - The security origin of the `media` check.
*`mediaType` String - The type of media access being requested, can be `video`,
`audio` or `unknown`
*`requestingUrl` String - The last URL the requesting frame loaded
@@ -518,7 +527,7 @@ Returns `String[]` - An array of language codes the spellchecker is enabled for.
will fallback to using `en-US`. By default on launch if this setting is an empty list Electron will try to populate this
setting with the current OS locale. This setting is persisted across restarts.
**Note:** On macOS the OS spellchecker is used and has it's own list of languages. This API is a no-op on macOS.
**Note:** On macOS the OS spellchecker is used and has its own list of languages. This API is a no-op on macOS.
*`isDefault` Boolean - whether or not a given printer is set as the default printer on the OS.
*`options` Object - an object containing a variable number of platform-specific printer information.
The number represented by `status` means different things on different platforms: on Windows it's potential values can be found [here](https://docs.microsoft.com/en-us/windows/win32/printdocs/printer-info-2), and on Linux and macOS they can be found [here](https://www.cups.org/doc/cupspm.html).
The number represented by `status` means different things on different platforms: on Windows its potential values can be found [here](https://docs.microsoft.com/en-us/windows/win32/printdocs/printer-info-2), and on Linux and macOS they can be found [here](https://www.cups.org/doc/cupspm.html).
*`contentLengths` Number[] - The total size of the content, in bytes.
*`price` Number - The cost of the product in the local currency.
*`formattedPrice` String - The locale formatted price of the product.
*`currencyCode` String - 3 character code presenting a product's currency based on the ISO 4217 standard.
*`isDownloadable` Boolean - A Boolean value that indicates whether the App Store has downloadable content for this product. `true` if at least one file has been associated with the product.
@@ -406,7 +408,7 @@ systemPreferences.promptTouchID('To get consent for a Security-Gated Thing').the
})
```
This API itself will not protect your user data; rather, it is a mechanism to allow you to do so. Native apps will need to set [Access Control Constants](https://developer.apple.com/documentation/security/secaccesscontrolcreateflags?language=objc) like [`kSecAccessControlUserPresence`](https://developer.apple.com/documentation/security/secaccesscontrolcreateflags/ksecaccesscontroluserpresence?language=objc) on the their keychain entry so that reading it would auto-prompt for Touch ID biometric consent. This could be done with [`node-keytar`](https://github.com/atom/node-keytar), such that one would store an encryption key with `node-keytar` and only fetch it if `promptTouchID()` resolves.
This API itself will not protect your user data; rather, it is a mechanism to allow you to do so. Native apps will need to set [Access Control Constants](https://developer.apple.com/documentation/security/secaccesscontrolcreateflags?language=objc) like [`kSecAccessControlUserPresence`](https://developer.apple.com/documentation/security/secaccesscontrolcreateflags/ksecaccesscontroluserpresence?language=objc) on their keychain entry so that reading it would auto-prompt for Touch ID biometric consent. This could be done with [`node-keytar`](https://github.com/atom/node-keytar), such that one would store an encryption key with `node-keytar` and only fetch it if `promptTouchID()` resolves.
**NOTE:** This API will return a rejected Promise on macOS systems older than Sierra 10.12.2.
@@ -416,7 +418,7 @@ This API itself will not protect your user data; rather, it is a mechanism to al
Returns `Boolean` - `true` if the current process is a trusted accessibility client and `false` if it is not.
@@ -217,9 +217,11 @@ Sets the `image` associated with this tray icon when pressed on macOS.
Sets the hover text for this tray icon.
#### `tray.setTitle(title)` _macOS_
#### `tray.setTitle(title[, options])` _macOS_
*`title` String
*`options` Object (optional)
*`fontType` String (optional) - The font family variant to display, can be `monospaced` or `monospacedDigit`. `monospaced` is available in macOS 10.15+ and `monospacedDigit` is available in macOS 10.11+. When left blank, the title uses the default system font.
Sets the title displayed next to the tray icon in the status bar (Support ANSI colors).
@@ -883,11 +908,11 @@ Returns `String` - The URL of the current web page.
```javascript
const{BrowserWindow}=require('electron')
letwin=newBrowserWindow({width:800,height:600})
win.loadURL('http://github.com')
letcurrentURL=win.webContents.getURL()
console.log(currentURL)
constwin=newBrowserWindow({width:800,height:600})
win.loadURL('http://github.com').then(()=>{
constcurrentURL=win.webContents.getURL()
console.log(currentURL)
})
```
#### `contents.getTitle()`
@@ -974,6 +999,34 @@ Navigates to the specified offset from the "current entry".
Returns `Boolean` - Whether the renderer process has crashed.
#### `contents.forcefullyCrashRenderer()`
Forcefully terminates the renderer process that is currently hosting this
`webContents`. This will cause the `render-process-gone` event to be emitted
with the `reason=killed || reason=crashed`. Please note that some webContents share renderer
processes and therefore calling this method may also crash the host process
for other webContents as well.
Calling `reload()` immediately after calling this
method will force the reload to occur in a new process. This should be used
when this process is unstable or unusable, for instance in order to recover
from the `unresponsive` event.
```js
contents.on('unresponsive',async()=>{
const{response}=awaitdialog.showMessageBox({
message:'App X has become unresponsive',
title:'Do you want to try forcefully reloading the app?',
buttons:['OK','Cancel'],
cancelId:1
})
if(response===0){
contents.forcefullyCrashRenderer()
contents.reload()
}
})
```
#### `contents.setUserAgent(userAgent)`
*`userAgent` String
@@ -1180,8 +1233,7 @@ Inserts `text` to the focused element.
*`text` String - Content to be searched, must not be empty.
*`options` Object (optional)
*`forward` Boolean (optional) - Whether to search forward or backward, defaults to `true`.
*`findNext` Boolean (optional) - Whether the operation is first request or a followup,
defaults to `false`.
*`findNext` Boolean (optional) - Whether to begin a new text finding session with this request. Should be `true` for initial requests, and `false` for follow-up requests. Defaults to `false`.
*`matchCase` Boolean (optional) - Whether search should be case-sensitive,
defaults to `false`.
*`wordStart` Boolean (optional) - Whether to look only at the start of words.
*`success` Boolean - Indicates success of the print call.
*`failureReason` String - Error description called back if the print fails.
When a custom `pageSize` is passed, Chromium attempts to validate platform specific minimum values for `width_microns` and `height_microns`. Width and height must both be minimum 353 microns but may be higher on some operating systems.
Prints window's web page. When `silent` is set to `true`, Electron will pick
the system's default printer if `deviceName` is empty and the default settings for printing.
@@ -1295,7 +1349,14 @@ Use `page-break-before: always;` CSS style to force to print to a new page.
*`worldId` Integer - The ID of the world to run the javascript in, `0` is the default world, `999` is the world used by Electrons `contextIsolation` feature. Chrome extensions reserve the range of IDs in `[1 << 20, 1 << 29)`. You can provide any integer here.
Electron's `webview` tag is based on [Chromium's `webview`][chrome-webview], which
is undergoing dramatic architectural changes. This impacts the stability of `webviews`,
including rendering, navigation, and event routing. We currently recommend to not
use the `webview` tag and to consider alternatives, like `iframe`, Electron's `BrowserView`,
use the `webview` tag and to consider alternatives, like `iframe`, [Electron's `BrowserView`](browser-view.md),
or an architecture that avoids embedded content altogether.
## Enabling
@@ -137,7 +137,7 @@ This option is disabled by default in the guest page.
```
A `Boolean`. When this attribute is `false` the guest page in `webview` will not have access
to the [`remote`](remote.md) module. The remote module is available by default.
to the [`remote`](remote.md) module. The remote module is unavailable by default.
### `plugins`
@@ -515,8 +515,7 @@ Inserts `text` to the focused element.
*`text` String - Content to be searched, must not be empty.
*`options` Object (optional)
*`forward` Boolean (optional) - Whether to search forward or backward, defaults to `true`.
*`findNext` Boolean (optional) - Whether the operation is first request or a followup,
defaults to `false`.
*`findNext` Boolean (optional) - Whether to begin a new text finding session with this request. Should be `true` for initial requests, and `false` for follow-up requests. Defaults to `false`.
*`matchCase` Boolean (optional) - Whether search should be case-sensitive,
defaults to `false`.
*`wordStart` Boolean (optional) - Whether to look only at the start of words.
@@ -560,9 +559,9 @@ Stops any `findInPage` request for the `webview` with the provided `action`.
*`pagesPerSheet` Number (optional) - The number of pages to print per page sheet.
*`collate` Boolean (optional) - Whether the web page should be collated.
*`copies` Number (optional) - The number of copies of the web page to print.
*`pageRanges`Record<string, number> (optional) - The page range to print.
*`from` Number - the start page.
*`to` Number - the end page.
*`pageRanges`Object[] (optional) - The page range to print.
*`from` Number - Index of the first page to print (0-based).
*`to` Number - Index of the last page to print (inclusive) (0-based).
*`duplexMode` String (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`.
*`dpi` Record<string, number> (optional)
*`horizontal` Number (optional) - The horizontal dpi.
@@ -588,8 +587,8 @@ Prints `webview`'s web page. Same as `webContents.print([options])`.
and `width` in microns.
*`scaleFactor` Number (optional) - The scale factor of the web page. Can range from 0 to 100.
*`pageRanges` Record<string, number> (optional) - The page range to print.
*`from` Number - the first page to print.
*`to` Number - the last page to print (inclusive).
*`from` Number - Index of the first page to print (0-based).
*`to` Number - Index of the last page to print (inclusive) (0-based).
*`pageSize` String | Size (optional) - Specify page size of the generated PDF. Can be `A3`,
`A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height`
*`printBackground` Boolean (optional) - Whether to print CSS backgrounds.
@@ -755,9 +754,9 @@ Fired when page leaves fullscreen triggered by HTML API.
Returns:
*`level` Integer
*`message` String
*`line` Integer
*`level` Integer - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`.
*`message` String - The actual console message
*`line` Integer - The line number of the source that triggered this console message
*`sourceId` String
Fired when the guest window logs a console message.
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.