docs: track electron documentation
Rel: https://github.com/electron/electronjs.org-new/issues/64#issuecomment-931738721
This commit is contained in:
Родитель
7e163fb918
Коммит
b6fc413776
|
@ -5,4 +5,3 @@ node_modules
|
|||
.vscode/settings.json
|
||||
build/
|
||||
content/
|
||||
docs/
|
14
README.md
14
README.md
|
@ -9,6 +9,18 @@ This repository contains the code for the new electronsjs.org website. It is bui
|
|||
yarn install
|
||||
```
|
||||
|
||||
## How to modify the documentation
|
||||
|
||||
For English documentation the changes need to happen upstream in `[electron/electron]`. These
|
||||
changes are picked automatically as soon as they are done in the stable branch. The exception
|
||||
is when there is a new major release.
|
||||
|
||||
The translation work happens in [Crowdin] and the changes are picked up periodically every
|
||||
15 minutes.
|
||||
|
||||
Any documentation changes done manually in this repo will be eventually override by any of these
|
||||
updates.
|
||||
|
||||
## How to add a new blogpost
|
||||
|
||||
To add a new blogpost you need to create a new markdown file under `/blog`. The supported
|
||||
|
@ -98,3 +110,5 @@ The content of this repository is organized as follows:
|
|||
```
|
||||
|
||||
[ced]: https://npmjs.com/package/create-electron-documentation
|
||||
[Crowdin]: https://crowdin.com/project/electron
|
||||
[electron/electron]: https://github.com/electron/electron/tree/main/docs
|
||||
|
|
|
@ -0,0 +1,166 @@
|
|||
---
|
||||
title: "Official Guides"
|
||||
description: "Please make sure that you use the documents that match your Electron version. The version number should be a part of the page URL. If it's not, you are probably using the documentation of a development branch which may contain API changes that are not compatible with your Electron version. To view older versions of the documentation, you can browse by tag on GitHub by opening the \"Switch branches/tags\" dropdown and selecting the tag that matches your version."
|
||||
slug: README
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Official Guides
|
||||
|
||||
Please make sure that you use the documents that match your Electron version.
|
||||
The version number should be a part of the page URL. If it's not, you are
|
||||
probably using the documentation of a development branch which may contain API
|
||||
changes that are not compatible with your Electron version. To view older
|
||||
versions of the documentation, you can
|
||||
[browse by tag](https://github.com/electron/electron/tree/v1.4.0)
|
||||
on GitHub by opening the "Switch branches/tags" dropdown and selecting the tag
|
||||
that matches your version.
|
||||
|
||||
## FAQ
|
||||
|
||||
There are questions that are asked quite often. Check this out before creating
|
||||
an issue:
|
||||
|
||||
* [Electron FAQ](latest/faq.md)
|
||||
|
||||
## Guides and Tutorials
|
||||
|
||||
### Getting started
|
||||
|
||||
* [Introduction](latest/tutorial/introduction.md)
|
||||
* [Quick Start](latest/tutorial/quick-start.md)
|
||||
* [Process Model](latest/tutorial/process-model.md)
|
||||
|
||||
### Learning the basics
|
||||
|
||||
* Adding Features to Your App
|
||||
* [Notifications](latest/tutorial/notifications.md)
|
||||
* [Recent Documents](latest/tutorial/recent-documents.md)
|
||||
* [Application Progress](latest/tutorial/progress-bar.md)
|
||||
* [Custom Dock Menu](latest/tutorial/macos-dock.md)
|
||||
* [Custom Windows Taskbar](latest/tutorial/windows-taskbar.md)
|
||||
* [Custom Linux Desktop Actions](latest/tutorial/linux-desktop-actions.md)
|
||||
* [Keyboard Shortcuts](latest/tutorial/keyboard-shortcuts.md)
|
||||
* [Offline/Online Detection](latest/tutorial/online-offline-events.md)
|
||||
* [Represented File for macOS BrowserWindows](latest/tutorial/represented-file.md)
|
||||
* [Native File Drag & Drop](latest/tutorial/native-file-drag-drop.md)
|
||||
* [Offscreen Rendering](latest/tutorial/offscreen-rendering.md)
|
||||
* [Dark Mode](latest/tutorial/dark-mode.md)
|
||||
* [Web embeds in Electron](latest/tutorial/web-embeds.md)
|
||||
* [Boilerplates and CLIs](latest/tutorial/boilerplates-and-clis.md)
|
||||
* [Boilerplate vs CLI](latest/tutorial/boilerplates-and-clis.md#boilerplate-vs-cli)
|
||||
* [electron-forge](latest/tutorial/boilerplates-and-clis.md#electron-forge)
|
||||
* [electron-builder](latest/tutorial/boilerplates-and-clis.md#electron-builder)
|
||||
* [electron-react-boilerplate](latest/tutorial/boilerplates-and-clis.md#electron-react-boilerplate)
|
||||
* [Other Tools and Boilerplates](latest/tutorial/boilerplates-and-clis.md#other-tools-and-boilerplates)
|
||||
|
||||
### Advanced steps
|
||||
|
||||
* Application Architecture
|
||||
* [Using Native Node.js Modules](latest/tutorial/using-native-node-modules.md)
|
||||
* [Performance Strategies](latest/tutorial/performance.md)
|
||||
* [Security Strategies](latest/tutorial/security.md)
|
||||
* [Process Sandboxing](latest/tutorial/sandbox.md)
|
||||
* [Accessibility](latest/tutorial/accessibility.md)
|
||||
* [Manually Enabling Accessibility Features](latest/tutorial/accessibility.md#manually-enabling-accessibility-features)
|
||||
* [Testing and Debugging](latest/tutorial/application-debugging.md)
|
||||
* [Debugging the Main Process](latest/tutorial/debugging-main-process.md)
|
||||
* [Debugging with Visual Studio Code](latest/tutorial/debugging-vscode.md)
|
||||
* [Using Selenium and WebDriver](latest/tutorial/using-selenium-and-webdriver.md)
|
||||
* [Testing on Headless CI Systems (Travis, Jenkins)](latest/tutorial/testing-on-headless-ci.md)
|
||||
* [DevTools Extension](latest/tutorial/devtools-extension.md)
|
||||
* [Automated Testing with a Custom Driver](latest/tutorial/automated-testing-with-a-custom-driver.md)
|
||||
* [REPL](latest/tutorial/repl.md)
|
||||
* [Distribution](latest/tutorial/application-distribution.md)
|
||||
* [Supported Platforms](latest/tutorial/support.md#supported-platforms)
|
||||
* [Code Signing](latest/tutorial/code-signing.md)
|
||||
* [Mac App Store](latest/tutorial/mac-app-store-submission-guide.md)
|
||||
* [Windows Store](latest/tutorial/windows-store-guide.md)
|
||||
* [Snapcraft](latest/tutorial/snapcraft.md)
|
||||
* [Updates](latest/tutorial/updates.md)
|
||||
* [Deploying an Update Server](latest/tutorial/updates.md#deploying-an-update-server)
|
||||
* [Implementing Updates in Your App](latest/tutorial/updates.md#implementing-updates-in-your-app)
|
||||
* [Applying Updates](latest/tutorial/updates.md#applying-updates)
|
||||
* [Getting Support](latest/tutorial/support.md)
|
||||
|
||||
## Detailed Tutorials
|
||||
|
||||
These individual tutorials expand on topics discussed in the guide above.
|
||||
|
||||
* [Installing Electron](latest/tutorial/installation.md)
|
||||
* [Proxies](latest/tutorial/installation.md#proxies)
|
||||
* [Custom Mirrors and Caches](latest/tutorial/installation.md#custom-mirrors-and-caches)
|
||||
* [Troubleshooting](latest/tutorial/installation.md#troubleshooting)
|
||||
* Electron Releases & Developer Feedback
|
||||
* [Versioning Policy](latest/tutorial/electron-versioning.md)
|
||||
* [Release Timelines](latest/tutorial/electron-timelines.md)
|
||||
* [Testing Widevine CDM](latest/tutorial/testing-widevine-cdm.md)
|
||||
|
||||
---
|
||||
|
||||
* [Glossary of Terms](latest/glossary.md)
|
||||
|
||||
## API References
|
||||
|
||||
* [Synopsis](latest/api/synopsis.md)
|
||||
* [Process Object](latest/api/process.md)
|
||||
* [Supported Command Line Switches](latest/api/command-line-switches.md)
|
||||
* [Environment Variables](latest/api/environment-variables.md)
|
||||
* [Chrome Extensions Support](latest/api/extensions.md)
|
||||
* [Breaking API Changes](latest/breaking-changes.md)
|
||||
|
||||
### Custom DOM Elements:
|
||||
|
||||
* [`File` Object](latest/api/file-object.md)
|
||||
* [`<webview>` Tag](latest/api/webview-tag.md)
|
||||
* [`window.open` Function](latest/api/window-open.md)
|
||||
* [`BrowserWindowProxy` Object](latest/api/browser-window-proxy.md)
|
||||
|
||||
### Modules for the Main Process:
|
||||
|
||||
* [app](latest/api/app.md)
|
||||
* [autoUpdater](latest/api/auto-updater.md)
|
||||
* [BrowserView](latest/api/browser-view.md)
|
||||
* [BrowserWindow](latest/api/browser-window.md)
|
||||
* [contentTracing](latest/api/content-tracing.md)
|
||||
* [dialog](latest/api/dialog.md)
|
||||
* [globalShortcut](latest/api/global-shortcut.md)
|
||||
* [inAppPurchase](latest/api/in-app-purchase.md)
|
||||
* [ipcMain](latest/api/ipc-main.md)
|
||||
* [Menu](latest/api/menu.md)
|
||||
* [MenuItem](latest/api/menu-item.md)
|
||||
* [MessageChannelMain](latest/api/message-channel-main.md)
|
||||
* [MessagePortMain](latest/api/message-port-main.md)
|
||||
* [net](latest/api/net.md)
|
||||
* [netLog](latest/api/net-log.md)
|
||||
* [nativeTheme](latest/api/native-theme.md)
|
||||
* [Notification](latest/api/notification.md)
|
||||
* [powerMonitor](latest/api/power-monitor.md)
|
||||
* [powerSaveBlocker](latest/api/power-save-blocker.md)
|
||||
* [protocol](latest/api/protocol.md)
|
||||
* [screen](latest/api/screen.md)
|
||||
* [session](latest/api/session.md)
|
||||
* [ShareMenu](latest/api/share-menu.md)
|
||||
* [systemPreferences](latest/api/system-preferences.md)
|
||||
* [TouchBar](latest/api/touch-bar.md)
|
||||
* [Tray](latest/tutorial/tray.md)
|
||||
* [webContents](latest/api/web-contents.md)
|
||||
* [webFrameMain](latest/api/web-frame-main.md)
|
||||
|
||||
### Modules for the Renderer Process (Web Page):
|
||||
|
||||
* [contextBridge](latest/api/context-bridge.md)
|
||||
* [ipcRenderer](latest/api/ipc-renderer.md)
|
||||
* [webFrame](latest/api/web-frame.md)
|
||||
|
||||
### Modules for Both Processes:
|
||||
|
||||
* [clipboard](latest/api/clipboard.md)
|
||||
* [crashReporter](latest/api/crash-reporter.md)
|
||||
* [desktopCapturer](latest/api/desktop-capturer.md)
|
||||
* [nativeImage](latest/api/native-image.md)
|
||||
* [shell](latest/api/shell.md)
|
||||
|
||||
## Development
|
||||
|
||||
See [development/README.md](latest/development/README.md)
|
|
@ -0,0 +1,89 @@
|
|||
---
|
||||
title: "Accelerator"
|
||||
description: "Define keyboard shortcuts."
|
||||
slug: accelerator
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Accelerator
|
||||
|
||||
> Define keyboard shortcuts.
|
||||
|
||||
Accelerators are Strings that can contain multiple modifiers and a single key code,
|
||||
combined by the `+` character, and are used to define keyboard shortcuts
|
||||
throughout your application.
|
||||
|
||||
Examples:
|
||||
|
||||
* `CommandOrControl+A`
|
||||
* `CommandOrControl+Shift+Z`
|
||||
|
||||
Shortcuts are registered with the [`globalShortcut`](latest/api/global-shortcut.md) module
|
||||
using the [`register`](latest/api/global-shortcut.md#globalshortcutregisteraccelerator-callback)
|
||||
method, i.e.
|
||||
|
||||
```javascript
|
||||
const { app, globalShortcut } = require('electron')
|
||||
|
||||
app.whenReady().then(() => {
|
||||
// Register a 'CommandOrControl+Y' shortcut listener.
|
||||
globalShortcut.register('CommandOrControl+Y', () => {
|
||||
// Do stuff when Y and either Command/Control is pressed.
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## Platform notice
|
||||
|
||||
On Linux and Windows, the `Command` key does not have any effect so
|
||||
use `CommandOrControl` which represents `Command` on macOS and `Control` on
|
||||
Linux and Windows to define some accelerators.
|
||||
|
||||
Use `Alt` instead of `Option`. The `Option` key only exists on macOS, whereas
|
||||
the `Alt` key is available on all platforms.
|
||||
|
||||
The `Super` (or `Meta`) key is mapped to the `Windows` key on Windows and Linux and
|
||||
`Cmd` on macOS.
|
||||
|
||||
## Available modifiers
|
||||
|
||||
* `Command` (or `Cmd` for short)
|
||||
* `Control` (or `Ctrl` for short)
|
||||
* `CommandOrControl` (or `CmdOrCtrl` for short)
|
||||
* `Alt`
|
||||
* `Option`
|
||||
* `AltGr`
|
||||
* `Shift`
|
||||
* `Super`
|
||||
* `Meta`
|
||||
|
||||
## Available key codes
|
||||
|
||||
* `0` to `9`
|
||||
* `A` to `Z`
|
||||
* `F1` to `F24`
|
||||
* Punctuation like `~`, `!`, `@`, `#`, `$`, etc.
|
||||
* `Plus`
|
||||
* `Space`
|
||||
* `Tab`
|
||||
* `Capslock`
|
||||
* `Numlock`
|
||||
* `Scrolllock`
|
||||
* `Backspace`
|
||||
* `Delete`
|
||||
* `Insert`
|
||||
* `Return` (or `Enter` as alias)
|
||||
* `Up`, `Down`, `Left` and `Right`
|
||||
* `Home` and `End`
|
||||
* `PageUp` and `PageDown`
|
||||
* `Escape` (or `Esc` for short)
|
||||
* `VolumeUp`, `VolumeDown` and `VolumeMute`
|
||||
* `MediaNextTrack`, `MediaPreviousTrack`, `MediaStop` and `MediaPlayPause`
|
||||
* `PrintScreen`
|
||||
* NumPad Keys
|
||||
* `num0` - `num9`
|
||||
* `numdec` - decimal key
|
||||
* `numadd` - numpad `+` key
|
||||
* `numsub` - numpad `-` key
|
||||
* `nummult` - numpad `*` key
|
||||
* `numdiv` - numpad `÷` key
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1,151 @@
|
|||
---
|
||||
title: "autoUpdater"
|
||||
description: "Enable apps to automatically update themselves."
|
||||
slug: auto-updater
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# autoUpdater
|
||||
|
||||
> Enable apps to automatically update themselves.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
**See also: [A detailed guide about how to implement updates in your application](latest/tutorial/updates.md).**
|
||||
|
||||
`autoUpdater` is an [EventEmitter][event-emitter].
|
||||
|
||||
## Platform Notices
|
||||
|
||||
Currently, only macOS and Windows are supported. There is no built-in support
|
||||
for auto-updater on Linux, so it is recommended to use the
|
||||
distribution's package manager to update your app.
|
||||
|
||||
In addition, there are some subtle differences on each platform:
|
||||
|
||||
### macOS
|
||||
|
||||
On macOS, the `autoUpdater` module is built upon [Squirrel.Mac][squirrel-mac],
|
||||
meaning you don't need any special setup to make it work. For server-side
|
||||
requirements, you can read [Server Support][server-support]. Note that [App
|
||||
Transport Security](https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW35) (ATS) applies to all requests made as part of the
|
||||
update process. Apps that need to disable ATS can add the
|
||||
`NSAllowsArbitraryLoads` key to their app's plist.
|
||||
|
||||
**Note:** Your application must be signed for automatic updates on macOS.
|
||||
This is a requirement of `Squirrel.Mac`.
|
||||
|
||||
### Windows
|
||||
|
||||
On Windows, you have to install your app into a user's machine before you can
|
||||
use the `autoUpdater`, so it is recommended that you use the
|
||||
[electron-winstaller][installer-lib], [electron-forge][electron-forge-lib] or the [grunt-electron-installer][installer] package to generate a Windows installer.
|
||||
|
||||
When using [electron-winstaller][installer-lib] or [electron-forge][electron-forge-lib] make sure you do not try to update your app [the first time it runs](https://github.com/electron/windows-installer#handling-squirrel-events) (Also see [this issue for more info](https://github.com/electron/electron/issues/7155)). It's also recommended to use [electron-squirrel-startup](https://github.com/mongodb-js/electron-squirrel-startup) to get desktop shortcuts for your app.
|
||||
|
||||
The installer generated with Squirrel will create a shortcut icon with an
|
||||
[Application User Model ID][app-user-model-id] in the format of
|
||||
`com.squirrel.PACKAGE_ID.YOUR_EXE_WITHOUT_DOT_EXE`, examples are
|
||||
`com.squirrel.slack.Slack` and `com.squirrel.code.Code`. You have to use the
|
||||
same ID for your app with `app.setAppUserModelId` API, otherwise Windows will
|
||||
not be able to pin your app properly in task bar.
|
||||
|
||||
Like Squirrel.Mac, Windows can host updates on S3 or any other static file host.
|
||||
You can read the documents of [Squirrel.Windows][squirrel-windows] to get more details
|
||||
about how Squirrel.Windows works.
|
||||
|
||||
## Events
|
||||
|
||||
The `autoUpdater` object emits the following events:
|
||||
|
||||
### Event: 'error'
|
||||
|
||||
Returns:
|
||||
|
||||
* `error` Error
|
||||
|
||||
Emitted when there is an error while updating.
|
||||
|
||||
### Event: 'checking-for-update'
|
||||
|
||||
Emitted when checking if an update has started.
|
||||
|
||||
### Event: 'update-available'
|
||||
|
||||
Emitted when there is an available update. The update is downloaded
|
||||
automatically.
|
||||
|
||||
### Event: 'update-not-available'
|
||||
|
||||
Emitted when there is no available update.
|
||||
|
||||
### Event: 'update-downloaded'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `releaseNotes` String
|
||||
* `releaseName` String
|
||||
* `releaseDate` Date
|
||||
* `updateURL` String
|
||||
|
||||
Emitted when an update has been downloaded.
|
||||
|
||||
On Windows only `releaseName` is available.
|
||||
|
||||
**Note:** It is not strictly necessary to handle this event. A successfully
|
||||
downloaded update will still be applied the next time the application starts.
|
||||
|
||||
### Event: 'before-quit-for-update'
|
||||
|
||||
This event is emitted after a user calls `quitAndInstall()`.
|
||||
|
||||
When this API is called, the `before-quit` event is not emitted before all windows are closed. As a result you should listen to this event if you wish to perform actions before the windows are closed while a process is quitting, as well as listening to `before-quit`.
|
||||
|
||||
## Methods
|
||||
|
||||
The `autoUpdater` object has the following methods:
|
||||
|
||||
### `autoUpdater.setFeedURL(options)`
|
||||
|
||||
* `options` Object
|
||||
* `url` String
|
||||
* `headers` Record<String, String> (optional) _macOS_ - HTTP request headers.
|
||||
* `serverType` String (optional) _macOS_ - Can be `json` or `default`, see the [Squirrel.Mac][squirrel-mac]
|
||||
README for more information.
|
||||
|
||||
Sets the `url` and initialize the auto updater.
|
||||
|
||||
### `autoUpdater.getFeedURL()`
|
||||
|
||||
Returns `String` - The current update feed URL.
|
||||
|
||||
### `autoUpdater.checkForUpdates()`
|
||||
|
||||
Asks the server whether there is an update. You must call `setFeedURL` before
|
||||
using this API.
|
||||
|
||||
**Note:** If an update is available it will be downloaded automatically.
|
||||
Calling `autoUpdater.checkForUpdates()` twice will download the update two times.
|
||||
|
||||
### `autoUpdater.quitAndInstall()`
|
||||
|
||||
Restarts the app and installs the update after it has been downloaded. It
|
||||
should only be called after `update-downloaded` has been emitted.
|
||||
|
||||
Under the hood calling `autoUpdater.quitAndInstall()` will close all application
|
||||
windows first, and automatically call `app.quit()` after all windows have been
|
||||
closed.
|
||||
|
||||
**Note:** It is not strictly necessary to call this function to apply an update,
|
||||
as a successfully downloaded update will always be applied the next time the
|
||||
application starts.
|
||||
|
||||
[squirrel-mac]: https://github.com/Squirrel/Squirrel.Mac
|
||||
[server-support]: https://github.com/Squirrel/Squirrel.Mac#server-support
|
||||
[squirrel-windows]: https://github.com/Squirrel/Squirrel.Windows
|
||||
[installer]: https://github.com/electron/grunt-electron-installer
|
||||
[installer-lib]: https://github.com/electron/windows-installer
|
||||
[electron-forge-lib]: https://github.com/electron-userland/electron-forge
|
||||
[app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx
|
||||
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
|
|
@ -0,0 +1,79 @@
|
|||
---
|
||||
title: "BrowserView"
|
||||
description: "A BrowserView can be used to embed additional web content into a BrowserWindow. It is like a child window, except that it is positioned relative to its owning window. It is meant to be an alternative to the webview tag."
|
||||
slug: browser-view
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# BrowserView
|
||||
|
||||
A `BrowserView` can be used to embed additional web content into a
|
||||
[`BrowserWindow`](latest/api/browser-window.md). It is like a child window, except that it is positioned
|
||||
relative to its owning window. It is meant to be an alternative to the
|
||||
`webview` tag.
|
||||
|
||||
## Class: BrowserView
|
||||
|
||||
> Create and control views.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
### Example
|
||||
|
||||
```javascript
|
||||
// In the main process.
|
||||
const { BrowserView, BrowserWindow } = require('electron')
|
||||
|
||||
const win = new BrowserWindow({ width: 800, height: 600 })
|
||||
|
||||
const view = new BrowserView()
|
||||
win.setBrowserView(view)
|
||||
view.setBounds({ x: 0, y: 0, width: 300, height: 300 })
|
||||
view.webContents.loadURL('https://electronjs.org')
|
||||
```
|
||||
|
||||
### `new BrowserView([options])` _Experimental_
|
||||
|
||||
* `options` Object (optional)
|
||||
* `webPreferences` Object (optional) - See [BrowserWindow](latest/api/browser-window.md).
|
||||
|
||||
### Instance Properties
|
||||
|
||||
Objects created with `new BrowserView` have the following properties:
|
||||
|
||||
#### `view.webContents` _Experimental_
|
||||
|
||||
A [`WebContents`](latest/api/web-contents.md) object owned by this view.
|
||||
|
||||
### Instance Methods
|
||||
|
||||
Objects created with `new BrowserView` have the following instance methods:
|
||||
|
||||
#### `view.setAutoResize(options)` _Experimental_
|
||||
|
||||
* `options` Object
|
||||
* `width` Boolean (optional) - If `true`, the view's width will grow and shrink together
|
||||
with the window. `false` by default.
|
||||
* `height` Boolean (optional) - If `true`, the view's height will grow and shrink
|
||||
together with the window. `false` by default.
|
||||
* `horizontal` Boolean (optional) - If `true`, the view's x position and width will grow
|
||||
and shrink proportionally with the window. `false` by default.
|
||||
* `vertical` Boolean (optional) - If `true`, the view's y position and height will grow
|
||||
and shrink proportionally with the window. `false` by default.
|
||||
|
||||
#### `view.setBounds(bounds)` _Experimental_
|
||||
|
||||
* `bounds` [Rectangle](latest/api/structures/rectangle.md)
|
||||
|
||||
Resizes and moves the view to the supplied bounds relative to the window.
|
||||
|
||||
#### `view.getBounds()` _Experimental_
|
||||
|
||||
Returns [`Rectangle`](latest/api/structures/rectangle.md)
|
||||
|
||||
The `bounds` of this BrowserView instance as `Object`.
|
||||
|
||||
#### `view.setBackgroundColor(color)` _Experimental_
|
||||
|
||||
* `color` String - Color in `#aarrggbb` or `#argb` form. The alpha channel is
|
||||
optional.
|
|
@ -0,0 +1,61 @@
|
|||
---
|
||||
title: "Class: BrowserWindowProxy"
|
||||
description: "Manipulate the child browser window"
|
||||
slug: browser-window-proxy
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
## Class: BrowserWindowProxy
|
||||
|
||||
> Manipulate the child browser window
|
||||
|
||||
Process: [Renderer](latest/glossary.md#renderer-process)<br />
|
||||
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._
|
||||
|
||||
The `BrowserWindowProxy` object is returned from `window.open` and provides
|
||||
limited functionality with the child window.
|
||||
|
||||
### Instance Methods
|
||||
|
||||
The `BrowserWindowProxy` object has the following instance methods:
|
||||
|
||||
#### `win.blur()`
|
||||
|
||||
Removes focus from the child window.
|
||||
|
||||
#### `win.close()`
|
||||
|
||||
Forcefully closes the child window without calling its unload event.
|
||||
|
||||
#### `win.eval(code)`
|
||||
|
||||
* `code` String
|
||||
|
||||
Evaluates the code in the child window.
|
||||
|
||||
#### `win.focus()`
|
||||
|
||||
Focuses the child window (brings the window to front).
|
||||
|
||||
#### `win.print()`
|
||||
|
||||
Invokes the print dialog on the child window.
|
||||
|
||||
#### `win.postMessage(message, targetOrigin)`
|
||||
|
||||
* `message` any
|
||||
* `targetOrigin` String
|
||||
|
||||
Sends a message to the child window with the specified origin or `*` for no
|
||||
origin preference.
|
||||
|
||||
In addition to these methods, the child window implements `window.opener` object
|
||||
with no properties and a single method.
|
||||
|
||||
### Instance Properties
|
||||
|
||||
The `BrowserWindowProxy` object has the following instance properties:
|
||||
|
||||
#### `win.closed`
|
||||
|
||||
A `Boolean` that is set to true after the child window gets closed.
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1,273 @@
|
|||
---
|
||||
title: "Class: ClientRequest"
|
||||
description: "Make HTTP/HTTPS requests."
|
||||
slug: client-request
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
## Class: ClientRequest
|
||||
|
||||
> Make HTTP/HTTPS requests.
|
||||
|
||||
Process: [Main](latest/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._
|
||||
|
||||
`ClientRequest` implements the [Writable Stream](https://nodejs.org/api/stream.html#stream_writable_streams)
|
||||
interface and is therefore an [EventEmitter][event-emitter].
|
||||
|
||||
### `new ClientRequest(options)`
|
||||
|
||||
* `options` (Object | String) - If `options` is a String, it is interpreted as
|
||||
the request URL. If it is an object, it is expected to fully specify an HTTP request via the
|
||||
following properties:
|
||||
* `method` String (optional) - The HTTP request method. Defaults to the GET
|
||||
method.
|
||||
* `url` String (optional) - The request URL. Must be provided in the absolute
|
||||
form with the protocol scheme specified as http or https.
|
||||
* `session` Session (optional) - The [`Session`](latest/api/session.md) instance with
|
||||
which the request is associated.
|
||||
* `partition` String (optional) - The name of the [`partition`](latest/api/session.md)
|
||||
with which the request is associated. Defaults to the empty string. The
|
||||
`session` option supersedes `partition`. Thus if a `session` is explicitly
|
||||
specified, `partition` is ignored.
|
||||
* `credentials` String (optional) - Can be `include` or `omit`. Whether to
|
||||
send [credentials](https://fetch.spec.whatwg.org/#credentials) with this
|
||||
request. If set to `include`, credentials from the session associated with
|
||||
the request will be used. If set to `omit`, credentials will not be sent
|
||||
with the request (and the `'login'` event will not be triggered in the
|
||||
event of a 401). This matches the behavior of the
|
||||
[fetch](https://fetch.spec.whatwg.org/#concept-request-credentials-mode)
|
||||
option of the same name. If this option is not specified, authentication
|
||||
data from the session will be sent, and cookies will not be sent (unless
|
||||
`useSessionCookies` is set).
|
||||
* `useSessionCookies` Boolean (optional) - Whether to send cookies with this
|
||||
request from the provided session. If `credentials` is specified, this
|
||||
option has no effect. Default is `false`.
|
||||
* `protocol` String (optional) - Can be `http:` or `https:`. The protocol
|
||||
scheme in the form 'scheme:'. Defaults to 'http:'.
|
||||
* `host` String (optional) - The server host provided as a concatenation of
|
||||
the hostname and the port number 'hostname:port'.
|
||||
* `hostname` String (optional) - The server host name.
|
||||
* `port` Integer (optional) - The server's listening port number.
|
||||
* `path` String (optional) - The path part of the request URL.
|
||||
* `redirect` String (optional) - Can be `follow`, `error` or `manual`. The
|
||||
redirect mode for this request. When mode is `error`, any redirection will
|
||||
be aborted. When mode is `manual` the redirection will be cancelled unless
|
||||
[`request.followRedirect`](#requestfollowredirect) is invoked synchronously
|
||||
during the [`redirect`](#event-redirect) event. Defaults to `follow`.
|
||||
* `origin` String (optional) - The origin URL of the request.
|
||||
|
||||
`options` properties such as `protocol`, `host`, `hostname`, `port` and `path`
|
||||
strictly follow the Node.js model as described in the
|
||||
[URL](https://nodejs.org/api/url.html) module.
|
||||
|
||||
For instance, we could have created the same request to 'github.com' as follows:
|
||||
|
||||
```JavaScript
|
||||
const request = net.request({
|
||||
method: 'GET',
|
||||
protocol: 'https:',
|
||||
hostname: 'github.com',
|
||||
port: 443,
|
||||
path: '/'
|
||||
})
|
||||
```
|
||||
|
||||
### Instance Events
|
||||
|
||||
#### Event: 'response'
|
||||
|
||||
Returns:
|
||||
|
||||
* `response` [IncomingMessage](latest/api/incoming-message.md) - An object representing the HTTP response message.
|
||||
|
||||
#### Event: 'login'
|
||||
|
||||
Returns:
|
||||
|
||||
* `authInfo` Object
|
||||
* `isProxy` Boolean
|
||||
* `scheme` String
|
||||
* `host` String
|
||||
* `port` Integer
|
||||
* `realm` String
|
||||
* `callback` Function
|
||||
* `username` String (optional)
|
||||
* `password` String (optional)
|
||||
|
||||
Emitted when an authenticating proxy is asking for user credentials.
|
||||
|
||||
The `callback` function is expected to be called back with user credentials:
|
||||
|
||||
* `username` String
|
||||
* `password` String
|
||||
|
||||
```JavaScript
|
||||
request.on('login', (authInfo, callback) => {
|
||||
callback('username', 'password')
|
||||
})
|
||||
```
|
||||
|
||||
Providing empty credentials will cancel the request and report an authentication
|
||||
error on the response object:
|
||||
|
||||
```JavaScript
|
||||
request.on('response', (response) => {
|
||||
console.log(`STATUS: ${response.statusCode}`);
|
||||
response.on('error', (error) => {
|
||||
console.log(`ERROR: ${JSON.stringify(error)}`)
|
||||
})
|
||||
})
|
||||
request.on('login', (authInfo, callback) => {
|
||||
callback()
|
||||
})
|
||||
```
|
||||
|
||||
#### Event: 'finish'
|
||||
|
||||
Emitted just after the last chunk of the `request`'s data has been written into
|
||||
the `request` object.
|
||||
|
||||
#### Event: 'abort'
|
||||
|
||||
Emitted when the `request` is aborted. The `abort` event will not be fired if
|
||||
the `request` is already closed.
|
||||
|
||||
#### Event: 'error'
|
||||
|
||||
Returns:
|
||||
|
||||
* `error` Error - an error object providing some information about the failure.
|
||||
|
||||
Emitted when the `net` module fails to issue a network request. Typically when
|
||||
the `request` object emits an `error` event, a `close` event will subsequently
|
||||
follow and no response object will be provided.
|
||||
|
||||
#### Event: 'close'
|
||||
|
||||
Emitted as the last event in the HTTP request-response transaction. The `close`
|
||||
event indicates that no more events will be emitted on either the `request` or
|
||||
`response` objects.
|
||||
|
||||
#### Event: 'redirect'
|
||||
|
||||
Returns:
|
||||
|
||||
* `statusCode` Integer
|
||||
* `method` String
|
||||
* `redirectUrl` String
|
||||
* `responseHeaders` Record<String, String[]>
|
||||
|
||||
Emitted when the server returns a redirect response (e.g. 301 Moved
|
||||
Permanently). Calling [`request.followRedirect`](#requestfollowredirect) will
|
||||
continue with the redirection. If this event is handled,
|
||||
[`request.followRedirect`](#requestfollowredirect) must be called
|
||||
**synchronously**, otherwise the request will be cancelled.
|
||||
|
||||
### Instance Properties
|
||||
|
||||
#### `request.chunkedEncoding`
|
||||
|
||||
A `Boolean` specifying whether the request will use HTTP chunked transfer encoding
|
||||
or not. Defaults to false. The property is readable and writable, however it can
|
||||
be set only before the first write operation as the HTTP headers are not yet put
|
||||
on the wire. Trying to set the `chunkedEncoding` property after the first write
|
||||
will throw an error.
|
||||
|
||||
Using chunked encoding is strongly recommended if you need to send a large
|
||||
request body as data will be streamed in small chunks instead of being
|
||||
internally buffered inside Electron process memory.
|
||||
|
||||
### Instance Methods
|
||||
|
||||
#### `request.setHeader(name, value)`
|
||||
|
||||
* `name` String - An extra HTTP header name.
|
||||
* `value` String - An extra HTTP header value.
|
||||
|
||||
Adds an extra HTTP header. The header name will be issued as-is without
|
||||
lowercasing. It can be called only before first write. Calling this method after
|
||||
the first write will throw an error. If the passed value is not a `String`, its
|
||||
`toString()` method will be called to obtain the final value.
|
||||
|
||||
Certain headers are restricted from being set by apps. These headers are
|
||||
listed below. More information on restricted headers can be found in
|
||||
[Chromium's header utils](https://source.chromium.org/chromium/chromium/src/+/master:services/network/public/cpp/header_util.cc;drc=1562cab3f1eda927938f8f4a5a91991fefde66d3;bpv=1;bpt=1;l=22).
|
||||
|
||||
* `Content-Length`
|
||||
* `Host`
|
||||
* `Trailer` or `Te`
|
||||
* `Upgrade`
|
||||
* `Cookie2`
|
||||
* `Keep-Alive`
|
||||
* `Transfer-Encoding`
|
||||
|
||||
Additionally, setting the `Connection` header to the value `upgrade` is also disallowed.
|
||||
|
||||
#### `request.getHeader(name)`
|
||||
|
||||
* `name` String - Specify an extra header name.
|
||||
|
||||
Returns `String` - The value of a previously set extra header name.
|
||||
|
||||
#### `request.removeHeader(name)`
|
||||
|
||||
* `name` String - Specify an extra header name.
|
||||
|
||||
Removes a previously set extra header name. This method can be called only
|
||||
before first write. Trying to call it after the first write will throw an error.
|
||||
|
||||
#### `request.write(chunk[, encoding][, callback])`
|
||||
|
||||
* `chunk` (String | Buffer) - A chunk of the request body's data. If it is a
|
||||
string, it is converted into a Buffer using the specified encoding.
|
||||
* `encoding` String (optional) - Used to convert string chunks into Buffer
|
||||
objects. Defaults to 'utf-8'.
|
||||
* `callback` Function (optional) - Called after the write operation ends.
|
||||
|
||||
`callback` is essentially a dummy function introduced in the purpose of keeping
|
||||
similarity with the Node.js API. It is called asynchronously in the next tick
|
||||
after `chunk` content have been delivered to the Chromium networking layer.
|
||||
Contrary to the Node.js implementation, it is not guaranteed that `chunk`
|
||||
content have been flushed on the wire before `callback` is called.
|
||||
|
||||
Adds a chunk of data to the request body. The first write operation may cause
|
||||
the request headers to be issued on the wire. After the first write operation,
|
||||
it is not allowed to add or remove a custom header.
|
||||
|
||||
#### `request.end([chunk][, encoding][, callback])`
|
||||
|
||||
* `chunk` (String | Buffer) (optional)
|
||||
* `encoding` String (optional)
|
||||
* `callback` Function (optional)
|
||||
|
||||
Sends the last chunk of the request data. Subsequent write or end operations
|
||||
will not be allowed. The `finish` event is emitted just after the end operation.
|
||||
|
||||
#### `request.abort()`
|
||||
|
||||
Cancels an ongoing HTTP transaction. If the request has already emitted the
|
||||
`close` event, the abort operation will have no effect. Otherwise an ongoing
|
||||
event will emit `abort` and `close` events. Additionally, if there is an ongoing
|
||||
response object,it will emit the `aborted` event.
|
||||
|
||||
#### `request.followRedirect()`
|
||||
|
||||
Continues any pending redirection. Can only be called during a `'redirect'`
|
||||
event.
|
||||
|
||||
#### `request.getUploadProgress()`
|
||||
|
||||
Returns `Object`:
|
||||
|
||||
* `active` Boolean - Whether the request is currently active. If this is false
|
||||
no other properties will be set
|
||||
* `started` Boolean - Whether the upload has started. If this is false both
|
||||
`current` and `total` will be set to 0.
|
||||
* `current` Integer - The number of bytes that have been uploaded so far
|
||||
* `total` Integer - The number of bytes that will be uploaded this request
|
||||
|
||||
You can use this method in conjunction with `POST` requests to get the progress
|
||||
of a file upload or other data transfer.
|
||||
|
||||
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
|
|
@ -0,0 +1,288 @@
|
|||
---
|
||||
title: "clipboard"
|
||||
description: "Perform copy and paste operations on the system clipboard."
|
||||
slug: clipboard
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# clipboard
|
||||
|
||||
> Perform copy and paste operations on the system clipboard.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process), [Renderer](latest/glossary.md#renderer-process)
|
||||
|
||||
On Linux, there is also a `selection` clipboard. To manipulate it
|
||||
you need to pass `selection` to each method:
|
||||
|
||||
```javascript
|
||||
const { clipboard } = require('electron')
|
||||
|
||||
clipboard.writeText('Example String', 'selection')
|
||||
console.log(clipboard.readText('selection'))
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
The `clipboard` module has the following methods:
|
||||
|
||||
**Note:** Experimental APIs are marked as such and could be removed in future.
|
||||
|
||||
### `clipboard.readText([type])`
|
||||
|
||||
* `type` String (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux.
|
||||
|
||||
Returns `String` - The content in the clipboard as plain text.
|
||||
|
||||
```js
|
||||
const { clipboard } = require('electron')
|
||||
|
||||
clipboard.writeText('hello i am a bit of text!')
|
||||
|
||||
const text = clipboard.readText()
|
||||
console.log(text)
|
||||
// hello i am a bit of text!'
|
||||
```
|
||||
|
||||
### `clipboard.writeText(text[, type])`
|
||||
|
||||
* `text` String
|
||||
* `type` String (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux.
|
||||
|
||||
Writes the `text` into the clipboard as plain text.
|
||||
|
||||
```js
|
||||
const { clipboard } = require('electron')
|
||||
|
||||
const text = 'hello i am a bit of text!'
|
||||
clipboard.writeText(text)
|
||||
```
|
||||
|
||||
### `clipboard.readHTML([type])`
|
||||
|
||||
* `type` String (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux.
|
||||
|
||||
Returns `String` - The content in the clipboard as markup.
|
||||
|
||||
```js
|
||||
const { clipboard } = require('electron')
|
||||
|
||||
clipboard.writeHTML('<b>Hi</b>')
|
||||
const html = clipboard.readHTML()
|
||||
|
||||
console.log(html)
|
||||
// <meta charset='utf-8'><b>Hi</b>
|
||||
```
|
||||
|
||||
### `clipboard.writeHTML(markup[, type])`
|
||||
|
||||
* `markup` String
|
||||
* `type` String (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux.
|
||||
|
||||
Writes `markup` to the clipboard.
|
||||
|
||||
```js
|
||||
const { clipboard } = require('electron')
|
||||
|
||||
clipboard.writeHTML('<b>Hi</b')
|
||||
```
|
||||
|
||||
### `clipboard.readImage([type])`
|
||||
|
||||
* `type` String (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux.
|
||||
|
||||
Returns [`NativeImage`](latest/api/native-image.md) - The image content in the clipboard.
|
||||
|
||||
### `clipboard.writeImage(image[, type])`
|
||||
|
||||
* `image` [NativeImage](latest/api/native-image.md)
|
||||
* `type` String (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux.
|
||||
|
||||
Writes `image` to the clipboard.
|
||||
|
||||
### `clipboard.readRTF([type])`
|
||||
|
||||
* `type` String (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux.
|
||||
|
||||
Returns `String` - The content in the clipboard as RTF.
|
||||
|
||||
```js
|
||||
const { clipboard } = require('electron')
|
||||
|
||||
clipboard.writeRTF('{\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}\\f0\\pard\nThis is some {\\b bold} text.\\par\n}')
|
||||
|
||||
const rtf = clipboard.readRTF()
|
||||
console.log(rtf)
|
||||
// {\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}\\f0\\pard\nThis is some {\\b bold} text.\\par\n}
|
||||
```
|
||||
|
||||
### `clipboard.writeRTF(text[, type])`
|
||||
|
||||
* `text` String
|
||||
* `type` String (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux.
|
||||
|
||||
Writes the `text` into the clipboard in RTF.
|
||||
|
||||
```js
|
||||
const { clipboard } = require('electron')
|
||||
|
||||
const rtf = '{\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}\\f0\\pard\nThis is some {\\b bold} text.\\par\n}'
|
||||
clipboard.writeRTF(rtf)
|
||||
```
|
||||
|
||||
### `clipboard.readBookmark()` _macOS_ _Windows_
|
||||
|
||||
Returns `Object`:
|
||||
|
||||
* `title` String
|
||||
* `url` String
|
||||
|
||||
Returns an Object containing `title` and `url` keys representing the bookmark in
|
||||
the clipboard. The `title` and `url` values will be empty strings when the
|
||||
bookmark is unavailable.
|
||||
|
||||
### `clipboard.writeBookmark(title, url[, type])` _macOS_ _Windows_
|
||||
|
||||
* `title` String
|
||||
* `url` String
|
||||
* `type` String (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux.
|
||||
|
||||
Writes the `title` and `url` into the clipboard as a bookmark.
|
||||
|
||||
**Note:** Most apps on Windows don't support pasting bookmarks into them so
|
||||
you can use `clipboard.write` to write both a bookmark and fallback text to the
|
||||
clipboard.
|
||||
|
||||
```js
|
||||
const { clipboard } = require('electron')
|
||||
|
||||
clipboard.writeBookmark({
|
||||
text: 'https://electronjs.org',
|
||||
bookmark: 'Electron Homepage'
|
||||
})
|
||||
```
|
||||
|
||||
### `clipboard.readFindText()` _macOS_
|
||||
|
||||
Returns `String` - The text on the find pasteboard, which is the pasteboard that holds information about the current state of the active application’s find panel.
|
||||
|
||||
This method uses synchronous IPC when called from the renderer process.
|
||||
The cached value is reread from the find pasteboard whenever the application is activated.
|
||||
|
||||
### `clipboard.writeFindText(text)` _macOS_
|
||||
|
||||
* `text` String
|
||||
|
||||
Writes the `text` into the find pasteboard (the pasteboard that holds information about the current state of the active application’s find panel) as plain text. This method uses synchronous IPC when called from the renderer process.
|
||||
|
||||
### `clipboard.clear([type])`
|
||||
|
||||
* `type` String (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux.
|
||||
|
||||
Clears the clipboard content.
|
||||
|
||||
### `clipboard.availableFormats([type])`
|
||||
|
||||
* `type` String (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux.
|
||||
|
||||
Returns `String[]` - An array of supported formats for the clipboard `type`.
|
||||
|
||||
```js
|
||||
const { clipboard } = require('electron')
|
||||
|
||||
const formats = clipboard.availableFormats()
|
||||
console.log(formats)
|
||||
// [ 'text/plain', 'text/html' ]
|
||||
```
|
||||
|
||||
### `clipboard.has(format[, type])` _Experimental_
|
||||
|
||||
* `format` String
|
||||
* `type` String (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux.
|
||||
|
||||
Returns `Boolean` - Whether the clipboard supports the specified `format`.
|
||||
|
||||
```js
|
||||
const { clipboard } = require('electron')
|
||||
|
||||
const hasFormat = clipboard.has('<p>selection</p>')
|
||||
console.log(hasFormat)
|
||||
// 'true' or 'false'
|
||||
```
|
||||
|
||||
### `clipboard.read(format)` _Experimental_
|
||||
|
||||
* `format` String
|
||||
|
||||
Returns `String` - Reads `format` type from the clipboard.
|
||||
|
||||
`format` should contain valid ASCII characters and have `/` separator.
|
||||
`a/c`, `a/bc` are valid formats while `/abc`, `abc/`, `a/`, `/a`, `a`
|
||||
are not valid.
|
||||
|
||||
### `clipboard.readBuffer(format)` _Experimental_
|
||||
|
||||
* `format` String
|
||||
|
||||
Returns `Buffer` - Reads `format` type from the clipboard.
|
||||
|
||||
```js
|
||||
const { clipboard } = require('electron')
|
||||
|
||||
const buffer = Buffer.from('this is binary', 'utf8')
|
||||
clipboard.writeBuffer('public/utf8-plain-text', buffer)
|
||||
|
||||
const ret = clipboard.readBuffer('public/utf8-plain-text')
|
||||
|
||||
console.log(buffer.equals(out))
|
||||
// true
|
||||
```
|
||||
|
||||
### `clipboard.writeBuffer(format, buffer[, type])` _Experimental_
|
||||
|
||||
* `format` String
|
||||
* `buffer` Buffer
|
||||
* `type` String (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux.
|
||||
|
||||
Writes the `buffer` into the clipboard as `format`.
|
||||
|
||||
```js
|
||||
const { clipboard } = require('electron')
|
||||
|
||||
const buffer = Buffer.from('writeBuffer', 'utf8')
|
||||
clipboard.writeBuffer('public/utf8-plain-text', buffer)
|
||||
```
|
||||
|
||||
### `clipboard.write(data[, type])`
|
||||
|
||||
* `data` Object
|
||||
* `text` String (optional)
|
||||
* `html` String (optional)
|
||||
* `image` [NativeImage](latest/api/native-image.md) (optional)
|
||||
* `rtf` String (optional)
|
||||
* `bookmark` String (optional) - The title of the URL at `text`.
|
||||
* `type` String (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux.
|
||||
|
||||
Writes `data` to the clipboard.
|
||||
|
||||
```js
|
||||
const { clipboard } = require('electron')
|
||||
|
||||
clipboard.write({
|
||||
text: 'test',
|
||||
html: '<b>Hi</b>',
|
||||
rtf: '{\\rtf1\\utf8 text}',
|
||||
bookmark: 'a title'
|
||||
})
|
||||
|
||||
console.log(clipboard.readText())
|
||||
// 'test'
|
||||
|
||||
console.log(clipboard.readHTML())
|
||||
// <meta charset='utf-8'><b>Hi</b>
|
||||
|
||||
console.log(clipboard.readRTF())
|
||||
// '{\\rtf1\\utf8 text}'
|
||||
|
||||
console.log(clipboard.readBookmark())
|
||||
// { title: 'a title', url: 'test' }
|
||||
```
|
|
@ -0,0 +1,294 @@
|
|||
---
|
||||
title: "Supported Command Line Switches"
|
||||
description: "Command line switches supported by Electron."
|
||||
slug: command-line-switches
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Supported Command Line Switches
|
||||
|
||||
> Command line switches supported by Electron.
|
||||
|
||||
You can use [app.commandLine.appendSwitch][append-switch] to append them in
|
||||
your app's main script before the [ready][ready] event of the [app][app] module
|
||||
is emitted:
|
||||
|
||||
```javascript
|
||||
const { app } = require('electron')
|
||||
app.commandLine.appendSwitch('remote-debugging-port', '8315')
|
||||
app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1')
|
||||
|
||||
app.whenReady().then(() => {
|
||||
// Your code here
|
||||
})
|
||||
```
|
||||
|
||||
## Electron CLI Flags
|
||||
|
||||
### --auth-server-whitelist=`url`
|
||||
|
||||
A comma-separated list of servers for which integrated authentication is enabled.
|
||||
|
||||
For example:
|
||||
|
||||
```sh
|
||||
--auth-server-whitelist='*example.com, *foobar.com, *baz'
|
||||
```
|
||||
|
||||
then any `url` ending with `example.com`, `foobar.com`, `baz` will be considered
|
||||
for integrated authentication. Without `*` prefix the URL has to match exactly.
|
||||
|
||||
### --auth-negotiate-delegate-whitelist=`url`
|
||||
|
||||
A comma-separated list of servers for which delegation of user credentials is required.
|
||||
Without `*` prefix the URL has to match exactly.
|
||||
|
||||
### --disable-ntlm-v2
|
||||
|
||||
Disables NTLM v2 for posix platforms, no effect elsewhere.
|
||||
|
||||
### --disable-http-cache
|
||||
|
||||
Disables the disk cache for HTTP requests.
|
||||
|
||||
### --disable-http2
|
||||
|
||||
Disable HTTP/2 and SPDY/3.1 protocols.
|
||||
|
||||
### --disable-renderer-backgrounding
|
||||
|
||||
Prevents Chromium from lowering the priority of invisible pages' renderer
|
||||
processes.
|
||||
|
||||
This flag is global to all renderer processes, if you only want to disable
|
||||
throttling in one window, you can take the hack of
|
||||
[playing silent audio][play-silent-audio].
|
||||
|
||||
### --disk-cache-size=`size`
|
||||
|
||||
Forces the maximum disk space to be used by the disk cache, in bytes.
|
||||
|
||||
### --enable-api-filtering-logging
|
||||
|
||||
Enables caller stack logging for the following APIs (filtering events):
|
||||
|
||||
* `desktopCapturer.getSources()` / `desktop-capturer-get-sources`
|
||||
|
||||
### --enable-logging[=file]
|
||||
|
||||
Prints Chromium's logging to stderr (or a log file).
|
||||
|
||||
The `ELECTRON_ENABLE_LOGGING` environment variable has the same effect as
|
||||
passing `--enable-logging`.
|
||||
|
||||
Passing `--enable-logging` will result in logs being printed on stderr.
|
||||
Passing `--enable-logging=file` will result in logs being saved to the file
|
||||
specified by `--log-file=...`, or to `electron_debug.log` in the user-data
|
||||
directory if `--log-file` is not specified.
|
||||
|
||||
> **Note:** On Windows, logs from child processes cannot be sent to stderr.
|
||||
> Logging to a file is the most reliable way to collect logs on Windows.
|
||||
|
||||
See also `--log-file`, `--log-level`, `--v`, and `--vmodule`.
|
||||
|
||||
### --force-fieldtrials=`trials`
|
||||
|
||||
Field trials to be forcefully enabled or disabled.
|
||||
|
||||
For example: `WebRTC-Audio-Red-For-Opus/Enabled/`
|
||||
|
||||
### --host-rules=`rules`
|
||||
|
||||
A comma-separated list of `rules` that control how hostnames are mapped.
|
||||
|
||||
For example:
|
||||
|
||||
* `MAP * 127.0.0.1` Forces all hostnames to be mapped to 127.0.0.1
|
||||
* `MAP *.google.com proxy` Forces all google.com subdomains to be resolved to
|
||||
"proxy".
|
||||
* `MAP test.com [::1]:77` Forces "test.com" to resolve to IPv6 loopback. Will
|
||||
also force the port of the resulting socket address to be 77.
|
||||
* `MAP * baz, EXCLUDE www.google.com` Remaps everything to "baz", except for
|
||||
"www.google.com".
|
||||
|
||||
These mappings apply to the endpoint host in a net request (the TCP connect
|
||||
and host resolver in a direct connection, and the `CONNECT` in an HTTP proxy
|
||||
connection, and the endpoint host in a `SOCKS` proxy connection).
|
||||
|
||||
### --host-resolver-rules=`rules`
|
||||
|
||||
Like `--host-rules` but these `rules` only apply to the host resolver.
|
||||
|
||||
### --ignore-certificate-errors
|
||||
|
||||
Ignores certificate related errors.
|
||||
|
||||
### --ignore-connections-limit=`domains`
|
||||
|
||||
Ignore the connections limit for `domains` list separated by `,`.
|
||||
|
||||
### --js-flags=`flags`
|
||||
|
||||
Specifies the flags passed to the Node.js engine. It has to be passed when starting
|
||||
Electron if you want to enable the `flags` in the main process.
|
||||
|
||||
```sh
|
||||
$ electron --js-flags="--harmony_proxies --harmony_collections" your-app
|
||||
```
|
||||
|
||||
See the [Node.js documentation][node-cli] or run `node --help` in your terminal for a list of available flags. Additionally, run `node --v8-options` to see a list of flags that specifically refer to Node.js's V8 JavaScript engine.
|
||||
|
||||
### --lang
|
||||
|
||||
Set a custom locale.
|
||||
|
||||
### --log-file=`path`
|
||||
|
||||
If `--enable-logging` is specified, logs will be written to the given path. The
|
||||
parent directory must exist.
|
||||
|
||||
Setting the `ELECTRON_LOG_FILE` environment variable is equivalent to passing
|
||||
this flag. If both are present, the command-line switch takes precedence.
|
||||
|
||||
### --log-net-log=`path`
|
||||
|
||||
Enables net log events to be saved and writes them to `path`.
|
||||
|
||||
### --log-level=`N`
|
||||
|
||||
Sets the verbosity of logging when used together with `--enable-logging`.
|
||||
`N` should be one of [Chrome's LogSeverities][severities].
|
||||
|
||||
Note that two complimentary logging mechanisms in Chromium -- `LOG()`
|
||||
and `VLOG()` -- are controlled by different switches. `--log-level`
|
||||
controls `LOG()` messages, while `--v` and `--vmodule` control `VLOG()`
|
||||
messages. So you may want to use a combination of these three switches
|
||||
depending on the granularity you want and what logging calls are made
|
||||
by the code you're trying to watch.
|
||||
|
||||
See [Chromium Logging source][logging] for more information on how
|
||||
`LOG()` and `VLOG()` interact. Loosely speaking, `VLOG()` can be thought
|
||||
of as sub-levels / per-module levels inside `LOG(INFO)` to control the
|
||||
firehose of `LOG(INFO)` data.
|
||||
|
||||
See also `--enable-logging`, `--log-level`, `--v`, and `--vmodule`.
|
||||
|
||||
### --no-proxy-server
|
||||
|
||||
Don't use a proxy server and always make direct connections. Overrides any other
|
||||
proxy server flags that are passed.
|
||||
|
||||
### --no-sandbox
|
||||
|
||||
Disables the Chromium [sandbox](https://www.chromium.org/developers/design-documents/sandbox).
|
||||
Forces renderer process and Chromium helper processes to run un-sandboxed.
|
||||
Should only be used for testing.
|
||||
|
||||
### --proxy-bypass-list=`hosts`
|
||||
|
||||
Instructs Electron to bypass the proxy server for the given semi-colon-separated
|
||||
list of hosts. This flag has an effect only if used in tandem with
|
||||
`--proxy-server`.
|
||||
|
||||
For example:
|
||||
|
||||
```javascript
|
||||
const { app } = require('electron')
|
||||
app.commandLine.appendSwitch('proxy-bypass-list', '<local>;*.google.com;*foo.com;1.2.3.4:5678')
|
||||
```
|
||||
|
||||
Will use the proxy server for all hosts except for local addresses (`localhost`,
|
||||
`127.0.0.1` etc.), `google.com` subdomains, hosts that contain the suffix
|
||||
`foo.com` and anything at `1.2.3.4:5678`.
|
||||
|
||||
### --proxy-pac-url=`url`
|
||||
|
||||
Uses the PAC script at the specified `url`.
|
||||
|
||||
### --proxy-server=`address:port`
|
||||
|
||||
Use a specified proxy server, which overrides the system setting. This switch
|
||||
only affects requests with HTTP protocol, including HTTPS and WebSocket
|
||||
requests. It is also noteworthy that not all proxy servers support HTTPS and
|
||||
WebSocket requests. The proxy URL does not support username and password
|
||||
authentication [per Chromium issue](https://bugs.chromium.org/p/chromium/issues/detail?id=615947).
|
||||
|
||||
### --remote-debugging-port=`port`
|
||||
|
||||
Enables remote debugging over HTTP on the specified `port`.
|
||||
|
||||
### --v=`log_level`
|
||||
|
||||
Gives the default maximal active V-logging level; 0 is the default. Normally
|
||||
positive values are used for V-logging levels.
|
||||
|
||||
This switch only works when `--enable-logging` is also passed.
|
||||
|
||||
See also `--enable-logging`, `--log-level`, and `--vmodule`.
|
||||
|
||||
### --vmodule=`pattern`
|
||||
|
||||
Gives the per-module maximal V-logging levels to override the value given by
|
||||
`--v`. E.g. `my_module=2,foo*=3` would change the logging level for all code in
|
||||
source files `my_module.*` and `foo*.*`.
|
||||
|
||||
Any pattern containing a forward or backward slash will be tested against the
|
||||
whole pathname and not only the module. E.g. `*/foo/bar/*=2` would change the
|
||||
logging level for all code in the source files under a `foo/bar` directory.
|
||||
|
||||
This switch only works when `--enable-logging` is also passed.
|
||||
|
||||
See also `--enable-logging`, `--log-level`, and `--v`.
|
||||
|
||||
### --force_high_performance_gpu
|
||||
|
||||
Force using discrete GPU when there are multiple GPUs available.
|
||||
|
||||
### --force_low_power_gpu
|
||||
|
||||
Force using integrated GPU when there are multiple GPUs available.
|
||||
|
||||
## Node.js Flags
|
||||
|
||||
Electron supports some of the [CLI flags][node-cli] supported by Node.js.
|
||||
|
||||
**Note:** Passing unsupported command line switches to Electron when it is not running in `ELECTRON_RUN_AS_NODE` will have no effect.
|
||||
|
||||
### --inspect-brk[=[host:]port]
|
||||
|
||||
Activate inspector on host:port and break at start of user script. Default host:port is 127.0.0.1:9229.
|
||||
|
||||
Aliased to `--debug-brk=[host:]port`.
|
||||
|
||||
### --inspect-port=[host:]port
|
||||
|
||||
Set the `host:port` to be used when the inspector is activated. Useful when activating the inspector by sending the SIGUSR1 signal. Default host is `127.0.0.1`.
|
||||
|
||||
Aliased to `--debug-port=[host:]port`.
|
||||
|
||||
### --inspect[=[host:]port]
|
||||
|
||||
Activate inspector on `host:port`. Default is `127.0.0.1:9229`.
|
||||
|
||||
V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug and profile Electron instances. The tools attach to Electron instances via a TCP port and communicate using the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/).
|
||||
|
||||
See the [Debugging the Main Process][debugging-main-process] guide for more details.
|
||||
|
||||
Aliased to `--debug[=[host:]port`.
|
||||
|
||||
### --inspect-publish-uid=stderr,http
|
||||
|
||||
Specify ways of the inspector web socket url exposure.
|
||||
|
||||
By default inspector websocket url is available in stderr and under /json/list endpoint on http://host:port/json/list.
|
||||
|
||||
[app]: latest/api/app.md
|
||||
[append-switch]: latest/api/command-line.md#commandlineappendswitchswitch-value
|
||||
[ready]: latest/api/app.md#event-ready
|
||||
[play-silent-audio]: https://github.com/atom/atom/pull/9485/files
|
||||
[debugging-main-process]: latest/tutorial/debugging-main-process.md
|
||||
[logging]: https://source.chromium.org/chromium/chromium/src/+/master:base/logging.h
|
||||
[node-cli]: https://nodejs.org/api/cli.html
|
||||
[play-silent-audio]: https://github.com/atom/atom/pull/9485/files
|
||||
[ready]: latest/api/app.md#event-ready
|
||||
[severities]: https://source.chromium.org/chromium/chromium/src/+/master:base/logging.h?q=logging::LogSeverity&ss=chromium
|
|
@ -0,0 +1,62 @@
|
|||
---
|
||||
title: "Class: CommandLine"
|
||||
description: "Manipulate the command line arguments for your app that Chromium reads"
|
||||
slug: command-line
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
## Class: CommandLine
|
||||
|
||||
> Manipulate the command line arguments for your app that Chromium reads
|
||||
|
||||
Process: [Main](latest/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._
|
||||
|
||||
The following example shows how to check if the `--disable-gpu` flag is set.
|
||||
|
||||
```javascript
|
||||
const { app } = require('electron')
|
||||
app.commandLine.hasSwitch('disable-gpu')
|
||||
```
|
||||
|
||||
For more information on what kinds of flags and switches you can use, check
|
||||
out the [Command Line Switches](latest/api/command-line-switches.md)
|
||||
document.
|
||||
|
||||
### Instance Methods
|
||||
|
||||
#### `commandLine.appendSwitch(switch[, value])`
|
||||
|
||||
* `switch` String - A command-line switch, without the leading `--`
|
||||
* `value` String (optional) - A value for the given switch
|
||||
|
||||
Append a switch (with optional `value`) to Chromium's command line.
|
||||
|
||||
**Note:** This will not affect `process.argv`. The intended usage of this function is to
|
||||
control Chromium's behavior.
|
||||
|
||||
#### `commandLine.appendArgument(value)`
|
||||
|
||||
* `value` String - The argument to append to the command line
|
||||
|
||||
Append an argument to Chromium's command line. The argument will be quoted
|
||||
correctly. Switches will precede arguments regardless of appending order.
|
||||
|
||||
If you're appending an argument like `--switch=value`, consider using `appendSwitch('switch', 'value')` instead.
|
||||
|
||||
**Note:** This will not affect `process.argv`. The intended usage of this function is to
|
||||
control Chromium's behavior.
|
||||
|
||||
#### `commandLine.hasSwitch(switch)`
|
||||
|
||||
* `switch` String - A command-line switch
|
||||
|
||||
Returns `Boolean` - Whether the command-line switch is present.
|
||||
|
||||
#### `commandLine.getSwitchValue(switch)`
|
||||
|
||||
* `switch` String - A command-line switch
|
||||
|
||||
Returns `String` - The command-line switch value.
|
||||
|
||||
**Note:** When the switch is not present or has no value, it returns empty string.
|
|
@ -0,0 +1,93 @@
|
|||
---
|
||||
title: "contentTracing"
|
||||
description: "Collect tracing data from Chromium to find performance bottlenecks and slow operations."
|
||||
slug: content-tracing
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# contentTracing
|
||||
|
||||
> Collect tracing data from Chromium to find performance bottlenecks and slow operations.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
This module does not include a web interface. To view recorded traces, use
|
||||
[trace viewer][], available at `chrome://tracing` in Chrome.
|
||||
|
||||
**Note:** You should not use this module until the `ready` event of the app
|
||||
module is emitted.
|
||||
|
||||
```javascript
|
||||
const { app, contentTracing } = require('electron')
|
||||
|
||||
app.whenReady().then(() => {
|
||||
(async () => {
|
||||
await contentTracing.startRecording({
|
||||
included_categories: ['*']
|
||||
})
|
||||
console.log('Tracing started')
|
||||
await new Promise(resolve => setTimeout(resolve, 5000))
|
||||
const path = await contentTracing.stopRecording()
|
||||
console.log('Tracing data recorded to ' + path)
|
||||
})()
|
||||
})
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
The `contentTracing` module has the following methods:
|
||||
|
||||
### `contentTracing.getCategories()`
|
||||
|
||||
Returns `Promise<String[]>` - resolves with an array of category groups once all child processes have acknowledged the `getCategories` request
|
||||
|
||||
Get a set of category groups. The category groups can change as new code paths
|
||||
are reached. See also the [list of built-in tracing
|
||||
categories](https://chromium.googlesource.com/chromium/src/+/master/base/trace_event/builtin_categories.h).
|
||||
|
||||
> **NOTE:** Electron adds a non-default tracing category called `"electron"`.
|
||||
> This category can be used to capture Electron-specific tracing events.
|
||||
|
||||
### `contentTracing.startRecording(options)`
|
||||
|
||||
* `options` ([TraceConfig](latest/api/structures/trace-config.md) | [TraceCategoriesAndOptions](latest/api/structures/trace-categories-and-options.md))
|
||||
|
||||
Returns `Promise<void>` - resolved once all child processes have acknowledged the `startRecording` request.
|
||||
|
||||
Start recording on all processes.
|
||||
|
||||
Recording begins immediately locally and asynchronously on child processes
|
||||
as soon as they receive the EnableRecording request.
|
||||
|
||||
If a recording is already running, the promise will be immediately resolved, as
|
||||
only one trace operation can be in progress at a time.
|
||||
|
||||
### `contentTracing.stopRecording([resultFilePath])`
|
||||
|
||||
* `resultFilePath` String (optional)
|
||||
|
||||
Returns `Promise<String>` - resolves with a path to a file that contains the traced data once all child processes have acknowledged the `stopRecording` request
|
||||
|
||||
Stop recording on all processes.
|
||||
|
||||
Child processes typically cache trace data and only rarely flush and send
|
||||
trace data back to the main process. This helps to minimize the runtime overhead
|
||||
of tracing since sending trace data over IPC can be an expensive operation. So,
|
||||
to end tracing, Chromium asynchronously asks all child processes to flush any
|
||||
pending trace data.
|
||||
|
||||
Trace data will be written into `resultFilePath`. If `resultFilePath` is empty
|
||||
or not provided, trace data will be written to a temporary file, and the path
|
||||
will be returned in the promise.
|
||||
|
||||
### `contentTracing.getTraceBufferUsage()`
|
||||
|
||||
Returns `Promise<Object>` - Resolves with an object containing the `value` and `percentage` of trace buffer maximum usage
|
||||
|
||||
* `value` Number
|
||||
* `percentage` Number
|
||||
|
||||
Get the maximum usage across processes of trace buffer as a percentage of the
|
||||
full state.
|
||||
|
||||
[trace viewer]: latest/development/README.md
|
|
@ -0,0 +1,139 @@
|
|||
---
|
||||
title: "contextBridge"
|
||||
description: "Create a safe, bi-directional, synchronous bridge across isolated contexts"
|
||||
slug: context-bridge
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# contextBridge
|
||||
|
||||
> Create a safe, bi-directional, synchronous bridge across isolated contexts
|
||||
|
||||
Process: [Renderer](latest/glossary.md#renderer-process)
|
||||
|
||||
An example of exposing an API to a renderer from an isolated preload script is given below:
|
||||
|
||||
```javascript
|
||||
// Preload (Isolated World)
|
||||
const { contextBridge, ipcRenderer } = require('electron')
|
||||
|
||||
contextBridge.exposeInMainWorld(
|
||||
'electron',
|
||||
{
|
||||
doThing: () => ipcRenderer.send('do-a-thing')
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
```javascript
|
||||
// Renderer (Main World)
|
||||
|
||||
window.electron.doThing()
|
||||
```
|
||||
|
||||
## Glossary
|
||||
|
||||
### Main World
|
||||
|
||||
The "Main World" is the JavaScript context that your main renderer code runs in. By default, the
|
||||
page you load in your renderer executes code in this world.
|
||||
|
||||
### Isolated World
|
||||
|
||||
When `contextIsolation` is enabled in your `webPreferences` (this is the default behavior since Electron 12.0.0), your `preload` scripts run in an
|
||||
"Isolated World". You can read more about context isolation and what it affects in the
|
||||
[security](latest/tutorial/security.md#3-enable-context-isolation-for-remote-content) docs.
|
||||
|
||||
## Methods
|
||||
|
||||
The `contextBridge` module has the following methods:
|
||||
|
||||
### `contextBridge.exposeInMainWorld(apiKey, api)`
|
||||
|
||||
* `apiKey` String - The key to inject the API onto `window` with. The API will be accessible on `window[apiKey]`.
|
||||
* `api` any - Your API, more information on what this API can be and how it works is available below.
|
||||
|
||||
## Usage
|
||||
|
||||
### API
|
||||
|
||||
The `api` provided to [`exposeInMainWorld`](#contextbridgeexposeinmainworldapikey-api) must be a `Function`, `String`, `Number`, `Array`, `Boolean`, or an object
|
||||
whose keys are strings and values are a `Function`, `String`, `Number`, `Array`, `Boolean`, or another nested object that meets the same conditions.
|
||||
|
||||
`Function` values are proxied to the other context and all other values are **copied** and **frozen**. Any data / primitives sent in
|
||||
the API become immutable and updates on either side of the bridge do not result in an update on the other side.
|
||||
|
||||
An example of a complex API is shown below:
|
||||
|
||||
```javascript
|
||||
const { contextBridge } = require('electron')
|
||||
|
||||
contextBridge.exposeInMainWorld(
|
||||
'electron',
|
||||
{
|
||||
doThing: () => ipcRenderer.send('do-a-thing'),
|
||||
myPromises: [Promise.resolve(), Promise.reject(new Error('whoops'))],
|
||||
anAsyncFunction: async () => 123,
|
||||
data: {
|
||||
myFlags: ['a', 'b', 'c'],
|
||||
bootTime: 1234
|
||||
},
|
||||
nestedAPI: {
|
||||
evenDeeper: {
|
||||
youCanDoThisAsMuchAsYouWant: {
|
||||
fn: () => ({
|
||||
returnData: 123
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
### API Functions
|
||||
|
||||
`Function` values that you bind through the `contextBridge` are proxied through Electron to ensure that contexts remain isolated. This
|
||||
results in some key limitations that we've outlined below.
|
||||
|
||||
#### Parameter / Error / Return Type support
|
||||
|
||||
Because parameters, errors and return values are **copied** when they are sent over the bridge, there are only certain types that can be used.
|
||||
At a high level, if the type you want to use can be serialized and deserialized into the same object it will work. A table of type support
|
||||
has been included below for completeness:
|
||||
|
||||
| Type | Complexity | Parameter Support | Return Value Support | Limitations |
|
||||
| ---- | ---------- | ----------------- | -------------------- | ----------- |
|
||||
| `String` | Simple | ✅ | ✅ | N/A |
|
||||
| `Number` | Simple | ✅ | ✅ | N/A |
|
||||
| `Boolean` | Simple | ✅ | ✅ | N/A |
|
||||
| `Object` | Complex | ✅ | ✅ | Keys must be supported using only "Simple" types in this table. Values must be supported in this table. Prototype modifications are dropped. Sending custom classes will copy values but not the prototype. |
|
||||
| `Array` | Complex | ✅ | ✅ | Same limitations as the `Object` type |
|
||||
| `Error` | Complex | ✅ | ✅ | Errors that are thrown are also copied, this can result in the message and stack trace of the error changing slightly due to being thrown in a different context |
|
||||
| `Promise` | Complex | ✅ | ✅ | Promises are only proxied if they are the return value or exact parameter. Promises nested in arrays or objects will be dropped. |
|
||||
| `Function` | Complex | ✅ | ✅ | Prototype modifications are dropped. Sending classes or constructors will not work. |
|
||||
| [Cloneable Types](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) | Simple | ✅ | ✅ | See the linked document on cloneable types |
|
||||
| `Element` | Complex | ✅ | ✅ | Prototype modifications are dropped. Sending custom elements will not work. |
|
||||
| `Blob` | Complex | ✅ | ✅ | N/A |
|
||||
| `Symbol` | N/A | ❌ | ❌ | Symbols cannot be copied across contexts so they are dropped |
|
||||
|
||||
If the type you care about is not in the above table, it is probably not supported.
|
||||
|
||||
### Exposing Node Global Symbols
|
||||
|
||||
The `contextBridge` can be used by the preload script to give your renderer access to Node APIs.
|
||||
The table of supported types described above also applies to Node APIs that you expose through `contextBridge`.
|
||||
Please note that many Node APIs grant access to local system resources.
|
||||
Be very cautious about which globals and APIs you expose to untrusted remote content.
|
||||
|
||||
```javascript
|
||||
const { contextBridge } = require('electron')
|
||||
const crypto = require('crypto')
|
||||
contextBridge.exposeInMainWorld('nodeCrypto', {
|
||||
sha256sum (data) {
|
||||
const hash = crypto.createHash('sha256')
|
||||
hash.update(data)
|
||||
return hash.digest('hex')
|
||||
}
|
||||
})
|
||||
```
|
|
@ -0,0 +1,128 @@
|
|||
---
|
||||
title: "Class: Cookies"
|
||||
description: "Query and modify a session's cookies."
|
||||
slug: cookies
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
## Class: Cookies
|
||||
|
||||
> Query and modify a session's cookies.
|
||||
|
||||
Process: [Main](latest/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._
|
||||
|
||||
Instances of the `Cookies` class are accessed by using `cookies` property of
|
||||
a `Session`.
|
||||
|
||||
For example:
|
||||
|
||||
```javascript
|
||||
const { session } = require('electron')
|
||||
|
||||
// Query all cookies.
|
||||
session.defaultSession.cookies.get({})
|
||||
.then((cookies) => {
|
||||
console.log(cookies)
|
||||
}).catch((error) => {
|
||||
console.log(error)
|
||||
})
|
||||
|
||||
// Query all cookies associated with a specific url.
|
||||
session.defaultSession.cookies.get({ url: 'http://www.github.com' })
|
||||
.then((cookies) => {
|
||||
console.log(cookies)
|
||||
}).catch((error) => {
|
||||
console.log(error)
|
||||
})
|
||||
|
||||
// Set a cookie with the given cookie data;
|
||||
// may overwrite equivalent cookies if they exist.
|
||||
const cookie = { url: 'http://www.github.com', name: 'dummy_name', value: 'dummy' }
|
||||
session.defaultSession.cookies.set(cookie)
|
||||
.then(() => {
|
||||
// success
|
||||
}, (error) => {
|
||||
console.error(error)
|
||||
})
|
||||
```
|
||||
|
||||
### Instance Events
|
||||
|
||||
The following events are available on instances of `Cookies`:
|
||||
|
||||
#### Event: 'changed'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `cookie` [Cookie](latest/api/structures/cookie.md) - The cookie that was changed.
|
||||
* `cause` String - The cause of the change with one of the following values:
|
||||
* `explicit` - The cookie was changed directly by a consumer's action.
|
||||
* `overwrite` - The cookie was automatically removed due to an insert
|
||||
operation that overwrote it.
|
||||
* `expired` - The cookie was automatically removed as it expired.
|
||||
* `evicted` - The cookie was automatically evicted during garbage collection.
|
||||
* `expired-overwrite` - The cookie was overwritten with an already-expired
|
||||
expiration date.
|
||||
* `removed` Boolean - `true` if the cookie was removed, `false` otherwise.
|
||||
|
||||
Emitted when a cookie is changed because it was added, edited, removed, or
|
||||
expired.
|
||||
|
||||
### Instance Methods
|
||||
|
||||
The following methods are available on instances of `Cookies`:
|
||||
|
||||
#### `cookies.get(filter)`
|
||||
|
||||
* `filter` Object
|
||||
* `url` String (optional) - Retrieves cookies which are associated with
|
||||
`url`. Empty implies retrieving cookies of all URLs.
|
||||
* `name` String (optional) - Filters cookies by name.
|
||||
* `domain` String (optional) - Retrieves cookies whose domains match or are
|
||||
subdomains of `domains`.
|
||||
* `path` String (optional) - Retrieves cookies whose path matches `path`.
|
||||
* `secure` Boolean (optional) - Filters cookies by their Secure property.
|
||||
* `session` Boolean (optional) - Filters out session or persistent cookies.
|
||||
|
||||
Returns `Promise<Cookie[]>` - A promise which resolves an array of cookie objects.
|
||||
|
||||
Sends a request to get all cookies matching `filter`, and resolves a promise with
|
||||
the response.
|
||||
|
||||
#### `cookies.set(details)`
|
||||
|
||||
* `details` Object
|
||||
* `url` String - The URL to associate the cookie with. The promise will be rejected if the URL is invalid.
|
||||
* `name` String (optional) - The name of the cookie. Empty by default if omitted.
|
||||
* `value` String (optional) - The value of the cookie. Empty by default if omitted.
|
||||
* `domain` String (optional) - The domain of the cookie; this will be normalized with a preceding dot so that it's also valid for subdomains. Empty by default if omitted.
|
||||
* `path` String (optional) - The path of the cookie. Empty by default if omitted.
|
||||
* `secure` Boolean (optional) - Whether the cookie should be marked as Secure. Defaults to
|
||||
false unless [Same Site=None](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure) attribute is used.
|
||||
* `httpOnly` Boolean (optional) - Whether the cookie should be marked as HTTP only.
|
||||
Defaults to false.
|
||||
* `expirationDate` Double (optional) - The expiration date of the cookie as the number of
|
||||
seconds since the UNIX epoch. If omitted then the cookie becomes a session
|
||||
cookie and will not be retained between sessions.
|
||||
* `sameSite` String (optional) - The [Same Site](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#SameSite_cookies) policy to apply to this cookie. Can be `unspecified`, `no_restriction`, `lax` or `strict`. Default is `no_restriction`.
|
||||
|
||||
Returns `Promise<void>` - A promise which resolves when the cookie has been set
|
||||
|
||||
Sets a cookie with `details`.
|
||||
|
||||
#### `cookies.remove(url, name)`
|
||||
|
||||
* `url` String - The URL associated with the cookie.
|
||||
* `name` String - The name of cookie to remove.
|
||||
|
||||
Returns `Promise<void>` - A promise which resolves when the cookie has been removed
|
||||
|
||||
Removes the cookies matching `url` and `name`
|
||||
|
||||
#### `cookies.flushStore()`
|
||||
|
||||
Returns `Promise<void>` - A promise which resolves when the cookie store has been flushed
|
||||
|
||||
Writes any unwritten cookies data to disk.
|
|
@ -0,0 +1,230 @@
|
|||
---
|
||||
title: "crashReporter"
|
||||
description: "Submit crash reports to a remote server."
|
||||
slug: crash-reporter
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# crashReporter
|
||||
|
||||
> Submit crash reports to a remote server.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process), [Renderer](latest/glossary.md#renderer-process)
|
||||
|
||||
The following is an example of setting up Electron to automatically submit
|
||||
crash reports to a remote server:
|
||||
|
||||
```javascript
|
||||
const { crashReporter } = require('electron')
|
||||
|
||||
crashReporter.start({ submitURL: 'https://your-domain.com/url-to-submit' })
|
||||
```
|
||||
|
||||
For setting up a server to accept and process crash reports, you can use
|
||||
following projects:
|
||||
|
||||
* [socorro](https://github.com/mozilla/socorro)
|
||||
* [mini-breakpad-server](https://github.com/electron/mini-breakpad-server)
|
||||
|
||||
Or use a 3rd party hosted solution:
|
||||
|
||||
* [Backtrace](https://backtrace.io/electron/)
|
||||
* [Sentry](https://docs.sentry.io/clients/electron)
|
||||
* [BugSplat](https://www.bugsplat.com/docs/platforms/electron)
|
||||
|
||||
Crash reports are stored temporarily before being uploaded in a directory
|
||||
underneath the app's user data directory (called 'Crashpad' on Windows and Mac,
|
||||
or 'Crash Reports' on Linux). You can override this directory by calling
|
||||
`app.setPath('crashDumps', '/path/to/crashes')` before starting the crash
|
||||
reporter.
|
||||
|
||||
On Windows and macOS, Electron uses
|
||||
[crashpad](latest/development/README.md)
|
||||
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.
|
||||
|
||||
### Note about Node child processes on Linux
|
||||
|
||||
If you are using the Node.js `child_process` module and want to report crashes
|
||||
from those processes on Linux, there is an extra step you will need to take to
|
||||
properly initialize the crash reporter in the child process. This is not
|
||||
necessary on Mac or Windows, as those platforms use Crashpad, which
|
||||
automatically monitors child processes.
|
||||
|
||||
Since `require('electron')` is not available in Node child processes, the
|
||||
following APIs are available on the `process` object in Node child processes.
|
||||
Note that, on Linux, each Node child process has its own separate instance of
|
||||
the breakpad crash reporter. This is dissimilar to renderer child processes,
|
||||
which have a "stub" breakpad reporter which returns information to the main
|
||||
process for reporting.
|
||||
|
||||
#### `process.crashReporter.start(options)`
|
||||
|
||||
See [`crashReporter.start()`](#crashreporterstartoptions).
|
||||
|
||||
#### `process.crashReporter.getParameters()`
|
||||
|
||||
See [`crashReporter.getParameters()`](#crashreportergetparameters).
|
||||
|
||||
#### `process.crashReporter.addExtraParameter(key, value)`
|
||||
|
||||
See [`crashReporter.addExtraParameter(key, value)`](#crashreporteraddextraparameterkey-value).
|
||||
|
||||
#### `process.crashReporter.removeExtraParameter(key)`
|
||||
|
||||
See [`crashReporter.removeExtraParameter(key)`](#crashreporterremoveextraparameterkey).
|
||||
|
||||
## Methods
|
||||
|
||||
The `crashReporter` module has the following methods:
|
||||
|
||||
### `crashReporter.start(options)`
|
||||
|
||||
* `options` Object
|
||||
* `submitURL` String (optional) - URL that crash reports will be sent to as
|
||||
POST. Required unless `uploadToServer` is `false`.
|
||||
* `productName` String (optional) - Defaults to `app.name`.
|
||||
* `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) - If true, crash reports will be compressed
|
||||
and uploaded with `Content-Encoding: gzip`. Default is `true`.
|
||||
* `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.
|
||||
|
||||
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.
|
||||
|
||||
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:** You can test out the crash reporter by generating a crash using
|
||||
`process.crash()`.
|
||||
|
||||
**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:** This method is only available in the main process.
|
||||
|
||||
### `crashReporter.getLastCrashReport()`
|
||||
|
||||
Returns [`CrashReport`](latest/api/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.
|
||||
|
||||
**Note:** This method is only available in the main process.
|
||||
|
||||
### `crashReporter.getUploadedReports()`
|
||||
|
||||
Returns [`CrashReport[]`](latest/api/structures/crash-report.md):
|
||||
|
||||
Returns all uploaded crash reports. Each report contains the date and uploaded
|
||||
ID.
|
||||
|
||||
**Note:** This method is only available in the main process.
|
||||
|
||||
### `crashReporter.getUploadToServer()`
|
||||
|
||||
Returns `Boolean` - Whether reports should be submitted to the server. Set through
|
||||
the `start` method or `setUploadToServer`.
|
||||
|
||||
**Note:** This method is only available in the main process.
|
||||
|
||||
### `crashReporter.setUploadToServer(uploadToServer)`
|
||||
|
||||
* `uploadToServer` Boolean - Whether reports should be submitted to the server.
|
||||
|
||||
This would normally be controlled by user preferences. This has no effect if
|
||||
called before `start` is called.
|
||||
|
||||
**Note:** This method is only available in the main process.
|
||||
|
||||
### `crashReporter.addExtraParameter(key, value)`
|
||||
|
||||
* `key` String - Parameter key, must be no longer than 39 bytes.
|
||||
* `value` String - Parameter value, must be no longer than 127 bytes.
|
||||
|
||||
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.
|
||||
|
||||
Parameters added in this fashion (or via the `extra` parameter to
|
||||
`crashReporter.start`) are specific to the calling process. Adding extra
|
||||
parameters in the main process will not cause those parameters to be sent along
|
||||
with crashes from renderer or other child processes. Similarly, adding extra
|
||||
parameters in a renderer process will not result in those parameters being sent
|
||||
with crashes that occur in other renderer processes or in the main process.
|
||||
|
||||
**Note:** Parameters have limits on the length of the keys and values. Key
|
||||
names must be no longer than 39 bytes, and values must be no longer than 20320
|
||||
bytes. Keys with names longer than the maximum will be silently ignored. Key
|
||||
values longer than the maximum length will be truncated.
|
||||
|
||||
**Note:** On linux values that are longer than 127 bytes will be chunked into
|
||||
multiple keys, each 127 bytes in length. E.g. `addExtraParameter('foo', 'a'.repeat(130))`
|
||||
will result in two chunked keys `foo__1` and `foo__2`, the first will contain
|
||||
the first 127 bytes and the second will contain the remaining 3 bytes. On
|
||||
your crash reporting backend you should stitch together keys in this format.
|
||||
|
||||
### `crashReporter.removeExtraParameter(key)`
|
||||
|
||||
* `key` String - Parameter key, must be no longer than 39 bytes.
|
||||
|
||||
Remove an extra parameter from the current set of parameters. Future crashes
|
||||
will not include this parameter.
|
||||
|
||||
### `crashReporter.getParameters()`
|
||||
|
||||
Returns `Record<String, String>` - The current 'extra' parameters of the crash reporter.
|
||||
|
||||
## Crash Report Payload
|
||||
|
||||
The crash reporter will send the following data to the `submitURL` as
|
||||
a `multipart/form-data` `POST`:
|
||||
|
||||
* `ver` String - The version of Electron.
|
||||
* `platform` String - e.g. 'win32'.
|
||||
* `process_type` String - e.g. 'renderer'.
|
||||
* `guid` String - e.g. '5e1286fc-da97-479e-918b-6bfb0c3d1c72'.
|
||||
* `_version` String - The version in `package.json`.
|
||||
* `_productName` String - The product name in the `crashReporter` `options`
|
||||
object.
|
||||
* `prod` String - Name of the underlying product. In this case Electron.
|
||||
* `_companyName` String - The company name in the `crashReporter` `options`
|
||||
object.
|
||||
* `upload_file_minidump` File - The crash report in the format of `minidump`.
|
||||
* All level one properties of the `extra` object in the `crashReporter`
|
||||
`options` object.
|
|
@ -0,0 +1,102 @@
|
|||
---
|
||||
title: "Class: Debugger"
|
||||
description: "An alternate transport for Chrome's remote debugging protocol."
|
||||
slug: debugger
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
## Class: Debugger
|
||||
|
||||
> An alternate transport for Chrome's remote debugging protocol.
|
||||
|
||||
Process: [Main](latest/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._
|
||||
|
||||
Chrome Developer Tools has a [special binding][rdp] available at JavaScript
|
||||
runtime that allows interacting with pages and instrumenting them.
|
||||
|
||||
```javascript
|
||||
const { BrowserWindow } = require('electron')
|
||||
const win = new BrowserWindow()
|
||||
|
||||
try {
|
||||
win.webContents.debugger.attach('1.1')
|
||||
} catch (err) {
|
||||
console.log('Debugger attach failed : ', err)
|
||||
}
|
||||
|
||||
win.webContents.debugger.on('detach', (event, reason) => {
|
||||
console.log('Debugger detached due to : ', reason)
|
||||
})
|
||||
|
||||
win.webContents.debugger.on('message', (event, method, params) => {
|
||||
if (method === 'Network.requestWillBeSent') {
|
||||
if (params.request.url === 'https://www.github.com') {
|
||||
win.webContents.debugger.detach()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
win.webContents.debugger.sendCommand('Network.enable')
|
||||
```
|
||||
|
||||
### Instance Events
|
||||
|
||||
#### Event: 'detach'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `reason` String - Reason for detaching debugger.
|
||||
|
||||
Emitted when the debugging session is terminated. This happens either when
|
||||
`webContents` is closed or devtools is invoked for the attached `webContents`.
|
||||
|
||||
#### Event: 'message'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `method` String - Method name.
|
||||
* `params` any - Event parameters defined by the 'parameters'
|
||||
attribute in the remote debugging protocol.
|
||||
* `sessionId` String - Unique identifier of attached debugging session,
|
||||
will match the value sent from `debugger.sendCommand`.
|
||||
|
||||
Emitted whenever the debugging target issues an instrumentation event.
|
||||
|
||||
[rdp]: https://chromedevtools.github.io/devtools-protocol/
|
||||
[`webContents.findInPage`]: latest/api/web-contents.md#contentsfindinpagetext-options
|
||||
|
||||
### Instance Methods
|
||||
|
||||
#### `debugger.attach([protocolVersion])`
|
||||
|
||||
* `protocolVersion` String (optional) - Requested debugging protocol version.
|
||||
|
||||
Attaches the debugger to the `webContents`.
|
||||
|
||||
#### `debugger.isAttached()`
|
||||
|
||||
Returns `Boolean` - Whether a debugger is attached to the `webContents`.
|
||||
|
||||
#### `debugger.detach()`
|
||||
|
||||
Detaches the debugger from the `webContents`.
|
||||
|
||||
#### `debugger.sendCommand(method[, commandParams, sessionId])`
|
||||
|
||||
* `method` String - Method name, should be one of the methods defined by the
|
||||
[remote debugging protocol][rdp].
|
||||
* `commandParams` any (optional) - JSON object with request parameters.
|
||||
* `sessionId` String (optional) - send command to the target with associated
|
||||
debugging session id. The initial value can be obtained by sending
|
||||
[Target.attachToTarget][attachToTarget] message.
|
||||
|
||||
[attachToTarget]: https://chromedevtools.github.io/devtools-protocol/tot/Target/#method-attachToTarget
|
||||
|
||||
Returns `Promise<any>` - A promise that resolves with the response defined by
|
||||
the 'returns' attribute of the command description in the remote debugging protocol
|
||||
or is rejected indicating the failure of the command.
|
||||
|
||||
Send given command to the debugging target.
|
|
@ -0,0 +1,111 @@
|
|||
---
|
||||
title: "desktopCapturer"
|
||||
description: "Access information about media sources that can be used to capture audio and video from the desktop using the navigator.mediaDevices.getUserMedia API."
|
||||
slug: desktop-capturer
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# desktopCapturer
|
||||
|
||||
> Access information about media sources that can be used to capture audio and
|
||||
> video from the desktop using the [`navigator.mediaDevices.getUserMedia`] API.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process), [Renderer](latest/glossary.md#renderer-process)
|
||||
|
||||
The following example shows how to capture video from a desktop window whose
|
||||
title is `Electron`:
|
||||
|
||||
```javascript
|
||||
// In the renderer process.
|
||||
const { desktopCapturer } = require('electron')
|
||||
|
||||
desktopCapturer.getSources({ types: ['window', 'screen'] }).then(async sources => {
|
||||
for (const source of sources) {
|
||||
if (source.name === 'Electron') {
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: false,
|
||||
video: {
|
||||
mandatory: {
|
||||
chromeMediaSource: 'desktop',
|
||||
chromeMediaSourceId: source.id,
|
||||
minWidth: 1280,
|
||||
maxWidth: 1280,
|
||||
minHeight: 720,
|
||||
maxHeight: 720
|
||||
}
|
||||
}
|
||||
})
|
||||
handleStream(stream)
|
||||
} catch (e) {
|
||||
handleError(e)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
function handleStream (stream) {
|
||||
const video = document.querySelector('video')
|
||||
video.srcObject = stream
|
||||
video.onloadedmetadata = (e) => video.play()
|
||||
}
|
||||
|
||||
function handleError (e) {
|
||||
console.log(e)
|
||||
}
|
||||
```
|
||||
|
||||
To capture video from a source provided by `desktopCapturer` the constraints
|
||||
passed to [`navigator.mediaDevices.getUserMedia`] must include
|
||||
`chromeMediaSource: 'desktop'`, and `audio: false`.
|
||||
|
||||
To capture both audio and video from the entire desktop the constraints passed
|
||||
to [`navigator.mediaDevices.getUserMedia`] must include `chromeMediaSource: 'desktop'`,
|
||||
for both `audio` and `video`, but should not include a `chromeMediaSourceId` constraint.
|
||||
|
||||
```javascript
|
||||
const constraints = {
|
||||
audio: {
|
||||
mandatory: {
|
||||
chromeMediaSource: 'desktop'
|
||||
}
|
||||
},
|
||||
video: {
|
||||
mandatory: {
|
||||
chromeMediaSource: 'desktop'
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
The `desktopCapturer` module has the following methods:
|
||||
|
||||
### `desktopCapturer.getSources(options)`
|
||||
|
||||
* `options` Object
|
||||
* `types` String[] - An array of Strings that lists the types of desktop sources
|
||||
to be captured, available types are `screen` and `window`.
|
||||
* `thumbnailSize` [Size](latest/api/structures/size.md) (optional) - The size that the media source thumbnail
|
||||
should be scaled to. Default is `150` x `150`. Set width or height to 0 when you do not need
|
||||
the thumbnails. This will save the processing time required for capturing the content of each
|
||||
window and screen.
|
||||
* `fetchWindowIcons` Boolean (optional) - Set to true to enable fetching window icons. The default
|
||||
value is false. When false the appIcon property of the sources return null. Same if a source has
|
||||
the type screen.
|
||||
|
||||
Returns `Promise<DesktopCapturerSource[]>` - Resolves with an array of [`DesktopCapturerSource`](latest/api/structures/desktop-capturer-source.md) objects, each `DesktopCapturerSource` represents a screen or an individual window that can be captured.
|
||||
|
||||
**Note** Capturing the screen contents requires user consent on macOS 10.15 Catalina or higher,
|
||||
which can detected by [`systemPreferences.getMediaAccessStatus`].
|
||||
|
||||
[`navigator.mediaDevices.getUserMedia`]: https://developer.mozilla.org/en/docs/Web/API/MediaDevices/getUserMedia
|
||||
[`systemPreferences.getMediaAccessStatus`]: latest/api/system-preferences.md#systempreferencesgetmediaaccessstatusmediatype-windows-macos
|
||||
|
||||
## Caveats
|
||||
|
||||
`navigator.mediaDevices.getUserMedia` does not work on macOS for audio capture due to a fundamental limitation whereby apps that want to access the system's audio require a [signed kernel extension](https://developer.apple.com/library/archive/documentation/Security/Conceptual/System_Integrity_Protection_Guide/KernelExtensions/KernelExtensions.html). Chromium, and by extension Electron, does not provide this.
|
||||
|
||||
It is possible to circumvent this limitation by capturing system audio with another macOS app like Soundflower and passing it through a virtual audio input device. This virtual device can then be queried with `navigator.mediaDevices.getUserMedia`.
|
|
@ -0,0 +1,378 @@
|
|||
---
|
||||
title: "dialog"
|
||||
description: "Display native system dialogs for opening and saving files, alerting, etc."
|
||||
slug: dialog
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# dialog
|
||||
|
||||
> Display native system dialogs for opening and saving files, alerting, etc.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
An example of showing a dialog to select multiple files:
|
||||
|
||||
```javascript
|
||||
const { dialog } = require('electron')
|
||||
console.log(dialog.showOpenDialog({ properties: ['openFile', 'multiSelections'] }))
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
The `dialog` module has the following methods:
|
||||
|
||||
### `dialog.showOpenDialogSync([browserWindow, ]options)`
|
||||
|
||||
* `browserWindow` [BrowserWindow](latest/api/browser-window.md) (optional)
|
||||
* `options` Object
|
||||
* `title` String (optional)
|
||||
* `defaultPath` String (optional)
|
||||
* `buttonLabel` String (optional) - Custom label for the confirmation button, when
|
||||
left empty the default label will be used.
|
||||
* `filters` [FileFilter[]](latest/api/structures/file-filter.md) (optional)
|
||||
* `properties` String[] (optional) - Contains which features the dialog should
|
||||
use. The following values are supported:
|
||||
* `openFile` - Allow files to be selected.
|
||||
* `openDirectory` - Allow directories to be selected.
|
||||
* `multiSelections` - Allow multiple paths to be selected.
|
||||
* `showHiddenFiles` - Show hidden files in dialog.
|
||||
* `createDirectory` _macOS_ - Allow creating new directories from dialog.
|
||||
* `promptToCreate` _Windows_ - Prompt for creation if the file path entered
|
||||
in the dialog does not exist. This does not actually create the file at
|
||||
the path but allows non-existent paths to be returned that should be
|
||||
created by the application.
|
||||
* `noResolveAliases` _macOS_ - Disable the automatic alias (symlink) path
|
||||
resolution. Selected aliases will now return the alias path instead of
|
||||
their target path.
|
||||
* `treatPackageAsDirectory` _macOS_ - Treat packages, such as `.app` folders,
|
||||
as a directory instead of a file.
|
||||
* `dontAddToRecent` _Windows_ - Do not add the item being opened to the recent documents list.
|
||||
* `message` String (optional) _macOS_ - Message to display above input
|
||||
boxes.
|
||||
* `securityScopedBookmarks` Boolean (optional) _macOS_ _mas_ - Create [security scoped bookmarks](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) when packaged for the Mac App Store.
|
||||
|
||||
Returns `String[] | undefined`, the file paths chosen by the user; if the dialog is cancelled it returns `undefined`.
|
||||
|
||||
The `browserWindow` argument allows the dialog to attach itself to a parent window, making it modal.
|
||||
|
||||
The `filters` specifies an array of file types that can be displayed or
|
||||
selected when you want to limit the user to a specific type. For example:
|
||||
|
||||
```javascript
|
||||
{
|
||||
filters: [
|
||||
{ name: 'Images', extensions: ['jpg', 'png', 'gif'] },
|
||||
{ name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
|
||||
{ name: 'Custom File Type', extensions: ['as'] },
|
||||
{ name: 'All Files', extensions: ['*'] }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The `extensions` array should contain extensions without wildcards or dots (e.g.
|
||||
`'png'` is good but `'.png'` and `'*.png'` are bad). To show all files, use the
|
||||
`'*'` wildcard (no other wildcard is supported).
|
||||
|
||||
**Note:** On Windows and Linux an open dialog can not be both a file selector
|
||||
and a directory selector, so if you set `properties` to
|
||||
`['openFile', 'openDirectory']` on these platforms, a directory selector will be
|
||||
shown.
|
||||
|
||||
```js
|
||||
dialog.showOpenDialogSync(mainWindow, {
|
||||
properties: ['openFile', 'openDirectory']
|
||||
})
|
||||
```
|
||||
|
||||
### `dialog.showOpenDialog([browserWindow, ]options)`
|
||||
|
||||
* `browserWindow` [BrowserWindow](latest/api/browser-window.md) (optional)
|
||||
* `options` Object
|
||||
* `title` String (optional)
|
||||
* `defaultPath` String (optional)
|
||||
* `buttonLabel` String (optional) - Custom label for the confirmation button, when
|
||||
left empty the default label will be used.
|
||||
* `filters` [FileFilter[]](latest/api/structures/file-filter.md) (optional)
|
||||
* `properties` String[] (optional) - Contains which features the dialog should
|
||||
use. The following values are supported:
|
||||
* `openFile` - Allow files to be selected.
|
||||
* `openDirectory` - Allow directories to be selected.
|
||||
* `multiSelections` - Allow multiple paths to be selected.
|
||||
* `showHiddenFiles` - Show hidden files in dialog.
|
||||
* `createDirectory` _macOS_ - Allow creating new directories from dialog.
|
||||
* `promptToCreate` _Windows_ - Prompt for creation if the file path entered
|
||||
in the dialog does not exist. This does not actually create the file at
|
||||
the path but allows non-existent paths to be returned that should be
|
||||
created by the application.
|
||||
* `noResolveAliases` _macOS_ - Disable the automatic alias (symlink) path
|
||||
resolution. Selected aliases will now return the alias path instead of
|
||||
their target path.
|
||||
* `treatPackageAsDirectory` _macOS_ - Treat packages, such as `.app` folders,
|
||||
as a directory instead of a file.
|
||||
* `dontAddToRecent` _Windows_ - Do not add the item being opened to the recent documents list.
|
||||
* `message` String (optional) _macOS_ - Message to display above input
|
||||
boxes.
|
||||
* `securityScopedBookmarks` Boolean (optional) _macOS_ _mas_ - Create [security scoped bookmarks](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) when packaged for the Mac App Store.
|
||||
|
||||
Returns `Promise<Object>` - Resolve with an object containing the following:
|
||||
|
||||
* `canceled` Boolean - whether or not the dialog was canceled.
|
||||
* `filePaths` String[] - An array of file paths chosen by the user. If the dialog is cancelled this will be an empty array.
|
||||
* `bookmarks` String[] (optional) _macOS_ _mas_ - An array matching the `filePaths` array of base64 encoded strings which contains security scoped bookmark data. `securityScopedBookmarks` must be enabled for this to be populated. (For return values, see [table here](#bookmarks-array).)
|
||||
|
||||
The `browserWindow` argument allows the dialog to attach itself to a parent window, making it modal.
|
||||
|
||||
The `filters` specifies an array of file types that can be displayed or
|
||||
selected when you want to limit the user to a specific type. For example:
|
||||
|
||||
```javascript
|
||||
{
|
||||
filters: [
|
||||
{ name: 'Images', extensions: ['jpg', 'png', 'gif'] },
|
||||
{ name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
|
||||
{ name: 'Custom File Type', extensions: ['as'] },
|
||||
{ name: 'All Files', extensions: ['*'] }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The `extensions` array should contain extensions without wildcards or dots (e.g.
|
||||
`'png'` is good but `'.png'` and `'*.png'` are bad). To show all files, use the
|
||||
`'*'` wildcard (no other wildcard is supported).
|
||||
|
||||
**Note:** On Windows and Linux an open dialog can not be both a file selector
|
||||
and a directory selector, so if you set `properties` to
|
||||
`['openFile', 'openDirectory']` on these platforms, a directory selector will be
|
||||
shown.
|
||||
|
||||
```js
|
||||
dialog.showOpenDialog(mainWindow, {
|
||||
properties: ['openFile', 'openDirectory']
|
||||
}).then(result => {
|
||||
console.log(result.canceled)
|
||||
console.log(result.filePaths)
|
||||
}).catch(err => {
|
||||
console.log(err)
|
||||
})
|
||||
```
|
||||
|
||||
### `dialog.showSaveDialogSync([browserWindow, ]options)`
|
||||
|
||||
* `browserWindow` [BrowserWindow](latest/api/browser-window.md) (optional)
|
||||
* `options` Object
|
||||
* `title` String (optional) - The dialog title. Cannot be displayed on some _Linux_ desktop environments.
|
||||
* `defaultPath` String (optional) - Absolute directory path, absolute file
|
||||
path, or file name to use by default.
|
||||
* `buttonLabel` String (optional) - Custom label for the confirmation button, when
|
||||
left empty the default label will be used.
|
||||
* `filters` [FileFilter[]](latest/api/structures/file-filter.md) (optional)
|
||||
* `message` String (optional) _macOS_ - Message to display above text fields.
|
||||
* `nameFieldLabel` String (optional) _macOS_ - Custom label for the text
|
||||
displayed in front of the filename text field.
|
||||
* `showsTagField` Boolean (optional) _macOS_ - Show the tags input box,
|
||||
defaults to `true`.
|
||||
* `properties` String[] (optional)
|
||||
* `showHiddenFiles` - Show hidden files in dialog.
|
||||
* `createDirectory` _macOS_ - Allow creating new directories from dialog.
|
||||
* `treatPackageAsDirectory` _macOS_ - Treat packages, such as `.app` folders,
|
||||
as a directory instead of a file.
|
||||
* `showOverwriteConfirmation` _Linux_ - Sets whether the user will be presented a confirmation dialog if the user types a file name that already exists.
|
||||
* `dontAddToRecent` _Windows_ - Do not add the item being saved to the recent documents list.
|
||||
* `securityScopedBookmarks` Boolean (optional) _macOS_ _mas_ - Create a [security scoped bookmark](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) when packaged for the Mac App Store. If this option is enabled and the file doesn't already exist a blank file will be created at the chosen path.
|
||||
|
||||
Returns `String | undefined`, the path of the file chosen by the user; if the dialog is cancelled it returns `undefined`.
|
||||
|
||||
The `browserWindow` argument allows the dialog to attach itself to a parent window, making it modal.
|
||||
|
||||
The `filters` specifies an array of file types that can be displayed, see
|
||||
`dialog.showOpenDialog` for an example.
|
||||
|
||||
### `dialog.showSaveDialog([browserWindow, ]options)`
|
||||
|
||||
* `browserWindow` [BrowserWindow](latest/api/browser-window.md) (optional)
|
||||
* `options` Object
|
||||
* `title` String (optional) - The dialog title. Cannot be displayed on some _Linux_ desktop environments.
|
||||
* `defaultPath` String (optional) - Absolute directory path, absolute file
|
||||
path, or file name to use by default.
|
||||
* `buttonLabel` String (optional) - Custom label for the confirmation button, when
|
||||
left empty the default label will be used.
|
||||
* `filters` [FileFilter[]](latest/api/structures/file-filter.md) (optional)
|
||||
* `message` String (optional) _macOS_ - Message to display above text fields.
|
||||
* `nameFieldLabel` String (optional) _macOS_ - Custom label for the text
|
||||
displayed in front of the filename text field.
|
||||
* `showsTagField` Boolean (optional) _macOS_ - Show the tags input box, defaults to `true`.
|
||||
* `properties` String[] (optional)
|
||||
* `showHiddenFiles` - Show hidden files in dialog.
|
||||
* `createDirectory` _macOS_ - Allow creating new directories from dialog.
|
||||
* `treatPackageAsDirectory` _macOS_ - Treat packages, such as `.app` folders,
|
||||
as a directory instead of a file.
|
||||
* `showOverwriteConfirmation` _Linux_ - Sets whether the user will be presented a confirmation dialog if the user types a file name that already exists.
|
||||
* `dontAddToRecent` _Windows_ - Do not add the item being saved to the recent documents list.
|
||||
* `securityScopedBookmarks` Boolean (optional) _macOS_ _mas_ - Create a [security scoped bookmark](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) when packaged for the Mac App Store. If this option is enabled and the file doesn't already exist a blank file will be created at the chosen path.
|
||||
|
||||
Returns `Promise<Object>` - Resolve with an object containing the following:
|
||||
|
||||
* `canceled` Boolean - whether or not the dialog was canceled.
|
||||
* `filePath` String (optional) - If the dialog is canceled, this will be `undefined`.
|
||||
* `bookmark` String (optional) _macOS_ _mas_ - Base64 encoded string which contains the security scoped bookmark data for the saved file. `securityScopedBookmarks` must be enabled for this to be present. (For return values, see [table here](#bookmarks-array).)
|
||||
|
||||
The `browserWindow` argument allows the dialog to attach itself to a parent window, making it modal.
|
||||
|
||||
The `filters` specifies an array of file types that can be displayed, see
|
||||
`dialog.showOpenDialog` for an example.
|
||||
|
||||
**Note:** On macOS, using the asynchronous version is recommended to avoid issues when
|
||||
expanding and collapsing the dialog.
|
||||
|
||||
### `dialog.showMessageBoxSync([browserWindow, ]options)`
|
||||
|
||||
* `browserWindow` [BrowserWindow](latest/api/browser-window.md) (optional)
|
||||
* `options` Object
|
||||
* `message` String - Content of the message box.
|
||||
* `type` String (optional) - Can be `"none"`, `"info"`, `"error"`, `"question"` or
|
||||
`"warning"`. On Windows, `"question"` displays the same icon as `"info"`, unless
|
||||
you set an icon using the `"icon"` option. On macOS, both `"warning"` and
|
||||
`"error"` display the same warning icon.
|
||||
* `buttons` String[] (optional) - Array of texts for buttons. On Windows, an empty array
|
||||
will result in one button labeled "OK".
|
||||
* `defaultId` Integer (optional) - Index of the button in the buttons array which will
|
||||
be selected by default when the message box opens.
|
||||
* `title` String (optional) - Title of the message box, some platforms will not show it.
|
||||
* `detail` String (optional) - Extra information of the message.
|
||||
* `icon` ([NativeImage](latest/api/native-image.md) | String) (optional)
|
||||
* `textWidth` Integer (optional) _macOS_ - Custom width of the text in the message box.
|
||||
* `cancelId` Integer (optional) - The index of the button to be used to cancel the dialog, via
|
||||
the `Esc` key. By default this is assigned to the first button with "cancel" or "no" as the
|
||||
label. If no such labeled buttons exist and this option is not set, `0` will be used as the
|
||||
return value.
|
||||
* `noLink` Boolean (optional) - On Windows Electron will try to figure out which one of
|
||||
the `buttons` are common buttons (like "Cancel" or "Yes"), and show the
|
||||
others as command links in the dialog. This can make the dialog appear in
|
||||
the style of modern Windows apps. If you don't like this behavior, you can
|
||||
set `noLink` to `true`.
|
||||
* `normalizeAccessKeys` Boolean (optional) - Normalize the keyboard access keys
|
||||
across platforms. Default is `false`. Enabling this assumes `&` is used in
|
||||
the button labels for the placement of the keyboard shortcut access key
|
||||
and labels will be converted so they work correctly on each platform, `&`
|
||||
characters are removed on macOS, converted to `_` on Linux, and left
|
||||
untouched on Windows. For example, a button label of `Vie&w` will be
|
||||
converted to `Vie_w` on Linux and `View` on macOS and can be selected
|
||||
via `Alt-W` on Windows and Linux.
|
||||
|
||||
Returns `Integer` - the index of the clicked button.
|
||||
|
||||
Shows a message box, it will block the process until the message box is closed.
|
||||
It returns the index of the clicked button.
|
||||
|
||||
The `browserWindow` argument allows the dialog to attach itself to a parent window, making it modal.
|
||||
If `browserWindow` is not shown dialog will not be attached to it. In such case it will be displayed as an independent window.
|
||||
|
||||
### `dialog.showMessageBox([browserWindow, ]options)`
|
||||
|
||||
* `browserWindow` [BrowserWindow](latest/api/browser-window.md) (optional)
|
||||
* `options` Object
|
||||
* `message` String - Content of the message box.
|
||||
* `type` String (optional) - Can be `"none"`, `"info"`, `"error"`, `"question"` or
|
||||
`"warning"`. On Windows, `"question"` displays the same icon as `"info"`, unless
|
||||
you set an icon using the `"icon"` option. On macOS, both `"warning"` and
|
||||
`"error"` display the same warning icon.
|
||||
* `buttons` String[] (optional) - Array of texts for buttons. On Windows, an empty array
|
||||
will result in one button labeled "OK".
|
||||
* `defaultId` Integer (optional) - Index of the button in the buttons array which will
|
||||
be selected by default when the message box opens.
|
||||
* `signal` AbortSignal (optional) - Pass an instance of [AbortSignal][] to
|
||||
optionally close the message box, the message box will behave as if it was
|
||||
cancelled by the user. On macOS, `signal` does not work with message boxes
|
||||
that do not have a parent window, since those message boxes run
|
||||
synchronously due to platform limitations.
|
||||
* `title` String (optional) - Title of the message box, some platforms will not show it.
|
||||
* `detail` String (optional) - Extra information of the message.
|
||||
* `checkboxLabel` String (optional) - If provided, the message box will
|
||||
include a checkbox with the given label.
|
||||
* `checkboxChecked` Boolean (optional) - Initial checked state of the
|
||||
checkbox. `false` by default.
|
||||
* `icon` [NativeImage](latest/api/native-image.md) (optional)
|
||||
* `textWidth` Integer (optional) _macOS_ - Custom width of the text in the message box.
|
||||
* `cancelId` Integer (optional) - The index of the button to be used to cancel the dialog, via
|
||||
the `Esc` key. By default this is assigned to the first button with "cancel" or "no" as the
|
||||
label. If no such labeled buttons exist and this option is not set, `0` will be used as the
|
||||
return value.
|
||||
* `noLink` Boolean (optional) - On Windows Electron will try to figure out which one of
|
||||
the `buttons` are common buttons (like "Cancel" or "Yes"), and show the
|
||||
others as command links in the dialog. This can make the dialog appear in
|
||||
the style of modern Windows apps. If you don't like this behavior, you can
|
||||
set `noLink` to `true`.
|
||||
* `normalizeAccessKeys` Boolean (optional) - Normalize the keyboard access keys
|
||||
across platforms. Default is `false`. Enabling this assumes `&` is used in
|
||||
the button labels for the placement of the keyboard shortcut access key
|
||||
and labels will be converted so they work correctly on each platform, `&`
|
||||
characters are removed on macOS, converted to `_` on Linux, and left
|
||||
untouched on Windows. For example, a button label of `Vie&w` will be
|
||||
converted to `Vie_w` on Linux and `View` on macOS and can be selected
|
||||
via `Alt-W` on Windows and Linux.
|
||||
|
||||
Returns `Promise<Object>` - resolves with a promise containing the following properties:
|
||||
|
||||
* `response` Number - The index of the clicked button.
|
||||
* `checkboxChecked` Boolean - The checked state of the checkbox if
|
||||
`checkboxLabel` was set. Otherwise `false`.
|
||||
|
||||
Shows a message box.
|
||||
|
||||
The `browserWindow` argument allows the dialog to attach itself to a parent window, making it modal.
|
||||
|
||||
### `dialog.showErrorBox(title, content)`
|
||||
|
||||
* `title` String - The title to display in the error box.
|
||||
* `content` String - The text content to display in the error box.
|
||||
|
||||
Displays a modal dialog that shows an error message.
|
||||
|
||||
This API can be called safely before the `ready` event the `app` module emits,
|
||||
it is usually used to report errors in early stage of startup. If called
|
||||
before the app `ready`event on Linux, the message will be emitted to stderr,
|
||||
and no GUI dialog will appear.
|
||||
|
||||
### `dialog.showCertificateTrustDialog([browserWindow, ]options)` _macOS_ _Windows_
|
||||
|
||||
* `browserWindow` [BrowserWindow](latest/api/browser-window.md) (optional)
|
||||
* `options` Object
|
||||
* `certificate` [Certificate](latest/api/structures/certificate.md) - The certificate to trust/import.
|
||||
* `message` String - The message to display to the user.
|
||||
|
||||
Returns `Promise<void>` - resolves when the certificate trust dialog is shown.
|
||||
|
||||
On macOS, this displays a modal dialog that shows a message and certificate
|
||||
information, and gives the user the option of trusting/importing the
|
||||
certificate. If you provide a `browserWindow` argument the dialog will be
|
||||
attached to the parent window, making it modal.
|
||||
|
||||
On Windows the options are more limited, due to the Win32 APIs used:
|
||||
|
||||
* The `message` argument is not used, as the OS provides its own confirmation
|
||||
dialog.
|
||||
* The `browserWindow` argument is ignored since it is not possible to make
|
||||
this confirmation dialog modal.
|
||||
|
||||
## Bookmarks array
|
||||
|
||||
`showOpenDialog`, `showOpenDialogSync`, `showSaveDialog`, and `showSaveDialogSync` will return a `bookmarks` array.
|
||||
|
||||
| Build Type | securityScopedBookmarks boolean | Return Type | Return Value |
|
||||
|------------|---------------------------------|:-----------:|--------------------------------|
|
||||
| macOS mas | True | Success | `['LONGBOOKMARKSTRING']` |
|
||||
| macOS mas | True | Error | `['']` (array of empty string) |
|
||||
| macOS mas | False | NA | `[]` (empty array) |
|
||||
| non mas | any | NA | `[]` (empty array) |
|
||||
|
||||
## Sheets
|
||||
|
||||
On macOS, dialogs are presented as sheets attached to a window if you provide
|
||||
a [`BrowserWindow`](latest/api/browser-window.md) reference in the `browserWindow` parameter, or modals if no
|
||||
window is provided.
|
||||
|
||||
You can call `BrowserWindow.getCurrentWindow().setSheetOffset(offset)` to change
|
||||
the offset from the window frame where sheets are attached.
|
||||
|
||||
[AbortSignal]: https://nodejs.org/api/globals.html#globals_class_abortsignal
|
|
@ -0,0 +1,88 @@
|
|||
---
|
||||
title: "Class: Dock"
|
||||
description: "Control your app in the macOS dock"
|
||||
slug: dock
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
## Class: Dock
|
||||
|
||||
> Control your app in the macOS dock
|
||||
|
||||
Process: [Main](latest/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._
|
||||
|
||||
The following example shows how to bounce your icon on the dock.
|
||||
|
||||
```javascript
|
||||
const { app } = require('electron')
|
||||
app.dock.bounce()
|
||||
```
|
||||
|
||||
### Instance Methods
|
||||
|
||||
#### `dock.bounce([type])` _macOS_
|
||||
|
||||
* `type` String (optional) - Can be `critical` or `informational`. The default is
|
||||
`informational`
|
||||
|
||||
Returns `Integer` - an ID representing the request.
|
||||
|
||||
When `critical` is passed, the dock icon will bounce until either the
|
||||
application becomes active or the request is canceled.
|
||||
|
||||
When `informational` is passed, the dock icon will bounce for one second.
|
||||
However, the request remains active until either the application becomes active
|
||||
or the request is canceled.
|
||||
|
||||
**Nota Bene:** This method can only be used while the app is not focused; when the app is focused it will return -1.
|
||||
|
||||
#### `dock.cancelBounce(id)` _macOS_
|
||||
|
||||
* `id` Integer
|
||||
|
||||
Cancel the bounce of `id`.
|
||||
|
||||
#### `dock.downloadFinished(filePath)` _macOS_
|
||||
|
||||
* `filePath` String
|
||||
|
||||
Bounces the Downloads stack if the filePath is inside the Downloads folder.
|
||||
|
||||
#### `dock.setBadge(text)` _macOS_
|
||||
|
||||
* `text` String
|
||||
|
||||
Sets the string to be displayed in the dock’s badging area.
|
||||
|
||||
#### `dock.getBadge()` _macOS_
|
||||
|
||||
Returns `String` - The badge string of the dock.
|
||||
|
||||
#### `dock.hide()` _macOS_
|
||||
|
||||
Hides the dock icon.
|
||||
|
||||
#### `dock.show()` _macOS_
|
||||
|
||||
Returns `Promise<void>` - Resolves when the dock icon is shown.
|
||||
|
||||
#### `dock.isVisible()` _macOS_
|
||||
|
||||
Returns `Boolean` - Whether the dock icon is visible.
|
||||
|
||||
#### `dock.setMenu(menu)` _macOS_
|
||||
|
||||
* `menu` [Menu](latest/api/menu.md)
|
||||
|
||||
Sets the application's [dock menu][dock-menu].
|
||||
|
||||
#### `dock.getMenu()` _macOS_
|
||||
|
||||
Returns `Menu | null` - The application's [dock menu][dock-menu].
|
||||
|
||||
#### `dock.setIcon(image)` _macOS_
|
||||
|
||||
* `image` ([NativeImage](latest/api/native-image.md) | String)
|
||||
|
||||
Sets the `image` associated with this dock icon.
|
|
@ -0,0 +1,204 @@
|
|||
---
|
||||
title: "Class: DownloadItem"
|
||||
description: "Control file downloads from remote sources."
|
||||
slug: download-item
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
## Class: DownloadItem
|
||||
|
||||
> Control file downloads from remote sources.
|
||||
|
||||
Process: [Main](latest/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._
|
||||
|
||||
`DownloadItem` is an [EventEmitter][event-emitter] that represents a download item in Electron.
|
||||
It is used in `will-download` event of `Session` class, and allows users to
|
||||
control the download item.
|
||||
|
||||
```javascript
|
||||
// In the main process.
|
||||
const { BrowserWindow } = require('electron')
|
||||
const win = new BrowserWindow()
|
||||
win.webContents.session.on('will-download', (event, item, webContents) => {
|
||||
// Set the save path, making Electron not to prompt a save dialog.
|
||||
item.setSavePath('/tmp/save.pdf')
|
||||
|
||||
item.on('updated', (event, state) => {
|
||||
if (state === 'interrupted') {
|
||||
console.log('Download is interrupted but can be resumed')
|
||||
} else if (state === 'progressing') {
|
||||
if (item.isPaused()) {
|
||||
console.log('Download is paused')
|
||||
} else {
|
||||
console.log(`Received bytes: ${item.getReceivedBytes()}`)
|
||||
}
|
||||
}
|
||||
})
|
||||
item.once('done', (event, state) => {
|
||||
if (state === 'completed') {
|
||||
console.log('Download successfully')
|
||||
} else {
|
||||
console.log(`Download failed: ${state}`)
|
||||
}
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
### Instance Events
|
||||
|
||||
#### Event: 'updated'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `state` String - Can be `progressing` or `interrupted`.
|
||||
|
||||
Emitted when the download has been updated and is not done.
|
||||
|
||||
The `state` can be one of following:
|
||||
|
||||
* `progressing` - The download is in-progress.
|
||||
* `interrupted` - The download has interrupted and can be resumed.
|
||||
|
||||
#### Event: 'done'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `state` String - Can be `completed`, `cancelled` or `interrupted`.
|
||||
|
||||
Emitted when the download is in a terminal state. This includes a completed
|
||||
download, a cancelled download (via `downloadItem.cancel()`), and interrupted
|
||||
download that can't be resumed.
|
||||
|
||||
The `state` can be one of following:
|
||||
|
||||
* `completed` - The download completed successfully.
|
||||
* `cancelled` - The download has been cancelled.
|
||||
* `interrupted` - The download has interrupted and can not resume.
|
||||
|
||||
### Instance Methods
|
||||
|
||||
The `downloadItem` object has the following methods:
|
||||
|
||||
#### `downloadItem.setSavePath(path)`
|
||||
|
||||
* `path` String - Set the save file path of the download item.
|
||||
|
||||
The API is only available in session's `will-download` callback function.
|
||||
If `path` doesn't exist, Electron will try to make the directory recursively.
|
||||
If user doesn't set the save path via the API, Electron will use the original
|
||||
routine to determine the save path; this usually prompts a save dialog.
|
||||
|
||||
#### `downloadItem.getSavePath()`
|
||||
|
||||
Returns `String` - The save path of the download item. This will be either the path
|
||||
set via `downloadItem.setSavePath(path)` or the path selected from the shown
|
||||
save dialog.
|
||||
|
||||
#### `downloadItem.setSaveDialogOptions(options)`
|
||||
|
||||
* `options` SaveDialogOptions - Set the save file dialog options. This object has the same
|
||||
properties as the `options` parameter of [`dialog.showSaveDialog()`](latest/api/dialog.md).
|
||||
|
||||
This API allows the user to set custom options for the save dialog that opens
|
||||
for the download item by default.
|
||||
The API is only available in session's `will-download` callback function.
|
||||
|
||||
#### `downloadItem.getSaveDialogOptions()`
|
||||
|
||||
Returns `SaveDialogOptions` - Returns the object previously set by `downloadItem.setSaveDialogOptions(options)`.
|
||||
|
||||
#### `downloadItem.pause()`
|
||||
|
||||
Pauses the download.
|
||||
|
||||
#### `downloadItem.isPaused()`
|
||||
|
||||
Returns `Boolean` - Whether the download is paused.
|
||||
|
||||
#### `downloadItem.resume()`
|
||||
|
||||
Resumes the download that has been paused.
|
||||
|
||||
**Note:** To enable resumable downloads the server you are downloading from must support range requests and provide both `Last-Modified` and `ETag` header values. Otherwise `resume()` will dismiss previously received bytes and restart the download from the beginning.
|
||||
|
||||
#### `downloadItem.canResume()`
|
||||
|
||||
Returns `Boolean` - Whether the download can resume.
|
||||
|
||||
#### `downloadItem.cancel()`
|
||||
|
||||
Cancels the download operation.
|
||||
|
||||
#### `downloadItem.getURL()`
|
||||
|
||||
Returns `String` - The origin URL where the item is downloaded from.
|
||||
|
||||
#### `downloadItem.getMimeType()`
|
||||
|
||||
Returns `String` - The files mime type.
|
||||
|
||||
#### `downloadItem.hasUserGesture()`
|
||||
|
||||
Returns `Boolean` - Whether the download has user gesture.
|
||||
|
||||
#### `downloadItem.getFilename()`
|
||||
|
||||
Returns `String` - The file name of the download item.
|
||||
|
||||
**Note:** The file name is not always the same as the actual one saved in local
|
||||
disk. If user changes the file name in a prompted download saving dialog, the
|
||||
actual name of saved file will be different.
|
||||
|
||||
#### `downloadItem.getTotalBytes()`
|
||||
|
||||
Returns `Integer` - The total size in bytes of the download item.
|
||||
|
||||
If the size is unknown, it returns 0.
|
||||
|
||||
#### `downloadItem.getReceivedBytes()`
|
||||
|
||||
Returns `Integer` - The received bytes of the download item.
|
||||
|
||||
#### `downloadItem.getContentDisposition()`
|
||||
|
||||
Returns `String` - The Content-Disposition field from the response
|
||||
header.
|
||||
|
||||
#### `downloadItem.getState()`
|
||||
|
||||
Returns `String` - The current state. Can be `progressing`, `completed`, `cancelled` or `interrupted`.
|
||||
|
||||
**Note:** The following methods are useful specifically to resume a
|
||||
`cancelled` item when session is restarted.
|
||||
|
||||
#### `downloadItem.getURLChain()`
|
||||
|
||||
Returns `String[]` - The complete URL chain of the item including any redirects.
|
||||
|
||||
#### `downloadItem.getLastModifiedTime()`
|
||||
|
||||
Returns `String` - Last-Modified header value.
|
||||
|
||||
#### `downloadItem.getETag()`
|
||||
|
||||
Returns `String` - ETag header value.
|
||||
|
||||
#### `downloadItem.getStartTime()`
|
||||
|
||||
Returns `Double` - Number of seconds since the UNIX epoch when the download was
|
||||
started.
|
||||
|
||||
### Instance Properties
|
||||
|
||||
#### `downloadItem.savePath`
|
||||
|
||||
A `String` property that determines the save file path of the download item.
|
||||
|
||||
The property is only available in session's `will-download` callback function.
|
||||
If user doesn't set the save path via the property, Electron will use the original
|
||||
routine to determine the save path; this usually prompts a save dialog.
|
||||
|
||||
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
|
|
@ -0,0 +1,198 @@
|
|||
---
|
||||
title: "Environment Variables"
|
||||
description: "Control application configuration and behavior without changing code."
|
||||
slug: environment-variables
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Environment Variables
|
||||
|
||||
> Control application configuration and behavior without changing code.
|
||||
|
||||
Certain Electron behaviors are controlled by environment variables because they
|
||||
are initialized earlier than the command line flags and the app's code.
|
||||
|
||||
POSIX shell example:
|
||||
|
||||
```sh
|
||||
$ export ELECTRON_ENABLE_LOGGING=true
|
||||
$ electron
|
||||
```
|
||||
|
||||
Windows console example:
|
||||
|
||||
```powershell
|
||||
> set ELECTRON_ENABLE_LOGGING=true
|
||||
> electron
|
||||
```
|
||||
|
||||
## Production Variables
|
||||
|
||||
The following environment variables are intended primarily for use at runtime
|
||||
in packaged Electron applications.
|
||||
|
||||
### `NODE_OPTIONS`
|
||||
|
||||
Electron includes support for a subset of Node's [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#cli_node_options_options). The majority are supported with the exception of those which conflict with Chromium's use of BoringSSL.
|
||||
|
||||
Example:
|
||||
|
||||
```sh
|
||||
export NODE_OPTIONS="--no-warnings --max-old-space-size=2048"
|
||||
```
|
||||
|
||||
Unsupported options are:
|
||||
|
||||
```sh
|
||||
--use-bundled-ca
|
||||
--force-fips
|
||||
--enable-fips
|
||||
--openssl-config
|
||||
--use-openssl-ca
|
||||
```
|
||||
|
||||
`NODE_OPTIONS` are explicitly disallowed in packaged apps, except for the following:
|
||||
|
||||
```sh
|
||||
--max-http-header-size
|
||||
--http-parser
|
||||
```
|
||||
|
||||
### `GOOGLE_API_KEY`
|
||||
|
||||
Geolocation support in Electron requires the use of Google Cloud Platform's
|
||||
geolocation webservice. To enable this feature, acquire a
|
||||
[Google API key](https://developers.google.com/maps/documentation/geolocation/get-api-key)
|
||||
and place the following code in your main process file, before opening any
|
||||
browser windows that will make geolocation requests:
|
||||
|
||||
```javascript
|
||||
process.env.GOOGLE_API_KEY = 'YOUR_KEY_HERE'
|
||||
```
|
||||
|
||||
By default, a newly generated Google API key may not be allowed to make geolocation requests.
|
||||
To enable the geolocation webservice for your project, enable it through the
|
||||
[API library](https://console.cloud.google.com/apis/library).
|
||||
|
||||
N.B. You will need to add a
|
||||
[Billing Account](https://cloud.google.com/billing/docs/how-to/payment-methods#add_a_payment_method)
|
||||
to the project associated to the API key for the geolocation webservice to work.
|
||||
|
||||
### `ELECTRON_NO_ASAR`
|
||||
|
||||
Disables ASAR support. This variable is only supported in forked child processes
|
||||
and spawned child processes that set `ELECTRON_RUN_AS_NODE`.
|
||||
|
||||
### `ELECTRON_RUN_AS_NODE`
|
||||
|
||||
Starts the process as a normal Node.js process.
|
||||
|
||||
In this mode, you will be able to pass [cli options](https://nodejs.org/api/cli.html) to Node.js as
|
||||
you would when running the normal Node.js executable, with the exception of the following flags:
|
||||
|
||||
* "--openssl-config"
|
||||
* "--use-bundled-ca"
|
||||
* "--use-openssl-ca",
|
||||
* "--force-fips"
|
||||
* "--enable-fips"
|
||||
|
||||
These flags are disabled owing to the fact that Electron uses BoringSSL instead of OpenSSL when building Node.js'
|
||||
`crypto` module, and so will not work as designed.
|
||||
|
||||
### `ELECTRON_NO_ATTACH_CONSOLE` _Windows_
|
||||
|
||||
Don't attach to the current console session.
|
||||
|
||||
### `ELECTRON_FORCE_WINDOW_MENU_BAR` _Linux_
|
||||
|
||||
Don't use the global menu bar on Linux.
|
||||
|
||||
### `ELECTRON_TRASH` _Linux_
|
||||
|
||||
Set the trash implementation on Linux. Default is `gio`.
|
||||
|
||||
Options:
|
||||
|
||||
* `gvfs-trash`
|
||||
* `trash-cli`
|
||||
* `kioclient5`
|
||||
* `kioclient`
|
||||
|
||||
## Development Variables
|
||||
|
||||
The following environment variables are intended primarily for development and
|
||||
debugging purposes.
|
||||
|
||||
### `ELECTRON_ENABLE_LOGGING`
|
||||
|
||||
Prints Chromium's internal logging to the console.
|
||||
|
||||
Setting this variable is the same as passing `--enable-logging`
|
||||
on the command line. For more info, see `--enable-logging` in [command-line
|
||||
switches](latest/api/command-line-switches.md#enable-loggingfile).
|
||||
|
||||
### `ELECTRON_LOG_FILE`
|
||||
|
||||
Sets the file destination for Chromium's internal logging.
|
||||
|
||||
Setting this variable is the same as passing `--log-file`
|
||||
on the command line. For more info, see `--log-file` in [command-line
|
||||
switches](latest/api/command-line-switches.md#log-filepath).
|
||||
|
||||
### `ELECTRON_DEBUG_DRAG_REGIONS`
|
||||
|
||||
Adds coloration to draggable regions on [`BrowserView`](latest/api/browser-view.md)s on macOS - draggable regions will be colored
|
||||
green and non-draggable regions will be colored red to aid debugging.
|
||||
|
||||
### `ELECTRON_DEBUG_NOTIFICATIONS`
|
||||
|
||||
Adds extra logs to [`Notification`](latest/api/notification.md) lifecycles on macOS to aid in debugging. Extra logging will be displayed when new Notifications are created or activated. They will also be displayed when common a
|
||||
tions are taken: a notification is shown, dismissed, its button is clicked, or it is replied to.
|
||||
|
||||
Sample output:
|
||||
|
||||
```sh
|
||||
Notification created (com.github.Electron:notification:EAF7B87C-A113-43D7-8E76-F88EC9D73D44)
|
||||
Notification displayed (com.github.Electron:notification:EAF7B87C-A113-43D7-8E76-F88EC9D73D44)
|
||||
Notification activated (com.github.Electron:notification:EAF7B87C-A113-43D7-8E76-F88EC9D73D44)
|
||||
Notification replied to (com.github.Electron:notification:EAF7B87C-A113-43D7-8E76-F88EC9D73D44)
|
||||
```
|
||||
|
||||
### `ELECTRON_LOG_ASAR_READS`
|
||||
|
||||
When Electron reads from an ASAR file, log the read offset and file path to
|
||||
the system `tmpdir`. The resulting file can be provided to the ASAR module
|
||||
to optimize file ordering.
|
||||
|
||||
### `ELECTRON_ENABLE_STACK_DUMPING`
|
||||
|
||||
Prints the stack trace to the console when Electron crashes.
|
||||
|
||||
This environment variable will not work if the `crashReporter` is started.
|
||||
|
||||
### `ELECTRON_DEFAULT_ERROR_MODE` _Windows_
|
||||
|
||||
Shows the Windows's crash dialog when Electron crashes.
|
||||
|
||||
This environment variable will not work if the `crashReporter` is started.
|
||||
|
||||
### `ELECTRON_OVERRIDE_DIST_PATH`
|
||||
|
||||
When running from the `electron` package, this variable tells
|
||||
the `electron` command to use the specified build of Electron instead of
|
||||
the one downloaded by `npm install`. Usage:
|
||||
|
||||
```sh
|
||||
export ELECTRON_OVERRIDE_DIST_PATH=/Users/username/projects/electron/out/Testing
|
||||
```
|
||||
|
||||
## Set By Electron
|
||||
|
||||
Electron sets some variables in your environment at runtime.
|
||||
|
||||
### `ORIGINAL_XDG_CURRENT_DESKTOP`
|
||||
|
||||
This variable is set to the value of `XDG_CURRENT_DESKTOP` that your application
|
||||
originally launched with. Electron sometimes modifies the value of `XDG_CURRENT_DESKTOP`
|
||||
to affect other logic within Chromium so if you want access to the _original_ value
|
||||
you should look up this environment variable instead.
|
|
@ -0,0 +1,131 @@
|
|||
---
|
||||
title: "Chrome Extension Support"
|
||||
description: "Electron supports a subset of the Chrome Extensions API, primarily to support DevTools extensions and Chromium-internal extensions, but it also happens to support some other extension capabilities."
|
||||
slug: extensions
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Chrome Extension Support
|
||||
|
||||
Electron supports a subset of the [Chrome Extensions
|
||||
API][chrome-extensions-api-index], primarily to support DevTools extensions and
|
||||
Chromium-internal extensions, but it also happens to support some other
|
||||
extension capabilities.
|
||||
|
||||
[chrome-extensions-api-index]: https://developer.chrome.com/extensions/api_index
|
||||
|
||||
> **Note:** Electron does not support arbitrary Chrome extensions from the
|
||||
> store, and it is a **non-goal** of the Electron project to be perfectly
|
||||
> compatible with Chrome's implementation of Extensions.
|
||||
|
||||
## Loading extensions
|
||||
|
||||
Electron only supports loading unpacked extensions (i.e., `.crx` files do not
|
||||
work). Extensions are installed per-`session`. To load an extension, call
|
||||
[`ses.loadExtension`](latest/api/session.md#sesloadextensionpath-options):
|
||||
|
||||
```js
|
||||
const { session } = require('electron')
|
||||
|
||||
session.loadExtension('path/to/unpacked/extension').then(({ id }) => {
|
||||
// ...
|
||||
})
|
||||
```
|
||||
|
||||
Loaded extensions will not be automatically remembered across exits; if you do
|
||||
not call `loadExtension` when the app runs, the extension will not be loaded.
|
||||
|
||||
Note that loading extensions is only supported in persistent sessions.
|
||||
Attempting to load an extension into an in-memory session will throw an error.
|
||||
|
||||
See the [`session`](latest/api/session.md) documentation for more information about
|
||||
loading, unloading, and querying active extensions.
|
||||
|
||||
## Supported Extensions APIs
|
||||
|
||||
We support the following extensions APIs, with some caveats. Other APIs may
|
||||
additionally be supported, but support for any APIs not listed here is
|
||||
provisional and may be removed.
|
||||
|
||||
### `chrome.devtools.inspectedWindow`
|
||||
|
||||
All features of this API are supported.
|
||||
|
||||
### `chrome.devtools.network`
|
||||
|
||||
All features of this API are supported.
|
||||
|
||||
### `chrome.devtools.panels`
|
||||
|
||||
All features of this API are supported.
|
||||
|
||||
### `chrome.extension`
|
||||
|
||||
The following properties of `chrome.extension` are supported:
|
||||
|
||||
- `chrome.extension.lastError`
|
||||
|
||||
The following methods of `chrome.extension` are supported:
|
||||
|
||||
- `chrome.extension.getURL`
|
||||
- `chrome.extension.getBackgroundPage`
|
||||
|
||||
### `chrome.runtime`
|
||||
|
||||
The following properties of `chrome.runtime` are supported:
|
||||
|
||||
- `chrome.runtime.lastError`
|
||||
- `chrome.runtime.id`
|
||||
|
||||
The following methods of `chrome.runtime` are supported:
|
||||
|
||||
- `chrome.runtime.getBackgroundPage`
|
||||
- `chrome.runtime.getManifest`
|
||||
- `chrome.runtime.getPlatformInfo`
|
||||
- `chrome.runtime.getURL`
|
||||
- `chrome.runtime.connect`
|
||||
- `chrome.runtime.sendMessage`
|
||||
- `chrome.runtime.reload`
|
||||
|
||||
The following events of `chrome.runtime` are supported:
|
||||
|
||||
- `chrome.runtime.onStartup`
|
||||
- `chrome.runtime.onInstalled`
|
||||
- `chrome.runtime.onSuspend`
|
||||
- `chrome.runtime.onSuspendCanceled`
|
||||
- `chrome.runtime.onConnect`
|
||||
- `chrome.runtime.onMessage`
|
||||
|
||||
### `chrome.storage`
|
||||
|
||||
Only `chrome.storage.local` is supported; `chrome.storage.sync` and
|
||||
`chrome.storage.managed` are not.
|
||||
|
||||
### `chrome.tabs`
|
||||
|
||||
The following methods of `chrome.tabs` are supported:
|
||||
|
||||
- `chrome.tabs.sendMessage`
|
||||
- `chrome.tabs.executeScript`
|
||||
|
||||
> **Note:** In Chrome, passing `-1` as a tab ID signifies the "currently active
|
||||
> tab". Since Electron has no such concept, passing `-1` as a tab ID is not
|
||||
> supported and will raise an error.
|
||||
|
||||
### `chrome.management`
|
||||
|
||||
The following methods of `chrome.management` are supported:
|
||||
|
||||
- `chrome.management.getAll`
|
||||
- `chrome.management.get`
|
||||
- `chrome.management.getSelf`
|
||||
- `chrome.management.getPermissionWarningsById`
|
||||
- `chrome.management.getPermissionWarningsByManifest`
|
||||
- `chrome.management.onEnabled`
|
||||
- `chrome.management.onDisabled`
|
||||
|
||||
### `chrome.webRequest`
|
||||
|
||||
All features of this API are supported.
|
||||
|
||||
> **NOTE:** Electron's [`webRequest`](latest/api/web-request.md) module takes precedence over `chrome.webRequest` if there are conflicting handlers.
|
|
@ -0,0 +1,38 @@
|
|||
---
|
||||
title: "`File` Object"
|
||||
description: "Use the HTML5 File API to work natively with files on the filesystem."
|
||||
slug: file-object
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# `File` Object
|
||||
|
||||
> Use the HTML5 `File` API to work natively with files on the filesystem.
|
||||
|
||||
The DOM's File interface provides abstraction around native files in order to
|
||||
let users work on native files directly with the HTML5 file API. Electron has
|
||||
added a `path` attribute to the `File` interface which exposes the file's real
|
||||
path on filesystem.
|
||||
|
||||
Example of getting a real path from a dragged-onto-the-app file:
|
||||
|
||||
```html
|
||||
<div id="holder">
|
||||
Drag your file here
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('drop', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
for (const f of e.dataTransfer.files) {
|
||||
console.log('File(s) you dragged here: ', f.path)
|
||||
}
|
||||
});
|
||||
document.addEventListener('dragover', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
});
|
||||
</script>
|
||||
```
|
|
@ -0,0 +1,228 @@
|
|||
---
|
||||
title: "Frameless Window"
|
||||
description: "Open a window without toolbars, borders, or other graphical \"chrome\"."
|
||||
slug: frameless-window
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Frameless Window
|
||||
|
||||
> Open a window without toolbars, borders, or other graphical "chrome".
|
||||
|
||||
A frameless window is a window that has no
|
||||
[chrome](https://developer.mozilla.org/en-US/docs/Glossary/Chrome), the parts of
|
||||
the window, like toolbars, that are not a part of the web page. These are
|
||||
options on the [`BrowserWindow`](latest/api/browser-window.md) class.
|
||||
|
||||
## Create a frameless window
|
||||
|
||||
To create a frameless window, you need to set `frame` to `false` in
|
||||
[BrowserWindow](latest/api/browser-window.md)'s `options`:
|
||||
|
||||
```javascript
|
||||
const { BrowserWindow } = require('electron')
|
||||
const win = new BrowserWindow({ width: 800, height: 600, frame: false })
|
||||
win.show()
|
||||
```
|
||||
|
||||
### Alternatives
|
||||
|
||||
There's an alternative way to specify a chromeless window on macOS and Windows.
|
||||
Instead of setting `frame` to `false` which disables both the titlebar and window controls,
|
||||
you may want to have the title bar hidden and your content extend to the full window size,
|
||||
yet still preserve the window controls ("traffic lights" on macOS) for standard window actions.
|
||||
You can do so by specifying the `titleBarStyle` option:
|
||||
|
||||
#### `hidden`
|
||||
|
||||
Results in a hidden title bar and a full size content window. On macOS, the title bar still has the standard window controls (“traffic lights”) in the top left.
|
||||
|
||||
```javascript
|
||||
const { BrowserWindow } = require('electron')
|
||||
const win = new BrowserWindow({ titleBarStyle: 'hidden' })
|
||||
win.show()
|
||||
```
|
||||
|
||||
### Alternatives on macOS
|
||||
|
||||
#### `hiddenInset`
|
||||
|
||||
Results in a hidden title bar with an alternative look where the traffic light buttons are slightly more inset from the window edge.
|
||||
|
||||
```javascript
|
||||
const { BrowserWindow } = require('electron')
|
||||
const win = new BrowserWindow({ titleBarStyle: 'hiddenInset' })
|
||||
win.show()
|
||||
```
|
||||
|
||||
#### `customButtonsOnHover`
|
||||
|
||||
Uses custom drawn close, and miniaturize buttons that display
|
||||
when hovering in the top left of the window. The fullscreen button
|
||||
is not available due to restrictions of frameless windows as they
|
||||
interface with Apple's macOS window masks. These custom buttons prevent
|
||||
issues with mouse events that occur with the standard window toolbar buttons.
|
||||
This option is only applicable for frameless windows.
|
||||
|
||||
```javascript
|
||||
const { BrowserWindow } = require('electron')
|
||||
const win = new BrowserWindow({ titleBarStyle: 'customButtonsOnHover', frame: false })
|
||||
win.show()
|
||||
```
|
||||
|
||||
## Windows Control Overlay
|
||||
|
||||
When using a frameless window in conjuction with `win.setWindowButtonVisibility(true)` on macOS, using one of the `titleBarStyle`s as described above so
|
||||
that the traffic lights are visible, or using `titleBarStyle: hidden` on Windows, you can access the Window Controls Overlay [JavaScript APIs][overlay-javascript-apis] and
|
||||
[CSS Environment Variables][overlay-css-env-vars] by setting the `titleBarOverlay` option to true. Specifying `true` will result in an overlay with default system colors.
|
||||
|
||||
On Windows, you can also specify the color of the overlay and its symbols by setting `titleBarOverlay` to an object with the options `color` and `symbolColor`. If an option is not specified, the color will default to its system color for the window control buttons:
|
||||
|
||||
```javascript
|
||||
const { BrowserWindow } = require('electron')
|
||||
const win = new BrowserWindow({
|
||||
titleBarStyle: 'hidden',
|
||||
titleBarOverlay: true
|
||||
})
|
||||
win.show()
|
||||
```
|
||||
|
||||
```javascript
|
||||
const { BrowserWindow } = require('electron')
|
||||
const win = new BrowserWindow({
|
||||
titleBarStyle: 'hidden',
|
||||
titleBarOverlay: {
|
||||
color: '#2f3241',
|
||||
symbolColor: '#74b1be'
|
||||
}
|
||||
})
|
||||
win.show()
|
||||
```
|
||||
|
||||
## Transparent window
|
||||
|
||||
By setting the `transparent` option to `true`, you can also make the frameless
|
||||
window transparent:
|
||||
|
||||
```javascript
|
||||
const { BrowserWindow } = require('electron')
|
||||
const win = new BrowserWindow({ transparent: true, frame: false })
|
||||
win.show()
|
||||
```
|
||||
|
||||
### Limitations
|
||||
|
||||
* You can not click through the transparent area. We are going to introduce an
|
||||
API to set window shape to solve this, see
|
||||
[our issue](https://github.com/electron/electron/issues/1335) for details.
|
||||
* Transparent windows are not resizable. Setting `resizable` to `true` may make
|
||||
a transparent window stop working on some platforms.
|
||||
* 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).
|
||||
* 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
|
||||
NVidia drivers](https://bugs.chromium.org/p/chromium/issues/detail?id=369209) on
|
||||
Linux.
|
||||
* On Mac, the native window shadow will not be shown on a transparent window.
|
||||
|
||||
## Click-through window
|
||||
|
||||
To create a click-through window, i.e. making the window ignore all mouse
|
||||
events, you can call the [win.setIgnoreMouseEvents(ignore)][ignore-mouse-events]
|
||||
API:
|
||||
|
||||
```javascript
|
||||
const { BrowserWindow } = require('electron')
|
||||
const win = new BrowserWindow()
|
||||
win.setIgnoreMouseEvents(true)
|
||||
```
|
||||
|
||||
### Forwarding
|
||||
|
||||
Ignoring mouse messages makes the web page oblivious to mouse movement, meaning
|
||||
that mouse movement events will not be emitted. On Windows operating systems an
|
||||
optional parameter can be used to forward mouse move messages to the web page,
|
||||
allowing events such as `mouseleave` to be emitted:
|
||||
|
||||
```javascript
|
||||
const { ipcRenderer } = require('electron')
|
||||
const el = document.getElementById('clickThroughElement')
|
||||
el.addEventListener('mouseenter', () => {
|
||||
ipcRenderer.send('set-ignore-mouse-events', true, { forward: true })
|
||||
})
|
||||
el.addEventListener('mouseleave', () => {
|
||||
ipcRenderer.send('set-ignore-mouse-events', false)
|
||||
})
|
||||
|
||||
// Main process
|
||||
const { ipcMain } = require('electron')
|
||||
ipcMain.on('set-ignore-mouse-events', (event, ...args) => {
|
||||
BrowserWindow.fromWebContents(event.sender).setIgnoreMouseEvents(...args)
|
||||
})
|
||||
```
|
||||
|
||||
This makes the web page click-through when over `el`, and returns to normal
|
||||
outside it.
|
||||
|
||||
## Draggable region
|
||||
|
||||
By default, the frameless window is non-draggable. Apps need to specify
|
||||
`-webkit-app-region: drag` in CSS to tell Electron which regions are draggable
|
||||
(like the OS's standard titlebar), and apps can also use
|
||||
`-webkit-app-region: no-drag` to exclude the non-draggable area from the
|
||||
draggable region. Note that only rectangular shapes are currently supported.
|
||||
|
||||
Note: `-webkit-app-region: drag` is known to have problems while the developer tools are open. See this [GitHub issue](https://github.com/electron/electron/issues/3647) for more information including a workaround.
|
||||
|
||||
To make the whole window draggable, you can add `-webkit-app-region: drag` as
|
||||
`body`'s style:
|
||||
|
||||
```html
|
||||
<body style="-webkit-app-region: drag">
|
||||
</body>
|
||||
```
|
||||
|
||||
And note that if you have made the whole window draggable, you must also mark
|
||||
buttons as non-draggable, otherwise it would be impossible for users to click on
|
||||
them:
|
||||
|
||||
```css
|
||||
button {
|
||||
-webkit-app-region: no-drag;
|
||||
}
|
||||
```
|
||||
|
||||
If you're only setting a custom titlebar as draggable, you also need to make all
|
||||
buttons in titlebar non-draggable.
|
||||
|
||||
## Text selection
|
||||
|
||||
In a frameless window the dragging behavior may conflict with selecting text.
|
||||
For example, when you drag the titlebar you may accidentally select the text on
|
||||
the titlebar. To prevent this, you need to disable text selection within a
|
||||
draggable area like this:
|
||||
|
||||
```css
|
||||
.titlebar {
|
||||
-webkit-user-select: none;
|
||||
-webkit-app-region: drag;
|
||||
}
|
||||
```
|
||||
|
||||
## Context menu
|
||||
|
||||
On some platforms, the draggable area will be treated as a non-client frame, so
|
||||
when you right click on it a system menu will pop up. To make the context menu
|
||||
behave correctly on all platforms you should never use a custom context menu on
|
||||
draggable areas.
|
||||
|
||||
[ignore-mouse-events]: latest/api/browser-window.md#winsetignoremouseeventsignore-options
|
||||
[overlay-javascript-apis]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#javascript-apis
|
||||
[overlay-css-env-vars]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#css-environment-variables
|
|
@ -0,0 +1,111 @@
|
|||
---
|
||||
title: "globalShortcut"
|
||||
description: "Detect keyboard events when the application does not have keyboard focus."
|
||||
slug: global-shortcut
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# globalShortcut
|
||||
|
||||
> Detect keyboard events when the application does not have keyboard focus.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
The `globalShortcut` module can register/unregister a global keyboard shortcut
|
||||
with the operating system so that you can customize the operations for various
|
||||
shortcuts.
|
||||
|
||||
**Note:** The shortcut is global; it will work even if the app does
|
||||
not have the keyboard focus. This module cannot be used before the `ready`
|
||||
event of the app module is emitted.
|
||||
|
||||
```javascript
|
||||
const { app, globalShortcut } = require('electron')
|
||||
|
||||
app.whenReady().then(() => {
|
||||
// Register a 'CommandOrControl+X' shortcut listener.
|
||||
const ret = globalShortcut.register('CommandOrControl+X', () => {
|
||||
console.log('CommandOrControl+X is pressed')
|
||||
})
|
||||
|
||||
if (!ret) {
|
||||
console.log('registration failed')
|
||||
}
|
||||
|
||||
// Check whether a shortcut is registered.
|
||||
console.log(globalShortcut.isRegistered('CommandOrControl+X'))
|
||||
})
|
||||
|
||||
app.on('will-quit', () => {
|
||||
// Unregister a shortcut.
|
||||
globalShortcut.unregister('CommandOrControl+X')
|
||||
|
||||
// Unregister all shortcuts.
|
||||
globalShortcut.unregisterAll()
|
||||
})
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
The `globalShortcut` module has the following methods:
|
||||
|
||||
### `globalShortcut.register(accelerator, callback)`
|
||||
|
||||
* `accelerator` [Accelerator](latest/api/accelerator.md)
|
||||
* `callback` Function
|
||||
|
||||
Returns `Boolean` - Whether or not the shortcut was registered successfully.
|
||||
|
||||
Registers a global shortcut of `accelerator`. The `callback` is called when
|
||||
the registered shortcut is pressed by the user.
|
||||
|
||||
When the accelerator is already taken by other applications, this call will
|
||||
silently fail. This behavior is intended by operating systems, since they don't
|
||||
want applications to fight for global shortcuts.
|
||||
|
||||
The following accelerators will not be registered successfully on macOS 10.14 Mojave unless
|
||||
the app has been authorized as a [trusted accessibility client](https://developer.apple.com/library/archive/documentation/Accessibility/Conceptual/AccessibilityMacOSX/OSXAXTestingApps.html):
|
||||
|
||||
* "Media Play/Pause"
|
||||
* "Media Next Track"
|
||||
* "Media Previous Track"
|
||||
* "Media Stop"
|
||||
|
||||
### `globalShortcut.registerAll(accelerators, callback)`
|
||||
|
||||
* `accelerators` String[] - an array of [Accelerator](latest/api/accelerator.md)s.
|
||||
* `callback` Function
|
||||
|
||||
Registers a global shortcut of all `accelerator` items in `accelerators`. The `callback` is called when any of the registered shortcuts are pressed by the user.
|
||||
|
||||
When a given accelerator is already taken by other applications, this call will
|
||||
silently fail. This behavior is intended by operating systems, since they don't
|
||||
want applications to fight for global shortcuts.
|
||||
|
||||
The following accelerators will not be registered successfully on macOS 10.14 Mojave unless
|
||||
the app has been authorized as a [trusted accessibility client](https://developer.apple.com/library/archive/documentation/Accessibility/Conceptual/AccessibilityMacOSX/OSXAXTestingApps.html):
|
||||
|
||||
* "Media Play/Pause"
|
||||
* "Media Next Track"
|
||||
* "Media Previous Track"
|
||||
* "Media Stop"
|
||||
|
||||
### `globalShortcut.isRegistered(accelerator)`
|
||||
|
||||
* `accelerator` [Accelerator](latest/api/accelerator.md)
|
||||
|
||||
Returns `Boolean` - Whether this application has registered `accelerator`.
|
||||
|
||||
When the accelerator is already taken by other applications, this call will
|
||||
still return `false`. This behavior is intended by operating systems, since they
|
||||
don't want applications to fight for global shortcuts.
|
||||
|
||||
### `globalShortcut.unregister(accelerator)`
|
||||
|
||||
* `accelerator` [Accelerator](latest/api/accelerator.md)
|
||||
|
||||
Unregisters the global shortcut of `accelerator`.
|
||||
|
||||
### `globalShortcut.unregisterAll()`
|
||||
|
||||
Unregisters all of the global shortcuts.
|
|
@ -0,0 +1,70 @@
|
|||
---
|
||||
title: "inAppPurchase"
|
||||
description: "In-app purchases on Mac App Store."
|
||||
slug: in-app-purchase
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# inAppPurchase
|
||||
|
||||
> In-app purchases on Mac App Store.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
## Events
|
||||
|
||||
The `inAppPurchase` module emits the following events:
|
||||
|
||||
### Event: 'transactions-updated'
|
||||
|
||||
Emitted when one or more transactions have been updated.
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `transactions` Transaction[] - Array of [`Transaction`](latest/api/structures/transaction.md) objects.
|
||||
|
||||
## Methods
|
||||
|
||||
The `inAppPurchase` module has the following methods:
|
||||
|
||||
### `inAppPurchase.purchaseProduct(productID[, quantity])`
|
||||
|
||||
* `productID` String - The identifiers of the product to purchase. (The identifier of `com.example.app.product1` is `product1`).
|
||||
* `quantity` Integer (optional) - The number of items the user wants to purchase.
|
||||
|
||||
Returns `Promise<Boolean>` - Returns `true` if the product is valid and added to the payment queue.
|
||||
|
||||
You should listen for the `transactions-updated` event as soon as possible and certainly before you call `purchaseProduct`.
|
||||
|
||||
### `inAppPurchase.getProducts(productIDs)`
|
||||
|
||||
* `productIDs` String[] - The identifiers of the products to get.
|
||||
|
||||
Returns `Promise<Product[]>` - Resolves with an array of [`Product`](latest/api/structures/product.md) objects.
|
||||
|
||||
Retrieves the product descriptions.
|
||||
|
||||
### `inAppPurchase.canMakePayments()`
|
||||
|
||||
Returns `Boolean` - whether a user can make a payment.
|
||||
|
||||
### `inAppPurchase.restoreCompletedTransactions()`
|
||||
|
||||
Restores finished transactions. This method can be called either to install purchases on additional devices, or to restore purchases for an application that the user deleted and reinstalled.
|
||||
|
||||
[The payment queue](https://developer.apple.com/documentation/storekit/skpaymentqueue?language=objc) delivers a new transaction for each previously completed transaction that can be restored. Each transaction includes a copy of the original transaction.
|
||||
|
||||
### `inAppPurchase.getReceiptURL()`
|
||||
|
||||
Returns `String` - the path to the receipt.
|
||||
|
||||
### `inAppPurchase.finishAllTransactions()`
|
||||
|
||||
Completes all pending transactions.
|
||||
|
||||
### `inAppPurchase.finishTransactionByDate(date)`
|
||||
|
||||
* `date` String - The ISO formatted date of the transaction to finish.
|
||||
|
||||
Completes the pending transactions corresponding to the date.
|
|
@ -0,0 +1,89 @@
|
|||
---
|
||||
title: "Class: IncomingMessage"
|
||||
description: "Handle responses to HTTP/HTTPS requests."
|
||||
slug: incoming-message
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
## Class: IncomingMessage
|
||||
|
||||
> Handle responses to HTTP/HTTPS requests.
|
||||
|
||||
Process: [Main](latest/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._
|
||||
|
||||
`IncomingMessage` implements the [Readable Stream](https://nodejs.org/api/stream.html#stream_readable_streams)
|
||||
interface and is therefore an [EventEmitter][event-emitter].
|
||||
|
||||
### Instance Events
|
||||
|
||||
#### Event: 'data'
|
||||
|
||||
Returns:
|
||||
|
||||
* `chunk` Buffer - A chunk of response body's data.
|
||||
|
||||
The `data` event is the usual method of transferring response data into
|
||||
applicative code.
|
||||
|
||||
#### Event: 'end'
|
||||
|
||||
Indicates that response body has ended. Must be placed before 'data' event.
|
||||
|
||||
#### Event: 'aborted'
|
||||
|
||||
Emitted when a request has been canceled during an ongoing HTTP transaction.
|
||||
|
||||
#### Event: 'error'
|
||||
|
||||
Returns:
|
||||
|
||||
`error` Error - Typically holds an error string identifying failure root cause.
|
||||
|
||||
Emitted when an error was encountered while streaming response data events. For
|
||||
instance, if the server closes the underlying while the response is still
|
||||
streaming, an `error` event will be emitted on the response object and a `close`
|
||||
event will subsequently follow on the request object.
|
||||
|
||||
### Instance Properties
|
||||
|
||||
An `IncomingMessage` instance has the following readable properties:
|
||||
|
||||
#### `response.statusCode`
|
||||
|
||||
An `Integer` indicating the HTTP response status code.
|
||||
|
||||
#### `response.statusMessage`
|
||||
|
||||
A `String` representing the HTTP status message.
|
||||
|
||||
#### `response.headers`
|
||||
|
||||
A `Record<string, string | string[]>` representing the HTTP response headers. The `headers` object is
|
||||
formatted as follows:
|
||||
|
||||
* All header names are lowercased.
|
||||
* Duplicates of `age`, `authorization`, `content-length`, `content-type`,
|
||||
`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,
|
||||
`last-modified`, `location`, `max-forwards`, `proxy-authorization`, `referer`,
|
||||
`retry-after`, `server`, or `user-agent` are discarded.
|
||||
* `set-cookie` is always an array. Duplicates are added to the array.
|
||||
* For duplicate `cookie` headers, the values are joined together with '; '.
|
||||
* For all other headers, the values are joined together with ', '.
|
||||
|
||||
#### `response.httpVersion`
|
||||
|
||||
A `String` indicating the HTTP protocol version number. Typical values are '1.0'
|
||||
or '1.1'. Additionally `httpVersionMajor` and `httpVersionMinor` are two
|
||||
Integer-valued readable properties that return respectively the HTTP major and
|
||||
minor version numbers.
|
||||
|
||||
#### `response.httpVersionMajor`
|
||||
|
||||
An `Integer` indicating the HTTP protocol major version number.
|
||||
|
||||
#### `response.httpVersionMinor`
|
||||
|
||||
An `Integer` indicating the HTTP protocol minor version number.
|
||||
|
||||
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
|
|
@ -0,0 +1,165 @@
|
|||
---
|
||||
title: "ipcMain"
|
||||
description: "Communicate asynchronously from the main process to renderer processes."
|
||||
slug: ipc-main
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# ipcMain
|
||||
|
||||
> Communicate asynchronously from the main process to renderer processes.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
The `ipcMain` module is an [Event Emitter][event-emitter]. When used in the main
|
||||
process, it handles asynchronous and synchronous messages sent from a renderer
|
||||
process (web page). Messages sent from a renderer will be emitted to this
|
||||
module.
|
||||
|
||||
## Sending Messages
|
||||
|
||||
It is also possible to send messages from the main process to the renderer
|
||||
process, see [webContents.send][web-contents-send] for more information.
|
||||
|
||||
* When sending a message, the event name is the `channel`.
|
||||
* To reply to a synchronous message, you need to set `event.returnValue`.
|
||||
* To send an asynchronous message back to the sender, you can use
|
||||
`event.reply(...)`. This helper method will automatically handle messages
|
||||
coming from frames that aren't the main frame (e.g. iframes) whereas
|
||||
`event.sender.send(...)` will always send to the main frame.
|
||||
|
||||
An example of sending and handling messages between the render and main
|
||||
processes:
|
||||
|
||||
```javascript
|
||||
// In main process.
|
||||
const { ipcMain } = require('electron')
|
||||
ipcMain.on('asynchronous-message', (event, arg) => {
|
||||
console.log(arg) // prints "ping"
|
||||
event.reply('asynchronous-reply', 'pong')
|
||||
})
|
||||
|
||||
ipcMain.on('synchronous-message', (event, arg) => {
|
||||
console.log(arg) // prints "ping"
|
||||
event.returnValue = 'pong'
|
||||
})
|
||||
```
|
||||
|
||||
```javascript
|
||||
// In renderer process (web page).
|
||||
// NB. Electron APIs are only accessible from preload, unless contextIsolation is disabled.
|
||||
// See https://www.electronjs.org/docs/tutorial/process-model#preload-scripts for more details.
|
||||
const { ipcRenderer } = require('electron')
|
||||
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // prints "pong"
|
||||
|
||||
ipcRenderer.on('asynchronous-reply', (event, arg) => {
|
||||
console.log(arg) // prints "pong"
|
||||
})
|
||||
ipcRenderer.send('asynchronous-message', 'ping')
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
The `ipcMain` module has the following method to listen for events:
|
||||
|
||||
### `ipcMain.on(channel, listener)`
|
||||
|
||||
* `channel` String
|
||||
* `listener` Function
|
||||
* `event` IpcMainEvent
|
||||
* `...args` any[]
|
||||
|
||||
Listens to `channel`, when a new message arrives `listener` would be called with
|
||||
`listener(event, args...)`.
|
||||
|
||||
### `ipcMain.once(channel, listener)`
|
||||
|
||||
* `channel` String
|
||||
* `listener` Function
|
||||
* `event` IpcMainEvent
|
||||
* `...args` any[]
|
||||
|
||||
Adds a one time `listener` function for the event. This `listener` is invoked
|
||||
only the next time a message is sent to `channel`, after which it is removed.
|
||||
|
||||
### `ipcMain.removeListener(channel, listener)`
|
||||
|
||||
* `channel` String
|
||||
* `listener` Function
|
||||
* `...args` any[]
|
||||
|
||||
Removes the specified `listener` from the listener array for the specified
|
||||
`channel`.
|
||||
|
||||
### `ipcMain.removeAllListeners([channel])`
|
||||
|
||||
* `channel` String (optional)
|
||||
|
||||
Removes listeners of the specified `channel`.
|
||||
|
||||
### `ipcMain.handle(channel, listener)`
|
||||
|
||||
* `channel` String
|
||||
* `listener` Function<Promise\<void> | any>
|
||||
* `event` IpcMainInvokeEvent
|
||||
* `...args` any[]
|
||||
|
||||
Adds a handler for an `invoke`able IPC. This handler will be called whenever a
|
||||
renderer calls `ipcRenderer.invoke(channel, ...args)`.
|
||||
|
||||
If `listener` returns a Promise, the eventual result of the promise will be
|
||||
returned as a reply to the remote caller. Otherwise, the return value of the
|
||||
listener will be used as the value of the reply.
|
||||
|
||||
```js
|
||||
// Main process
|
||||
ipcMain.handle('my-invokable-ipc', async (event, ...args) => {
|
||||
const result = await somePromise(...args)
|
||||
return result
|
||||
})
|
||||
|
||||
// Renderer process
|
||||
async () => {
|
||||
const result = await ipcRenderer.invoke('my-invokable-ipc', arg1, arg2)
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
The `event` that is passed as the first argument to the handler is the same as
|
||||
that passed to a regular event listener. It includes information about which
|
||||
WebContents is the source of the invoke request.
|
||||
|
||||
Errors thrown through `handle` in the main process are not transparent as they
|
||||
are serialized and only the `message` property from the original error is
|
||||
provided to the renderer process. Please refer to
|
||||
[#24427](https://github.com/electron/electron/issues/24427) for details.
|
||||
|
||||
### `ipcMain.handleOnce(channel, listener)`
|
||||
|
||||
* `channel` String
|
||||
* `listener` Function<Promise\<void> | any>
|
||||
* `event` IpcMainInvokeEvent
|
||||
* `...args` any[]
|
||||
|
||||
Handles a single `invoke`able IPC message, then removes the listener. See
|
||||
`ipcMain.handle(channel, listener)`.
|
||||
|
||||
### `ipcMain.removeHandler(channel)`
|
||||
|
||||
* `channel` String
|
||||
|
||||
Removes any handler for `channel`, if present.
|
||||
|
||||
## IpcMainEvent object
|
||||
|
||||
The documentation for the `event` object passed to the `callback` can be found
|
||||
in the [`ipc-main-event`](latest/api/structures/ipc-main-event.md) structure docs.
|
||||
|
||||
## IpcMainInvokeEvent object
|
||||
|
||||
The documentation for the `event` object passed to `handle` callbacks can be
|
||||
found in the [`ipc-main-invoke-event`](latest/api/structures/ipc-main-invoke-event.md)
|
||||
structure docs.
|
||||
|
||||
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
|
||||
[web-contents-send]: latest/api/web-contents.md#contentssendchannel-args
|
|
@ -0,0 +1,212 @@
|
|||
---
|
||||
title: "ipcRenderer"
|
||||
description: "Communicate asynchronously from a renderer process to the main process."
|
||||
slug: ipc-renderer
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# ipcRenderer
|
||||
|
||||
> Communicate asynchronously from a renderer process to the main process.
|
||||
|
||||
Process: [Renderer](latest/glossary.md#renderer-process)
|
||||
|
||||
The `ipcRenderer` module is an [EventEmitter][event-emitter]. It provides a few
|
||||
methods so you can send synchronous and asynchronous messages from the render
|
||||
process (web page) to the main process. You can also receive replies from the
|
||||
main process.
|
||||
|
||||
See [ipcMain](latest/api/ipc-main.md) for code examples.
|
||||
|
||||
## Methods
|
||||
|
||||
The `ipcRenderer` module has the following method to listen for events and send messages:
|
||||
|
||||
### `ipcRenderer.on(channel, listener)`
|
||||
|
||||
* `channel` String
|
||||
* `listener` Function
|
||||
* `event` IpcRendererEvent
|
||||
* `...args` any[]
|
||||
|
||||
Listens to `channel`, when a new message arrives `listener` would be called with
|
||||
`listener(event, args...)`.
|
||||
|
||||
### `ipcRenderer.once(channel, listener)`
|
||||
|
||||
* `channel` String
|
||||
* `listener` Function
|
||||
* `event` IpcRendererEvent
|
||||
* `...args` any[]
|
||||
|
||||
Adds a one time `listener` function for the event. This `listener` is invoked
|
||||
only the next time a message is sent to `channel`, after which it is removed.
|
||||
|
||||
### `ipcRenderer.removeListener(channel, listener)`
|
||||
|
||||
* `channel` String
|
||||
* `listener` Function
|
||||
* `...args` any[]
|
||||
|
||||
Removes the specified `listener` from the listener array for the specified
|
||||
`channel`.
|
||||
|
||||
### `ipcRenderer.removeAllListeners(channel)`
|
||||
|
||||
* `channel` String
|
||||
|
||||
Removes all listeners, or those of the specified `channel`.
|
||||
|
||||
### `ipcRenderer.send(channel, ...args)`
|
||||
|
||||
* `channel` String
|
||||
* `...args` any[]
|
||||
|
||||
Send an asynchronous message to the main process via `channel`, along with
|
||||
arguments. Arguments will be serialized with the [Structured Clone
|
||||
Algorithm][SCA], just like [`window.postMessage`][], so prototype chains will not be
|
||||
included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will
|
||||
throw an exception.
|
||||
|
||||
> **NOTE:** Sending non-standard JavaScript types such as DOM objects or
|
||||
> special Electron objects will throw an exception.
|
||||
>
|
||||
> Since the main process does not have support for DOM objects such as
|
||||
> `ImageBitmap`, `File`, `DOMMatrix` and so on, such objects cannot be sent over
|
||||
> Electron's IPC to the main process, as the main process would have no way to decode
|
||||
> them. Attempting to send such objects over IPC will result in an error.
|
||||
|
||||
The main process handles it by listening for `channel` with the
|
||||
[`ipcMain`](latest/api/ipc-main.md) module.
|
||||
|
||||
If you need to transfer a [`MessagePort`][] to the main process, use [`ipcRenderer.postMessage`](#ipcrendererpostmessagechannel-message-transfer).
|
||||
|
||||
If you want to receive a single response from the main process, like the result of a method call, consider using [`ipcRenderer.invoke`](#ipcrendererinvokechannel-args).
|
||||
|
||||
### `ipcRenderer.invoke(channel, ...args)`
|
||||
|
||||
* `channel` String
|
||||
* `...args` any[]
|
||||
|
||||
Returns `Promise<any>` - Resolves with the response from the main process.
|
||||
|
||||
Send a message to the main process via `channel` and expect a result
|
||||
asynchronously. Arguments will be serialized with the [Structured Clone
|
||||
Algorithm][SCA], just like [`window.postMessage`][], so prototype chains will not be
|
||||
included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will
|
||||
throw an exception.
|
||||
|
||||
> **NOTE:** Sending non-standard JavaScript types such as DOM objects or
|
||||
> special Electron objects will throw an exception.
|
||||
>
|
||||
> Since the main process does not have support for DOM objects such as
|
||||
> `ImageBitmap`, `File`, `DOMMatrix` and so on, such objects cannot be sent over
|
||||
> Electron's IPC to the main process, as the main process would have no way to decode
|
||||
> them. Attempting to send such objects over IPC will result in an error.
|
||||
|
||||
The main process should listen for `channel` with
|
||||
[`ipcMain.handle()`](latest/api/ipc-main.md#ipcmainhandlechannel-listener).
|
||||
|
||||
For example:
|
||||
|
||||
```javascript
|
||||
// Renderer process
|
||||
ipcRenderer.invoke('some-name', someArgument).then((result) => {
|
||||
// ...
|
||||
})
|
||||
|
||||
// Main process
|
||||
ipcMain.handle('some-name', async (event, someArgument) => {
|
||||
const result = await doSomeWork(someArgument)
|
||||
return result
|
||||
})
|
||||
```
|
||||
|
||||
If you need to transfer a [`MessagePort`][] to the main process, use [`ipcRenderer.postMessage`](#ipcrendererpostmessagechannel-message-transfer).
|
||||
|
||||
If you do not need a response to the message, consider using [`ipcRenderer.send`](#ipcrenderersendchannel-args).
|
||||
|
||||
### `ipcRenderer.sendSync(channel, ...args)`
|
||||
|
||||
* `channel` String
|
||||
* `...args` any[]
|
||||
|
||||
Returns `any` - The value sent back by the [`ipcMain`](latest/api/ipc-main.md) handler.
|
||||
|
||||
Send a message to the main process via `channel` and expect a result
|
||||
synchronously. Arguments will be serialized with the [Structured Clone
|
||||
Algorithm][SCA], just like [`window.postMessage`][], so prototype chains will not be
|
||||
included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will
|
||||
throw an exception.
|
||||
|
||||
> **NOTE:** Sending non-standard JavaScript types such as DOM objects or
|
||||
> special Electron objects will throw an exception.
|
||||
>
|
||||
> Since the main process does not have support for DOM objects such as
|
||||
> `ImageBitmap`, `File`, `DOMMatrix` and so on, such objects cannot be sent over
|
||||
> Electron's IPC to the main process, as the main process would have no way to decode
|
||||
> them. Attempting to send such objects over IPC will result in an error.
|
||||
|
||||
The main process handles it by listening for `channel` with [`ipcMain`](latest/api/ipc-main.md) module,
|
||||
and replies by setting `event.returnValue`.
|
||||
|
||||
> :warning: **WARNING**: Sending a synchronous message will block the whole
|
||||
> renderer process until the reply is received, so use this method only as a
|
||||
> last resort. It's much better to use the asynchronous version,
|
||||
> [`invoke()`](latest/api/ipc-renderer.md#ipcrendererinvokechannel-args).
|
||||
|
||||
### `ipcRenderer.postMessage(channel, message, [transfer])`
|
||||
|
||||
* `channel` String
|
||||
* `message` any
|
||||
* `transfer` MessagePort[] (optional)
|
||||
|
||||
Send a message to the main process, optionally transferring ownership of zero
|
||||
or more [`MessagePort`][] objects.
|
||||
|
||||
The transferred `MessagePort` objects will be available in the main process as
|
||||
[`MessagePortMain`](latest/api/message-port-main.md) objects by accessing the `ports`
|
||||
property of the emitted event.
|
||||
|
||||
For example:
|
||||
|
||||
```js
|
||||
// Renderer process
|
||||
const { port1, port2 } = new MessageChannel()
|
||||
ipcRenderer.postMessage('port', { message: 'hello' }, [port1])
|
||||
|
||||
// Main process
|
||||
ipcMain.on('port', (e, msg) => {
|
||||
const [port] = e.ports
|
||||
// ...
|
||||
})
|
||||
```
|
||||
|
||||
For more information on using `MessagePort` and `MessageChannel`, see the [MDN
|
||||
documentation](https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel).
|
||||
|
||||
### `ipcRenderer.sendTo(webContentsId, channel, ...args)`
|
||||
|
||||
* `webContentsId` Number
|
||||
* `channel` String
|
||||
* `...args` any[]
|
||||
|
||||
Sends a message to a window with `webContentsId` via `channel`.
|
||||
|
||||
### `ipcRenderer.sendToHost(channel, ...args)`
|
||||
|
||||
* `channel` String
|
||||
* `...args` any[]
|
||||
|
||||
Like `ipcRenderer.send` but the event will be sent to the `<webview>` element in
|
||||
the host page instead of the main process.
|
||||
|
||||
## Event object
|
||||
|
||||
The documentation for the `event` object passed to the `callback` can be found
|
||||
in the [`ipc-renderer-event`](latest/api/structures/ipc-renderer-event.md) structure docs.
|
||||
|
||||
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
|
||||
[SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
|
||||
[`window.postMessage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
|
||||
[`MessagePort`]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort
|
|
@ -0,0 +1,234 @@
|
|||
---
|
||||
title: "Class: MenuItem"
|
||||
description: "Add items to native application menus and context menus."
|
||||
slug: menu-item
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
## Class: MenuItem
|
||||
|
||||
> Add items to native application menus and context menus.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
See [`Menu`](latest/api/menu.md) for examples.
|
||||
|
||||
### `new MenuItem(options)`
|
||||
|
||||
* `options` Object
|
||||
* `click` Function (optional) - Will be called with
|
||||
`click(menuItem, browserWindow, event)` when the menu item is clicked.
|
||||
* `menuItem` MenuItem
|
||||
* `browserWindow` [BrowserWindow](latest/api/browser-window.md) | undefined - This will not be defined if no window is open.
|
||||
* `event` [KeyboardEvent](latest/api/structures/keyboard-event.md)
|
||||
* `role` String (optional) - Can be `undo`, `redo`, `cut`, `copy`, `paste`, `pasteAndMatchStyle`, `delete`, `selectAll`, `reload`, `forceReload`, `toggleDevTools`, `resetZoom`, `zoomIn`, `zoomOut`, `toggleSpellChecker`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, `about`, `services`, `hide`, `hideOthers`, `unhide`, `quit`, `startSpeaking`, `stopSpeaking`, `zoom`, `front`, `appMenu`, `fileMenu`, `editMenu`, `viewMenu`, `shareMenu`, `recentDocuments`, `toggleTabBar`, `selectNextTab`, `selectPreviousTab`, `mergeAllWindows`, `clearRecentDocuments`, `moveTabToNewWindow` or `windowMenu` - Define the action of the menu item, when specified the
|
||||
`click` property will be ignored. See [roles](#roles).
|
||||
* `type` String (optional) - Can be `normal`, `separator`, `submenu`, `checkbox` or
|
||||
`radio`.
|
||||
* `label` String (optional)
|
||||
* `sublabel` String (optional)
|
||||
* `toolTip` String (optional) _macOS_ - Hover text for this menu item.
|
||||
* `accelerator` [Accelerator](latest/api/accelerator.md) (optional)
|
||||
* `icon` ([NativeImage](latest/api/native-image.md) | String) (optional)
|
||||
* `enabled` Boolean (optional) - If false, the menu item will be greyed out and
|
||||
unclickable.
|
||||
* `acceleratorWorksWhenHidden` Boolean (optional) _macOS_ - default is `true`, and when `false` will prevent the accelerator from triggering the item if the item is not visible`.
|
||||
* `visible` Boolean (optional) - If false, the menu item will be entirely hidden.
|
||||
* `checked` Boolean (optional) - Should only be specified for `checkbox` or `radio` type
|
||||
menu items.
|
||||
* `registerAccelerator` Boolean (optional) _Linux_ _Windows_ - If false, the accelerator won't be registered
|
||||
with the system, but it will still be displayed. Defaults to true.
|
||||
* `sharingItem` SharingItem (optional) _macOS_ - The item to share when the `role` is `shareMenu`.
|
||||
* `submenu` (MenuItemConstructorOptions[] | [Menu](latest/api/menu.md)) (optional) - Should be specified
|
||||
for `submenu` type menu items. If `submenu` is specified, the `type: 'submenu'` can be omitted.
|
||||
If the value is not a [`Menu`](latest/api/menu.md) then it will be automatically converted to one using
|
||||
`Menu.buildFromTemplate`.
|
||||
* `id` String (optional) - Unique within a single menu. If defined then it can be used
|
||||
as a reference to this item by the position attribute.
|
||||
* `before` String[] (optional) - Inserts this item before the item with the specified label. If
|
||||
the referenced item doesn't exist the item will be inserted at the end of the menu. Also implies
|
||||
that the menu item in question should be placed in the same “group” as the item.
|
||||
* `after` String[] (optional) - Inserts this item after the item with the specified label. If the
|
||||
referenced item doesn't exist the item will be inserted at the end of
|
||||
the menu.
|
||||
* `beforeGroupContaining` String[] (optional) - Provides a means for a single context menu to declare
|
||||
the placement of their containing group before the containing group of the item
|
||||
with the specified label.
|
||||
* `afterGroupContaining` String[] (optional) - Provides a means for a single context menu to declare
|
||||
the placement of their containing group after the containing group of the item
|
||||
with the specified label.
|
||||
|
||||
**Note:** `acceleratorWorksWhenHidden` is specified as being macOS-only because accelerators always work when items are hidden on Windows and Linux. The option is exposed to users to give them the option to turn it off, as this is possible in native macOS development. This property is only usable on macOS High Sierra 10.13 or newer.
|
||||
|
||||
### Roles
|
||||
|
||||
Roles allow menu items to have predefined behaviors.
|
||||
|
||||
It is best to specify `role` for any menu item that matches a standard role,
|
||||
rather than trying to manually implement the behavior in a `click` function.
|
||||
The built-in `role` behavior will give the best native experience.
|
||||
|
||||
The `label` and `accelerator` values are optional when using a `role` and will
|
||||
default to appropriate values for each platform.
|
||||
|
||||
Every menu item must have either a `role`, `label`, or in the case of a separator
|
||||
a `type`.
|
||||
|
||||
The `role` property can have following values:
|
||||
|
||||
* `undo`
|
||||
* `about` - Trigger a native about panel (custom message box on Window, which does not provide its own).
|
||||
* `redo`
|
||||
* `cut`
|
||||
* `copy`
|
||||
* `paste`
|
||||
* `pasteAndMatchStyle`
|
||||
* `selectAll`
|
||||
* `delete`
|
||||
* `minimize` - Minimize current window.
|
||||
* `close` - Close current window.
|
||||
* `quit` - Quit the application.
|
||||
* `reload` - Reload the current window.
|
||||
* `forceReload` - Reload the current window ignoring the cache.
|
||||
* `toggleDevTools` - Toggle developer tools in the current window.
|
||||
* `togglefullscreen` - Toggle full screen mode on the current window.
|
||||
* `resetZoom` - Reset the focused page's zoom level to the original size.
|
||||
* `zoomIn` - Zoom in the focused page by 10%.
|
||||
* `zoomOut` - Zoom out the focused page by 10%.
|
||||
* `toggleSpellChecker` - Enable/disable builtin spell checker.
|
||||
* `fileMenu` - Whole default "File" menu (Close / Quit)
|
||||
* `editMenu` - Whole default "Edit" menu (Undo, Copy, etc.).
|
||||
* `viewMenu` - Whole default "View" menu (Reload, Toggle Developer Tools, etc.)
|
||||
* `windowMenu` - Whole default "Window" menu (Minimize, Zoom, etc.).
|
||||
|
||||
The following additional roles are available on _macOS_:
|
||||
|
||||
* `appMenu` - Whole default "App" menu (About, Services, etc.)
|
||||
* `hide` - Map to the `hide` action.
|
||||
* `hideOthers` - Map to the `hideOtherApplications` action.
|
||||
* `unhide` - Map to the `unhideAllApplications` action.
|
||||
* `startSpeaking` - Map to the `startSpeaking` action.
|
||||
* `stopSpeaking` - Map to the `stopSpeaking` action.
|
||||
* `front` - Map to the `arrangeInFront` action.
|
||||
* `zoom` - Map to the `performZoom` action.
|
||||
* `toggleTabBar` - Map to the `toggleTabBar` action.
|
||||
* `selectNextTab` - Map to the `selectNextTab` action.
|
||||
* `selectPreviousTab` - Map to the `selectPreviousTab` action.
|
||||
* `mergeAllWindows` - Map to the `mergeAllWindows` action.
|
||||
* `moveTabToNewWindow` - Map to the `moveTabToNewWindow` action.
|
||||
* `window` - The submenu is a "Window" menu.
|
||||
* `help` - The submenu is a "Help" menu.
|
||||
* `services` - The submenu is a ["Services"](https://developer.apple.com/documentation/appkit/nsapplication/1428608-servicesmenu?language=objc) menu. This is only intended for use in the Application Menu and is *not* the same as the "Services" submenu used in context menus in macOS apps, which is not implemented in Electron.
|
||||
* `recentDocuments` - The submenu is an "Open Recent" menu.
|
||||
* `clearRecentDocuments` - Map to the `clearRecentDocuments` action.
|
||||
* `shareMenu` - The submenu is [share menu][ShareMenu]. The `sharingItem` property must also be set to indicate the item to share.
|
||||
|
||||
When specifying a `role` on macOS, `label` and `accelerator` are the only
|
||||
options that will affect the menu item. All other options will be ignored.
|
||||
Lowercase `role`, e.g. `toggledevtools`, is still supported.
|
||||
|
||||
**Nota Bene:** The `enabled` and `visibility` properties are not available for top-level menu items in the tray on macOS.
|
||||
|
||||
### Instance Properties
|
||||
|
||||
The following properties are available on instances of `MenuItem`:
|
||||
|
||||
#### `menuItem.id`
|
||||
|
||||
A `String` indicating the item's unique id, this property can be
|
||||
dynamically changed.
|
||||
|
||||
#### `menuItem.label`
|
||||
|
||||
A `String` indicating the item's visible label.
|
||||
|
||||
#### `menuItem.click`
|
||||
|
||||
A `Function` that is fired when the MenuItem receives a click event.
|
||||
It can be called with `menuItem.click(event, focusedWindow, focusedWebContents)`.
|
||||
|
||||
* `event` [KeyboardEvent](latest/api/structures/keyboard-event.md)
|
||||
* `focusedWindow` [BrowserWindow](latest/api/browser-window.md)
|
||||
* `focusedWebContents` [WebContents](latest/api/web-contents.md)
|
||||
|
||||
#### `menuItem.submenu`
|
||||
|
||||
A `Menu` (optional) containing the menu
|
||||
item's submenu, if present.
|
||||
|
||||
#### `menuItem.type`
|
||||
|
||||
A `String` indicating the type of the item. Can be `normal`, `separator`, `submenu`, `checkbox` or `radio`.
|
||||
|
||||
#### `menuItem.role`
|
||||
|
||||
A `String` (optional) indicating the item's role, if set. Can be `undo`, `redo`, `cut`, `copy`, `paste`, `pasteAndMatchStyle`, `delete`, `selectAll`, `reload`, `forceReload`, `toggleDevTools`, `resetZoom`, `zoomIn`, `zoomOut`, `toggleSpellChecker`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, `about`, `services`, `hide`, `hideOthers`, `unhide`, `quit`, `startSpeaking`, `stopSpeaking`, `zoom`, `front`, `appMenu`, `fileMenu`, `editMenu`, `viewMenu`, `shareMenu`, `recentDocuments`, `toggleTabBar`, `selectNextTab`, `selectPreviousTab`, `mergeAllWindows`, `clearRecentDocuments`, `moveTabToNewWindow` or `windowMenu`
|
||||
|
||||
#### `menuItem.accelerator`
|
||||
|
||||
An `Accelerator` (optional) indicating the item's accelerator, if set.
|
||||
|
||||
#### `menuItem.userAccelerator` _Readonly_ _macOS_
|
||||
|
||||
An `Accelerator | null` indicating the item's [user-assigned accelerator](https://developer.apple.com/documentation/appkit/nsmenuitem/1514850-userkeyequivalent?language=objc) for the menu item.
|
||||
|
||||
**Note:** This property is only initialized after the `MenuItem` has been added to a `Menu`. Either via `Menu.buildFromTemplate` or via `Menu.append()/insert()`. Accessing before initialization will just return `null`.
|
||||
|
||||
#### `menuItem.icon`
|
||||
|
||||
A `NativeImage | String` (optional) indicating the
|
||||
item's icon, if set.
|
||||
|
||||
#### `menuItem.sublabel`
|
||||
|
||||
A `String` indicating the item's sublabel.
|
||||
|
||||
#### `menuItem.toolTip` _macOS_
|
||||
|
||||
A `String` indicating the item's hover text.
|
||||
|
||||
#### `menuItem.enabled`
|
||||
|
||||
A `Boolean` indicating whether the item is enabled, this property can be
|
||||
dynamically changed.
|
||||
|
||||
#### `menuItem.visible`
|
||||
|
||||
A `Boolean` indicating whether the item is visible, this property can be
|
||||
dynamically changed.
|
||||
|
||||
#### `menuItem.checked`
|
||||
|
||||
A `Boolean` indicating whether the item is checked, this property can be
|
||||
dynamically changed.
|
||||
|
||||
A `checkbox` menu item will toggle the `checked` property on and off when
|
||||
selected.
|
||||
|
||||
A `radio` menu item will turn on its `checked` property when clicked, and
|
||||
will turn off that property for all adjacent items in the same menu.
|
||||
|
||||
You can add a `click` function for additional behavior.
|
||||
|
||||
#### `menuItem.registerAccelerator`
|
||||
|
||||
A `Boolean` indicating if the accelerator should be registered with the
|
||||
system or just displayed.
|
||||
|
||||
This property can be dynamically changed.
|
||||
|
||||
#### `menuItem.sharingItem` _macOS_
|
||||
|
||||
A `SharingItem` indicating the item to share when the `role` is `shareMenu`.
|
||||
|
||||
This property can be dynamically changed.
|
||||
|
||||
#### `menuItem.commandId`
|
||||
|
||||
A `Number` indicating an item's sequential unique id.
|
||||
|
||||
#### `menuItem.menu`
|
||||
|
||||
A `Menu` that the item is a part of.
|
||||
|
||||
[ShareMenu]: https://developer.apple.com/design/human-interface-guidelines/macos/extensions/share-extensions/
|
|
@ -0,0 +1,415 @@
|
|||
---
|
||||
title: "Menu"
|
||||
description: ""
|
||||
slug: menu
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Menu
|
||||
|
||||
## Class: Menu
|
||||
|
||||
> Create native application menus and context menus.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
### `new Menu()`
|
||||
|
||||
Creates a new menu.
|
||||
|
||||
### Static Methods
|
||||
|
||||
The `Menu` class has the following static methods:
|
||||
|
||||
#### `Menu.setApplicationMenu(menu)`
|
||||
|
||||
* `menu` Menu | null
|
||||
|
||||
Sets `menu` as the application menu on macOS. On Windows and Linux, the
|
||||
`menu` will be set as each window's top menu.
|
||||
|
||||
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 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.
|
||||
|
||||
**Note:** The default menu will be created automatically if the app does not set one.
|
||||
It contains standard items such as `File`, `Edit`, `View`, `Window` and `Help`.
|
||||
|
||||
#### `Menu.getApplicationMenu()`
|
||||
|
||||
Returns `Menu | null` - The application menu, if set, or `null`, if not set.
|
||||
|
||||
**Note:** The returned `Menu` instance doesn't support dynamic addition or
|
||||
removal of menu items. [Instance properties](#instance-properties) can still
|
||||
be dynamically modified.
|
||||
|
||||
#### `Menu.sendActionToFirstResponder(action)` _macOS_
|
||||
|
||||
* `action` String
|
||||
|
||||
Sends the `action` to the first responder of application. This is used for
|
||||
emulating default macOS menu behaviors. Usually you would use the
|
||||
[`role`](latest/api/menu-item.md#roles) property of a [`MenuItem`](latest/api/menu-item.md).
|
||||
|
||||
See the [macOS Cocoa Event Handling Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/EventOverview/EventArchitecture/EventArchitecture.html#//apple_ref/doc/uid/10000060i-CH3-SW7)
|
||||
for more information on macOS' native actions.
|
||||
|
||||
#### `Menu.buildFromTemplate(template)`
|
||||
|
||||
* `template` (MenuItemConstructorOptions | MenuItem)[]
|
||||
|
||||
Returns `Menu`
|
||||
|
||||
Generally, the `template` is an array of `options` for constructing a
|
||||
[MenuItem](latest/api/menu-item.md). The usage can be referenced above.
|
||||
|
||||
You can also attach other fields to the element of the `template` and they will become properties of the constructed menu items.
|
||||
|
||||
### Instance Methods
|
||||
|
||||
The `menu` object has the following instance methods:
|
||||
|
||||
#### `menu.popup([options])`
|
||||
|
||||
* `options` Object (optional)
|
||||
* `window` [BrowserWindow](latest/api/browser-window.md) (optional) - Default is the focused window.
|
||||
* `x` Number (optional) - Default is the current mouse cursor position.
|
||||
Must be declared if `y` is declared.
|
||||
* `y` Number (optional) - Default is the current mouse cursor position.
|
||||
Must be declared if `x` is declared.
|
||||
* `positioningItem` Number (optional) _macOS_ - The index of the menu item to
|
||||
be positioned under the mouse cursor at the specified coordinates. Default
|
||||
is -1.
|
||||
* `callback` Function (optional) - Called when menu is closed.
|
||||
|
||||
Pops up this menu as a context menu in the [`BrowserWindow`](latest/api/browser-window.md).
|
||||
|
||||
#### `menu.closePopup([browserWindow])`
|
||||
|
||||
* `browserWindow` [BrowserWindow](latest/api/browser-window.md) (optional) - Default is the focused window.
|
||||
|
||||
Closes the context menu in the `browserWindow`.
|
||||
|
||||
#### `menu.append(menuItem)`
|
||||
|
||||
* `menuItem` [MenuItem](latest/api/menu-item.md)
|
||||
|
||||
Appends the `menuItem` to the menu.
|
||||
|
||||
#### `menu.getMenuItemById(id)`
|
||||
|
||||
* `id` String
|
||||
|
||||
Returns `MenuItem | null` the item with the specified `id`
|
||||
|
||||
#### `menu.insert(pos, menuItem)`
|
||||
|
||||
* `pos` Integer
|
||||
* `menuItem` [MenuItem](latest/api/menu-item.md)
|
||||
|
||||
Inserts the `menuItem` to the `pos` position of the menu.
|
||||
|
||||
### Instance Events
|
||||
|
||||
Objects created with `new Menu` or returned by `Menu.buildFromTemplate` emit the following events:
|
||||
|
||||
**Note:** Some events are only available on specific operating systems and are
|
||||
labeled as such.
|
||||
|
||||
#### Event: 'menu-will-show'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
|
||||
Emitted when `menu.popup()` is called.
|
||||
|
||||
#### Event: 'menu-will-close'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
|
||||
Emitted when a popup is closed either manually or with `menu.closePopup()`.
|
||||
|
||||
### Instance Properties
|
||||
|
||||
`menu` objects also have the following properties:
|
||||
|
||||
#### `menu.items`
|
||||
|
||||
A `MenuItem[]` array containing the menu's items.
|
||||
|
||||
Each `Menu` consists of multiple [`MenuItem`](latest/api/menu-item.md)s and each `MenuItem`
|
||||
can have a submenu.
|
||||
|
||||
## Examples
|
||||
|
||||
An example of creating the application menu with the simple template API:
|
||||
|
||||
```javascript
|
||||
const { app, Menu } = require('electron')
|
||||
|
||||
const isMac = process.platform === 'darwin'
|
||||
|
||||
const template = [
|
||||
// { role: 'appMenu' }
|
||||
...(isMac ? [{
|
||||
label: app.name,
|
||||
submenu: [
|
||||
{ role: 'about' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'services' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'hide' },
|
||||
{ role: 'hideOthers' },
|
||||
{ role: 'unhide' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'quit' }
|
||||
]
|
||||
}] : []),
|
||||
// { role: 'fileMenu' }
|
||||
{
|
||||
label: 'File',
|
||||
submenu: [
|
||||
isMac ? { role: 'close' } : { role: 'quit' }
|
||||
]
|
||||
},
|
||||
// { role: 'editMenu' }
|
||||
{
|
||||
label: 'Edit',
|
||||
submenu: [
|
||||
{ role: 'undo' },
|
||||
{ role: 'redo' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'cut' },
|
||||
{ role: 'copy' },
|
||||
{ role: 'paste' },
|
||||
...(isMac ? [
|
||||
{ role: 'pasteAndMatchStyle' },
|
||||
{ role: 'delete' },
|
||||
{ role: 'selectAll' },
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: 'Speech',
|
||||
submenu: [
|
||||
{ role: 'startSpeaking' },
|
||||
{ role: 'stopSpeaking' }
|
||||
]
|
||||
}
|
||||
] : [
|
||||
{ role: 'delete' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'selectAll' }
|
||||
])
|
||||
]
|
||||
},
|
||||
// { role: 'viewMenu' }
|
||||
{
|
||||
label: 'View',
|
||||
submenu: [
|
||||
{ role: 'reload' },
|
||||
{ role: 'forceReload' },
|
||||
{ role: 'toggleDevTools' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'resetZoom' },
|
||||
{ role: 'zoomIn' },
|
||||
{ role: 'zoomOut' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'togglefullscreen' }
|
||||
]
|
||||
},
|
||||
// { role: 'windowMenu' }
|
||||
{
|
||||
label: 'Window',
|
||||
submenu: [
|
||||
{ role: 'minimize' },
|
||||
{ role: 'zoom' },
|
||||
...(isMac ? [
|
||||
{ type: 'separator' },
|
||||
{ role: 'front' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'window' }
|
||||
] : [
|
||||
{ role: 'close' }
|
||||
])
|
||||
]
|
||||
},
|
||||
{
|
||||
role: 'help',
|
||||
submenu: [
|
||||
{
|
||||
label: 'Learn More',
|
||||
click: async () => {
|
||||
const { shell } = require('electron')
|
||||
await shell.openExternal('https://electronjs.org')
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
const menu = Menu.buildFromTemplate(template)
|
||||
Menu.setApplicationMenu(menu)
|
||||
```
|
||||
|
||||
### Render process
|
||||
|
||||
To create menus initiated by the renderer process, send the required
|
||||
information to the main process using IPC and have the main process display the
|
||||
menu on behalf of the renderer.
|
||||
|
||||
Below is an example of showing a menu when the user right clicks the page:
|
||||
|
||||
```js
|
||||
// renderer
|
||||
window.addEventListener('contextmenu', (e) => {
|
||||
e.preventDefault()
|
||||
ipcRenderer.send('show-context-menu')
|
||||
})
|
||||
|
||||
ipcRenderer.on('context-menu-command', (e, command) => {
|
||||
// ...
|
||||
})
|
||||
|
||||
// main
|
||||
ipcMain.on('show-context-menu', (event) => {
|
||||
const template = [
|
||||
{
|
||||
label: 'Menu Item 1',
|
||||
click: () => { event.sender.send('context-menu-command', 'menu-item-1') }
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{ label: 'Menu Item 2', type: 'checkbox', checked: true }
|
||||
]
|
||||
const menu = Menu.buildFromTemplate(template)
|
||||
menu.popup(BrowserWindow.fromWebContents(event.sender))
|
||||
})
|
||||
```
|
||||
|
||||
## Notes on macOS Application Menu
|
||||
|
||||
macOS has a completely different style of application menu from Windows and
|
||||
Linux. Here are some notes on making your app's menu more native-like.
|
||||
|
||||
### Standard Menus
|
||||
|
||||
On macOS there are many system-defined standard menus, like the [`Services`](https://developer.apple.com/documentation/appkit/nsapplication/1428608-servicesmenu?language=objc) and
|
||||
`Windows` menus. To make your menu a standard menu, you should set your menu's
|
||||
`role` to one of the following and Electron will recognize them and make them
|
||||
become standard menus:
|
||||
|
||||
* `window`
|
||||
* `help`
|
||||
* `services`
|
||||
|
||||
### Standard Menu Item Actions
|
||||
|
||||
macOS has provided standard actions for some menu items, like `About xxx`,
|
||||
`Hide xxx`, and `Hide Others`. To set the action of a menu item to a standard
|
||||
action, you should set the `role` attribute of the menu item.
|
||||
|
||||
### Main Menu's Name
|
||||
|
||||
On macOS the label of the application menu's first item is always your app's
|
||||
name, no matter what label you set. To change it, modify your app bundle's
|
||||
`Info.plist` file. See
|
||||
[About Information Property List Files][AboutInformationPropertyListFiles]
|
||||
for more information.
|
||||
|
||||
## Setting Menu for Specific Browser Window (*Linux* *Windows*)
|
||||
|
||||
The [`setMenu` method][setMenu] of browser windows can set the menu of certain
|
||||
browser windows.
|
||||
|
||||
## Menu Item Position
|
||||
|
||||
You can make use of `before`, `after`, `beforeGroupContaining`, `afterGroupContaining` and `id` to control how the item will be placed when building a menu with `Menu.buildFromTemplate`.
|
||||
|
||||
* `before` - Inserts this item before the item with the specified label. If the
|
||||
referenced item doesn't exist the item will be inserted at the end of
|
||||
the menu. Also implies that the menu item in question should be placed in the same “group” as the item.
|
||||
* `after` - Inserts this item after the item with the specified label. If the
|
||||
referenced item doesn't exist the item will be inserted at the end of
|
||||
the menu. Also implies that the menu item in question should be placed in the same “group” as the item.
|
||||
* `beforeGroupContaining` - Provides a means for a single context menu to declare
|
||||
the placement of their containing group before the containing group of the item with the specified label.
|
||||
* `afterGroupContaining` - Provides a means for a single context menu to declare
|
||||
the placement of their containing group after the containing group of the item with the specified label.
|
||||
|
||||
By default, items will be inserted in the order they exist in the template unless one of the specified positioning keywords is used.
|
||||
|
||||
### Examples
|
||||
|
||||
Template:
|
||||
|
||||
```javascript
|
||||
[
|
||||
{ id: '1', label: 'one' },
|
||||
{ id: '2', label: 'two' },
|
||||
{ id: '3', label: 'three' },
|
||||
{ id: '4', label: 'four' }
|
||||
]
|
||||
```
|
||||
|
||||
Menu:
|
||||
|
||||
```sh
|
||||
- 1
|
||||
- 2
|
||||
- 3
|
||||
- 4
|
||||
```
|
||||
|
||||
Template:
|
||||
|
||||
```javascript
|
||||
[
|
||||
{ id: '1', label: 'one' },
|
||||
{ type: 'separator' },
|
||||
{ id: '3', label: 'three', beforeGroupContaining: ['1'] },
|
||||
{ id: '4', label: 'four', afterGroupContaining: ['2'] },
|
||||
{ type: 'separator' },
|
||||
{ id: '2', label: 'two' }
|
||||
]
|
||||
```
|
||||
|
||||
Menu:
|
||||
|
||||
```sh
|
||||
- 3
|
||||
- 4
|
||||
- ---
|
||||
- 1
|
||||
- ---
|
||||
- 2
|
||||
```
|
||||
|
||||
Template:
|
||||
|
||||
```javascript
|
||||
[
|
||||
{ id: '1', label: 'one', after: ['3'] },
|
||||
{ id: '2', label: 'two', before: ['1'] },
|
||||
{ id: '3', label: 'three' }
|
||||
]
|
||||
```
|
||||
|
||||
Menu:
|
||||
|
||||
```sh
|
||||
- ---
|
||||
- 3
|
||||
- 2
|
||||
- 1
|
||||
```
|
||||
|
||||
[AboutInformationPropertyListFiles]: https://developer.apple.com/library/ios/documentation/general/Reference/InfoPlistKeyReference/Articles/AboutInformationPropertyListFiles.html
|
||||
[setMenu]: latest/api/browser-window.md#winsetmenumenu-linux-windows
|
|
@ -0,0 +1,53 @@
|
|||
---
|
||||
title: "MessageChannelMain"
|
||||
description: "MessageChannelMain is the main-process-side equivalent of the DOM MessageChannel object. Its singular function is to create a pair of connected MessagePortMain objects."
|
||||
slug: message-channel-main
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# MessageChannelMain
|
||||
|
||||
`MessageChannelMain` is the main-process-side equivalent of the DOM
|
||||
[`MessageChannel`][] object. Its singular function is to create a pair of
|
||||
connected [`MessagePortMain`](latest/api/message-port-main.md) objects.
|
||||
|
||||
See the [Channel Messaging API][] documentation for more information on using
|
||||
channel messaging.
|
||||
|
||||
## Class: MessageChannelMain
|
||||
|
||||
> Channel interface for channel messaging in the main process.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
// Main process
|
||||
const { MessageChannelMain } = require('electron')
|
||||
const { port1, port2 } = new MessageChannelMain()
|
||||
w.webContents.postMessage('port', null, [port2])
|
||||
port1.postMessage({ some: 'message' })
|
||||
|
||||
// Renderer process
|
||||
const { ipcRenderer } = require('electron')
|
||||
ipcRenderer.on('port', (e) => {
|
||||
// e.ports is a list of ports sent along with this message
|
||||
e.ports[0].on('message', (messageEvent) => {
|
||||
console.log(messageEvent.data)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
### Instance Properties
|
||||
|
||||
#### `channel.port1`
|
||||
|
||||
A [`MessagePortMain`](latest/api/message-port-main.md) property.
|
||||
|
||||
#### `channel.port2`
|
||||
|
||||
A [`MessagePortMain`](latest/api/message-port-main.md) property.
|
||||
|
||||
[`MessageChannel`]: https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel
|
||||
[Channel Messaging API]: https://developer.mozilla.org/en-US/docs/Web/API/Channel_Messaging_API
|
|
@ -0,0 +1,65 @@
|
|||
---
|
||||
title: "MessagePortMain"
|
||||
description: "MessagePortMain is the main-process-side equivalent of the DOM MessagePort object. It behaves similarly to the DOM version, with the exception that it uses the Node.js EventEmitter event system, instead of the DOM EventTarget system. This means you should use port.on('message', ...) to listen for events, instead of port.onmessage = ... or port.addEventListener('message', ...)"
|
||||
slug: message-port-main
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# MessagePortMain
|
||||
|
||||
`MessagePortMain` is the main-process-side equivalent of the DOM
|
||||
[`MessagePort`][] object. It behaves similarly to the DOM version, with the
|
||||
exception that it uses the Node.js `EventEmitter` event system, instead of the
|
||||
DOM `EventTarget` system. This means you should use `port.on('message', ...)`
|
||||
to listen for events, instead of `port.onmessage = ...` or
|
||||
`port.addEventListener('message', ...)`
|
||||
|
||||
See the [Channel Messaging API][] documentation for more information on using
|
||||
channel messaging.
|
||||
|
||||
`MessagePortMain` is an [EventEmitter][event-emitter].
|
||||
|
||||
## Class: MessagePortMain
|
||||
|
||||
> Port interface for channel messaging in the main process.
|
||||
|
||||
Process: [Main](latest/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
|
||||
|
||||
#### `port.postMessage(message, [transfer])`
|
||||
|
||||
* `message` any
|
||||
* `transfer` MessagePortMain[] (optional)
|
||||
|
||||
Sends a message from the port, and optionally, transfers ownership of objects
|
||||
to other browsing contexts.
|
||||
|
||||
#### `port.start()`
|
||||
|
||||
Starts the sending of messages queued on the port. Messages will be queued
|
||||
until this method is called.
|
||||
|
||||
#### `port.close()`
|
||||
|
||||
Disconnects the port, so it is no longer active.
|
||||
|
||||
### Instance Events
|
||||
|
||||
#### Event: 'message'
|
||||
|
||||
Returns:
|
||||
|
||||
* `messageEvent` Object
|
||||
* `data` any
|
||||
* `ports` MessagePortMain[]
|
||||
|
||||
Emitted when a MessagePortMain object receives a message.
|
||||
|
||||
#### Event: 'close'
|
||||
|
||||
Emitted when the remote end of a MessagePortMain object becomes disconnected.
|
||||
|
||||
[`MessagePort`]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort
|
||||
[Channel Messaging API]: https://developer.mozilla.org/en-US/docs/Web/API/Channel_Messaging_API
|
|
@ -0,0 +1,361 @@
|
|||
---
|
||||
title: "nativeImage"
|
||||
description: "Create tray, dock, and application icons using PNG or JPG files."
|
||||
slug: native-image
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# nativeImage
|
||||
|
||||
> Create tray, dock, and application icons using PNG or JPG files.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process), [Renderer](latest/glossary.md#renderer-process)
|
||||
|
||||
In Electron, for the APIs that take images, you can pass either file paths or
|
||||
`NativeImage` instances. An empty image will be used when `null` is passed.
|
||||
|
||||
For example, when creating a tray or setting a window's icon, you can pass an
|
||||
image file path as a `String`:
|
||||
|
||||
```javascript
|
||||
const { BrowserWindow, Tray } = require('electron')
|
||||
|
||||
const appIcon = new Tray('/Users/somebody/images/icon.png')
|
||||
const win = new BrowserWindow({ icon: '/Users/somebody/images/window.png' })
|
||||
console.log(appIcon, win)
|
||||
```
|
||||
|
||||
Or read the image from the clipboard, which returns a `NativeImage`:
|
||||
|
||||
```javascript
|
||||
const { clipboard, Tray } = require('electron')
|
||||
const image = clipboard.readImage()
|
||||
const appIcon = new Tray(image)
|
||||
console.log(appIcon)
|
||||
```
|
||||
|
||||
## Supported Formats
|
||||
|
||||
Currently `PNG` and `JPEG` image formats are supported. `PNG` is recommended
|
||||
because of its support for transparency and lossless compression.
|
||||
|
||||
On Windows, you can also load `ICO` icons from file paths. For best visual
|
||||
quality, it is recommended to include at least the following sizes in the:
|
||||
|
||||
* Small icon
|
||||
* 16x16 (100% DPI scale)
|
||||
* 20x20 (125% DPI scale)
|
||||
* 24x24 (150% DPI scale)
|
||||
* 32x32 (200% DPI scale)
|
||||
* Large icon
|
||||
* 32x32 (100% DPI scale)
|
||||
* 40x40 (125% DPI scale)
|
||||
* 48x48 (150% DPI scale)
|
||||
* 64x64 (200% DPI scale)
|
||||
* 256x256
|
||||
|
||||
Check the *Size requirements* section in [this article][icons].
|
||||
|
||||
[icons]:https://msdn.microsoft.com/en-us/library/windows/desktop/dn742485(v=vs.85).aspx
|
||||
|
||||
## High Resolution Image
|
||||
|
||||
On platforms that have high-DPI support such as Apple Retina displays, you can
|
||||
append `@2x` after image's base filename to mark it as a high resolution image.
|
||||
|
||||
For example, if `icon.png` is a normal image that has standard resolution, then
|
||||
`icon@2x.png` will be treated as a high resolution image that has double DPI
|
||||
density.
|
||||
|
||||
If you want to support displays with different DPI densities at the same time,
|
||||
you can put images with different sizes in the same folder and use the filename
|
||||
without DPI suffixes. For example:
|
||||
|
||||
```plaintext
|
||||
images/
|
||||
├── icon.png
|
||||
├── icon@2x.png
|
||||
└── icon@3x.png
|
||||
```
|
||||
|
||||
```javascript
|
||||
const { Tray } = require('electron')
|
||||
const appIcon = new Tray('/Users/somebody/images/icon.png')
|
||||
console.log(appIcon)
|
||||
```
|
||||
|
||||
The following suffixes for DPI are also supported:
|
||||
|
||||
* `@1x`
|
||||
* `@1.25x`
|
||||
* `@1.33x`
|
||||
* `@1.4x`
|
||||
* `@1.5x`
|
||||
* `@1.8x`
|
||||
* `@2x`
|
||||
* `@2.5x`
|
||||
* `@3x`
|
||||
* `@4x`
|
||||
* `@5x`
|
||||
|
||||
## Template Image
|
||||
|
||||
Template images consist of black and an alpha channel.
|
||||
Template images are not intended to be used as standalone images and are usually
|
||||
mixed with other content to create the desired final appearance.
|
||||
|
||||
The most common case is to use template images for a menu bar icon, so it can
|
||||
adapt to both light and dark menu bars.
|
||||
|
||||
**Note:** Template image is only supported on macOS.
|
||||
|
||||
To mark an image as a template image, its filename should end with the word
|
||||
`Template`. For example:
|
||||
|
||||
* `xxxTemplate.png`
|
||||
* `xxxTemplate@2x.png`
|
||||
|
||||
## Methods
|
||||
|
||||
The `nativeImage` module has the following methods, all of which return
|
||||
an instance of the `NativeImage` class:
|
||||
|
||||
### `nativeImage.createEmpty()`
|
||||
|
||||
Returns `NativeImage`
|
||||
|
||||
Creates an empty `NativeImage` instance.
|
||||
|
||||
### `nativeImage.createThumbnailFromPath(path, maxSize)` _macOS_ _Windows_
|
||||
|
||||
* `path` String - path to a file that we intend to construct a thumbnail out of.
|
||||
* `maxSize` [Size](latest/api/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](latest/api/native-image.md).
|
||||
|
||||
### `nativeImage.createFromPath(path)`
|
||||
|
||||
* `path` String
|
||||
|
||||
Returns `NativeImage`
|
||||
|
||||
Creates a new `NativeImage` instance from a file located at `path`. This method
|
||||
returns an empty image if the `path` does not exist, cannot be read, or is not
|
||||
a valid image.
|
||||
|
||||
```javascript
|
||||
const nativeImage = require('electron').nativeImage
|
||||
|
||||
const image = nativeImage.createFromPath('/Users/somebody/images/icon.png')
|
||||
console.log(image)
|
||||
```
|
||||
|
||||
### `nativeImage.createFromBitmap(buffer, options)`
|
||||
|
||||
* `buffer` [Buffer][buffer]
|
||||
* `options` Object
|
||||
* `width` Integer
|
||||
* `height` Integer
|
||||
* `scaleFactor` Double (optional) - Defaults to 1.0.
|
||||
|
||||
Returns `NativeImage`
|
||||
|
||||
Creates a new `NativeImage` instance from `buffer` that contains the raw bitmap
|
||||
pixel data returned by `toBitmap()`. The specific format is platform-dependent.
|
||||
|
||||
### `nativeImage.createFromBuffer(buffer[, options])`
|
||||
|
||||
* `buffer` [Buffer][buffer]
|
||||
* `options` Object (optional)
|
||||
* `width` Integer (optional) - Required for bitmap buffers.
|
||||
* `height` Integer (optional) - Required for bitmap buffers.
|
||||
* `scaleFactor` Double (optional) - Defaults to 1.0.
|
||||
|
||||
Returns `NativeImage`
|
||||
|
||||
Creates a new `NativeImage` instance from `buffer`. Tries to decode as PNG or JPEG first.
|
||||
|
||||
### `nativeImage.createFromDataURL(dataURL)`
|
||||
|
||||
* `dataURL` String
|
||||
|
||||
Returns `NativeImage`
|
||||
|
||||
Creates a new `NativeImage` instance from `dataURL`.
|
||||
|
||||
### `nativeImage.createFromNamedImage(imageName[, hslShift])` _macOS_
|
||||
|
||||
* `imageName` String
|
||||
* `hslShift` Number[] (optional)
|
||||
|
||||
Returns `NativeImage`
|
||||
|
||||
Creates a new `NativeImage` instance from the NSImage that maps to the
|
||||
given image name. See [`System Icons`](https://developer.apple.com/design/human-interface-guidelines/macos/icons-and-images/system-icons/)
|
||||
for a list of possible values.
|
||||
|
||||
The `hslShift` is applied to the image with the following rules:
|
||||
|
||||
* `hsl_shift[0]` (hue): The absolute hue value for the image - 0 and 1 map
|
||||
to 0 and 360 on the hue color wheel (red).
|
||||
* `hsl_shift[1]` (saturation): A saturation shift for the image, with the
|
||||
following key values:
|
||||
0 = remove all color.
|
||||
0.5 = leave unchanged.
|
||||
1 = fully saturate the image.
|
||||
* `hsl_shift[2]` (lightness): A lightness shift for the image, with the
|
||||
following key values:
|
||||
0 = remove all lightness (make all pixels black).
|
||||
0.5 = leave unchanged.
|
||||
1 = full lightness (make all pixels white).
|
||||
|
||||
This means that `[-1, 0, 1]` will make the image completely white and
|
||||
`[-1, 1, 0]` will make the image completely black.
|
||||
|
||||
In some cases, the `NSImageName` doesn't match its string representation; one example of this is `NSFolderImageName`, whose string representation would actually be `NSFolder`. Therefore, you'll need to determine the correct string representation for your image before passing it in. This can be done with the following:
|
||||
|
||||
`echo -e '#import <Cocoa/Cocoa.h>\nint main() { NSLog(@"%@", SYSTEM_IMAGE_NAME); }' | clang -otest -x objective-c -framework Cocoa - && ./test`
|
||||
|
||||
where `SYSTEM_IMAGE_NAME` should be replaced with any value from [this list](https://developer.apple.com/documentation/appkit/nsimagename?language=objc).
|
||||
|
||||
## Class: NativeImage
|
||||
|
||||
> Natively wrap images such as tray, dock, and application icons.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process), [Renderer](latest/glossary.md#renderer-process)<br />
|
||||
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._
|
||||
|
||||
### Instance Methods
|
||||
|
||||
The following methods are available on instances of the `NativeImage` class:
|
||||
|
||||
#### `image.toPNG([options])`
|
||||
|
||||
* `options` Object (optional)
|
||||
* `scaleFactor` Double (optional) - Defaults to 1.0.
|
||||
|
||||
Returns `Buffer` - A [Buffer][buffer] that contains the image's `PNG` encoded data.
|
||||
|
||||
#### `image.toJPEG(quality)`
|
||||
|
||||
* `quality` Integer - Between 0 - 100.
|
||||
|
||||
Returns `Buffer` - A [Buffer][buffer] that contains the image's `JPEG` encoded data.
|
||||
|
||||
#### `image.toBitmap([options])`
|
||||
|
||||
* `options` Object (optional)
|
||||
* `scaleFactor` Double (optional) - Defaults to 1.0.
|
||||
|
||||
Returns `Buffer` - A [Buffer][buffer] that contains a copy of the image's raw bitmap pixel
|
||||
data.
|
||||
|
||||
#### `image.toDataURL([options])`
|
||||
|
||||
* `options` Object (optional)
|
||||
* `scaleFactor` Double (optional) - Defaults to 1.0.
|
||||
|
||||
Returns `String` - The data URL of the image.
|
||||
|
||||
#### `image.getBitmap([options])`
|
||||
|
||||
* `options` Object (optional)
|
||||
* `scaleFactor` Double (optional) - Defaults to 1.0.
|
||||
|
||||
Returns `Buffer` - A [Buffer][buffer] that contains the image's raw bitmap pixel data.
|
||||
|
||||
The difference between `getBitmap()` and `toBitmap()` is that `getBitmap()` does not
|
||||
copy the bitmap data, so you have to use the returned Buffer immediately in
|
||||
current event loop tick; otherwise the data might be changed or destroyed.
|
||||
|
||||
#### `image.getNativeHandle()` _macOS_
|
||||
|
||||
Returns `Buffer` - A [Buffer][buffer] that stores C pointer to underlying native handle of
|
||||
the image. On macOS, a pointer to `NSImage` instance would be returned.
|
||||
|
||||
Notice that the returned pointer is a weak pointer to the underlying native
|
||||
image instead of a copy, so you _must_ ensure that the associated
|
||||
`nativeImage` instance is kept around.
|
||||
|
||||
#### `image.isEmpty()`
|
||||
|
||||
Returns `Boolean` - Whether the image is empty.
|
||||
|
||||
#### `image.getSize([scaleFactor])`
|
||||
|
||||
* `scaleFactor` Double (optional) - Defaults to 1.0.
|
||||
|
||||
Returns [`Size`](latest/api/structures/size.md).
|
||||
|
||||
If `scaleFactor` is passed, this will return the size corresponding to the image representation most closely matching the passed value.
|
||||
|
||||
#### `image.setTemplateImage(option)`
|
||||
|
||||
* `option` Boolean
|
||||
|
||||
Marks the image as a template image.
|
||||
|
||||
#### `image.isTemplateImage()`
|
||||
|
||||
Returns `Boolean` - Whether the image is a template image.
|
||||
|
||||
#### `image.crop(rect)`
|
||||
|
||||
* `rect` [Rectangle](latest/api/structures/rectangle.md) - The area of the image to crop.
|
||||
|
||||
Returns `NativeImage` - The cropped image.
|
||||
|
||||
#### `image.resize(options)`
|
||||
|
||||
* `options` Object
|
||||
* `width` Integer (optional) - Defaults to the image's width.
|
||||
* `height` Integer (optional) - Defaults to the image's height.
|
||||
* `quality` String (optional) - The desired quality of the resize image.
|
||||
Possible values are `good`, `better`, or `best`. The default is `best`.
|
||||
These values express a desired quality/speed tradeoff. They are translated
|
||||
into an algorithm-specific method that depends on the capabilities
|
||||
(CPU, GPU) of the underlying platform. It is possible for all three methods
|
||||
to be mapped to the same algorithm on a given platform.
|
||||
|
||||
Returns `NativeImage` - The resized image.
|
||||
|
||||
If only the `height` or the `width` are specified then the current aspect ratio
|
||||
will be preserved in the resized image.
|
||||
|
||||
#### `image.getAspectRatio([scaleFactor])`
|
||||
|
||||
* `scaleFactor` 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.
|
||||
|
||||
#### `image.addRepresentation(options)`
|
||||
|
||||
* `options` Object
|
||||
* `scaleFactor` Double - The scale factor to add the image representation for.
|
||||
* `width` Integer (optional) - Defaults to 0. Required if a bitmap buffer
|
||||
is specified as `buffer`.
|
||||
* `height` Integer (optional) - Defaults to 0. Required if a bitmap buffer
|
||||
is specified as `buffer`.
|
||||
* `buffer` Buffer (optional) - The buffer containing the raw image data.
|
||||
* `dataURL` String (optional) - The data URL containing either a base 64
|
||||
encoded PNG or JPEG image.
|
||||
|
||||
Add an image representation for a specific scale factor. This can be used
|
||||
to explicitly add different scale factor representations to an image. This
|
||||
can be called on empty images.
|
||||
|
||||
[buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer
|
||||
|
||||
### Instance Properties
|
||||
|
||||
#### `nativeImage.isMacTemplateImage` _macOS_
|
||||
|
||||
A `Boolean` property that determines whether the image is considered a [template image](https://developer.apple.com/documentation/appkit/nsimage/1520017-template).
|
||||
|
||||
Please note that this property only has an effect on macOS.
|
|
@ -0,0 +1,76 @@
|
|||
---
|
||||
title: "nativeTheme"
|
||||
description: "Read and respond to changes in Chromium's native color theme."
|
||||
slug: native-theme
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# nativeTheme
|
||||
|
||||
> Read and respond to changes in Chromium's native color theme.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
## Events
|
||||
|
||||
The `nativeTheme` module emits the following events:
|
||||
|
||||
### Event: 'updated'
|
||||
|
||||
Emitted when something in the underlying NativeTheme has changed. This normally
|
||||
means that either the value of `shouldUseDarkColors`,
|
||||
`shouldUseHighContrastColors` or `shouldUseInvertedColorScheme` has changed.
|
||||
You will have to check them to determine which one has changed.
|
||||
|
||||
## Properties
|
||||
|
||||
The `nativeTheme` module has the following properties:
|
||||
|
||||
### `nativeTheme.shouldUseDarkColors` _Readonly_
|
||||
|
||||
A `Boolean` for if the OS / Chromium currently has a dark mode enabled or is
|
||||
being instructed to show a dark-style UI. If you want to modify this value you
|
||||
should use `themeSource` below.
|
||||
|
||||
### `nativeTheme.themeSource`
|
||||
|
||||
A `String` property that can be `system`, `light` or `dark`. It is used to override and supersede
|
||||
the value that Chromium has chosen to use internally.
|
||||
|
||||
Setting this property to `system` will remove the override and
|
||||
everything will be reset to the OS default. By default `themeSource` is `system`.
|
||||
|
||||
Settings this property to `dark` will have the following effects:
|
||||
|
||||
* `nativeTheme.shouldUseDarkColors` will be `true` when accessed
|
||||
* Any UI Electron renders on Linux and Windows including context menus, devtools, etc. will use the dark UI.
|
||||
* Any UI the OS renders on macOS including menus, window frames, etc. will use the dark UI.
|
||||
* The [`prefers-color-scheme`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) CSS query will match `dark` mode.
|
||||
* The `updated` event will be emitted
|
||||
|
||||
Settings this property to `light` will have the following effects:
|
||||
|
||||
* `nativeTheme.shouldUseDarkColors` will be `false` when accessed
|
||||
* Any UI Electron renders on Linux and Windows including context menus, devtools, etc. will use the light UI.
|
||||
* Any UI the OS renders on macOS including menus, window frames, etc. will use the light UI.
|
||||
* The [`prefers-color-scheme`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) CSS query will match `light` mode.
|
||||
* The `updated` event will be emitted
|
||||
|
||||
The usage of this property should align with a classic "dark mode" state machine in your application
|
||||
where the user has three options.
|
||||
|
||||
* `Follow OS` --> `themeSource = 'system'`
|
||||
* `Dark Mode` --> `themeSource = 'dark'`
|
||||
* `Light Mode` --> `themeSource = 'light'`
|
||||
|
||||
Your application should then always use `shouldUseDarkColors` to determine what CSS to apply.
|
||||
|
||||
### `nativeTheme.shouldUseHighContrastColors` _macOS_ _Windows_ _Readonly_
|
||||
|
||||
A `Boolean` for if the OS / Chromium currently has high-contrast mode enabled
|
||||
or is being instructed to show a high-contrast UI.
|
||||
|
||||
### `nativeTheme.shouldUseInvertedColorScheme` _macOS_ _Windows_ _Readonly_
|
||||
|
||||
A `Boolean` for if the OS / Chromium currently has an inverted color scheme
|
||||
or is being instructed to use an inverted color scheme.
|
|
@ -0,0 +1,58 @@
|
|||
---
|
||||
title: "netLog"
|
||||
description: "Logging network events for a session."
|
||||
slug: net-log
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# netLog
|
||||
|
||||
> Logging network events for a session.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
```javascript
|
||||
const { netLog } = require('electron')
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
await netLog.startLogging('/path/to/net-log')
|
||||
// After some network events
|
||||
const path = await netLog.stopLogging()
|
||||
console.log('Net-logs written to', path)
|
||||
})
|
||||
```
|
||||
|
||||
See [`--log-net-log`](latest/api/command-line-switches.md#--log-net-logpath) to log network events throughout the app's lifecycle.
|
||||
|
||||
**Note:** All methods unless specified can only be used after the `ready` event
|
||||
of the `app` module gets emitted.
|
||||
|
||||
## Methods
|
||||
|
||||
### `netLog.startLogging(path[, options])`
|
||||
|
||||
* `path` String - File path to record network logs.
|
||||
* `options` Object (optional)
|
||||
* `captureMode` String (optional) - What kinds of data should be captured. By
|
||||
default, only metadata about requests will be captured. Setting this to
|
||||
`includeSensitive` will include cookies and authentication data. Setting
|
||||
it to `everything` will include all bytes transferred on sockets. Can be
|
||||
`default`, `includeSensitive` or `everything`.
|
||||
* `maxFileSize` Number (optional) - When the log grows beyond this size,
|
||||
logging will automatically stop. Defaults to unlimited.
|
||||
|
||||
Returns `Promise<void>` - resolves when the net log has begun recording.
|
||||
|
||||
Starts recording network events to `path`.
|
||||
|
||||
### `netLog.stopLogging()`
|
||||
|
||||
Returns `Promise<void>` - resolves when the net log has been flushed to disk.
|
||||
|
||||
Stops recording network events. If not called, net logging will automatically end when app quits.
|
||||
|
||||
## Properties
|
||||
|
||||
### `netLog.currentlyLogging` _Readonly_
|
||||
|
||||
A `Boolean` property that indicates whether network logs are currently being recorded.
|
|
@ -0,0 +1,93 @@
|
|||
---
|
||||
title: "net"
|
||||
description: "Issue HTTP/HTTPS requests using Chromium's native networking library"
|
||||
slug: net
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# net
|
||||
|
||||
> Issue HTTP/HTTPS requests using Chromium's native networking library
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
The `net` module is a client-side API for issuing HTTP(S) requests. It is
|
||||
similar to the [HTTP](https://nodejs.org/api/http.html) and
|
||||
[HTTPS](https://nodejs.org/api/https.html) modules of Node.js but uses
|
||||
Chromium's native networking library instead of the Node.js implementation,
|
||||
offering better support for web proxies. It also supports checking network status.
|
||||
|
||||
The following is a non-exhaustive list of why you may consider using the `net`
|
||||
module instead of the native Node.js modules:
|
||||
|
||||
* Automatic management of system proxy configuration, support of the wpad
|
||||
protocol and proxy pac configuration files.
|
||||
* Automatic tunneling of HTTPS requests.
|
||||
* Support for authenticating proxies using basic, digest, NTLM, Kerberos or
|
||||
negotiate authentication schemes.
|
||||
* Support for traffic monitoring proxies: Fiddler-like proxies used for access
|
||||
control and monitoring.
|
||||
|
||||
The API components (including classes, methods, properties and event names) are similar to those used in
|
||||
Node.js.
|
||||
|
||||
Example usage:
|
||||
|
||||
```javascript
|
||||
const { app } = require('electron')
|
||||
app.whenReady().then(() => {
|
||||
const { net } = require('electron')
|
||||
const request = net.request('https://github.com')
|
||||
request.on('response', (response) => {
|
||||
console.log(`STATUS: ${response.statusCode}`)
|
||||
console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
|
||||
response.on('data', (chunk) => {
|
||||
console.log(`BODY: ${chunk}`)
|
||||
})
|
||||
response.on('end', () => {
|
||||
console.log('No more data in response.')
|
||||
})
|
||||
})
|
||||
request.end()
|
||||
})
|
||||
```
|
||||
|
||||
The `net` API can be used only after the application emits the `ready` event.
|
||||
Trying to use the module before the `ready` event will throw an error.
|
||||
|
||||
## Methods
|
||||
|
||||
The `net` module has the following methods:
|
||||
|
||||
### `net.request(options)`
|
||||
|
||||
* `options` (ClientRequestConstructorOptions | String) - The `ClientRequest` constructor options.
|
||||
|
||||
Returns [`ClientRequest`](latest/api/client-request.md)
|
||||
|
||||
Creates a [`ClientRequest`](latest/api/client-request.md) instance using the provided
|
||||
`options` which are directly forwarded to the `ClientRequest` constructor.
|
||||
The `net.request` method would be used to issue both secure and insecure HTTP
|
||||
requests according to the specified protocol scheme in the `options` object.
|
||||
|
||||
### `net.isOnline()`
|
||||
|
||||
Returns `Boolean` - Whether there is currently internet connection.
|
||||
|
||||
A return value of `false` is a pretty strong indicator that the user
|
||||
won't be able to connect to remote sites. However, a return value of
|
||||
`true` is inconclusive; even if some link is up, it is uncertain
|
||||
whether a particular connection attempt to a particular remote site
|
||||
will be successful.
|
||||
|
||||
## Properties
|
||||
|
||||
### `net.online` _Readonly_
|
||||
|
||||
A `Boolean` property. Whether there is currently internet connection.
|
||||
|
||||
A return value of `false` is a pretty strong indicator that the user
|
||||
won't be able to connect to remote sites. However, a return value of
|
||||
`true` is inconclusive; even if some link is up, it is uncertain
|
||||
whether a particular connection attempt to a particular remote site
|
||||
will be successful.
|
|
@ -0,0 +1,201 @@
|
|||
---
|
||||
title: "Notification"
|
||||
description: "Create OS desktop notifications"
|
||||
slug: notification
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Notification
|
||||
|
||||
> Create OS desktop notifications
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
## Using in the renderer process
|
||||
|
||||
If you want to show Notifications from a renderer process you should use the [HTML5 Notification API](latest/tutorial/notifications.md)
|
||||
|
||||
## Class: Notification
|
||||
|
||||
> Create OS desktop notifications
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
`Notification` is an [EventEmitter][event-emitter].
|
||||
|
||||
It creates a new `Notification` with native properties as set by the `options`.
|
||||
|
||||
### Static Methods
|
||||
|
||||
The `Notification` class has the following static methods:
|
||||
|
||||
#### `Notification.isSupported()`
|
||||
|
||||
Returns `Boolean` - Whether or not desktop notifications are supported on the current system
|
||||
|
||||
### `new Notification([options])`
|
||||
|
||||
* `options` Object (optional)
|
||||
* `title` String (optional) - A title for the notification, which will be shown at the top of the notification window when it is shown.
|
||||
* `subtitle` String (optional) _macOS_ - A subtitle for the notification, which will be displayed below the title.
|
||||
* `body` String (optional) - The body text of the notification, which will be displayed below the title or subtitle.
|
||||
* `silent` Boolean (optional) - Whether or not to emit an OS notification noise when showing the notification.
|
||||
* `icon` (String | [NativeImage](latest/api/native-image.md)) (optional) - An icon to use in the notification.
|
||||
* `hasReply` Boolean (optional) _macOS_ - Whether or not to add an inline reply option to the notification.
|
||||
* `timeoutType` String (optional) _Linux_ _Windows_ - The timeout duration of the notification. Can be 'default' or 'never'.
|
||||
* `replyPlaceholder` String (optional) _macOS_ - The placeholder to write in the inline reply input field.
|
||||
* `sound` String (optional) _macOS_ - The name of the sound file to play when the notification is shown.
|
||||
* `urgency` String (optional) _Linux_ - The urgency level of the notification. Can be 'normal', 'critical', or 'low'.
|
||||
* `actions` [NotificationAction[]](latest/api/structures/notification-action.md) (optional) _macOS_ - Actions to add to the notification. Please read the available actions and limitations in the `NotificationAction` documentation.
|
||||
* `closeButtonText` String (optional) _macOS_ - A custom title for the close button of an alert. An empty string will cause the default localized text to be used.
|
||||
* `toastXml` String (optional) _Windows_ - A custom description of the Notification on Windows superseding all properties above. Provides full customization of design and behavior of the notification.
|
||||
|
||||
### Instance Events
|
||||
|
||||
Objects created with `new Notification` emit the following events:
|
||||
|
||||
**Note:** Some events are only available on specific operating systems and are
|
||||
labeled as such.
|
||||
|
||||
#### Event: 'show'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
|
||||
Emitted when the notification is shown to the user, note this could be fired
|
||||
multiple times as a notification can be shown multiple times through the
|
||||
`show()` method.
|
||||
|
||||
#### Event: 'click'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
|
||||
Emitted when the notification is clicked by the user.
|
||||
|
||||
#### Event: 'close'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
|
||||
Emitted when the notification is closed by manual intervention from the user.
|
||||
|
||||
This event is not guaranteed to be emitted in all cases where the notification
|
||||
is closed.
|
||||
|
||||
#### Event: 'reply' _macOS_
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `reply` String - The string the user entered into the inline reply field.
|
||||
|
||||
Emitted when the user clicks the "Reply" button on a notification with `hasReply: true`.
|
||||
|
||||
#### Event: 'action' _macOS_
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `index` Number - The index of the action that was activated.
|
||||
|
||||
#### Event: 'failed' _Windows_
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `error` String - The error encountered during execution of the `show()` method.
|
||||
|
||||
Emitted when an error is encountered while creating and showing the native notification.
|
||||
|
||||
### Instance Methods
|
||||
|
||||
Objects created with `new Notification` have the following instance methods:
|
||||
|
||||
#### `notification.show()`
|
||||
|
||||
Immediately shows the notification to the user, please note this means unlike the
|
||||
HTML5 Notification implementation, instantiating a `new Notification` does
|
||||
not immediately show it to the user, you need to call this method before the OS
|
||||
will display it.
|
||||
|
||||
If the notification has been shown before, this method will dismiss the previously
|
||||
shown notification and create a new one with identical properties.
|
||||
|
||||
#### `notification.close()`
|
||||
|
||||
Dismisses the notification.
|
||||
|
||||
### Instance Properties
|
||||
|
||||
#### `notification.title`
|
||||
|
||||
A `String` property representing the title of the notification.
|
||||
|
||||
#### `notification.subtitle`
|
||||
|
||||
A `String` property representing the subtitle of the notification.
|
||||
|
||||
#### `notification.body`
|
||||
|
||||
A `String` property representing the body of the notification.
|
||||
|
||||
#### `notification.replyPlaceholder`
|
||||
|
||||
A `String` property representing the reply placeholder of the notification.
|
||||
|
||||
#### `notification.sound`
|
||||
|
||||
A `String` property representing the sound of the notification.
|
||||
|
||||
#### `notification.closeButtonText`
|
||||
|
||||
A `String` property representing the close button text of the notification.
|
||||
|
||||
#### `notification.silent`
|
||||
|
||||
A `Boolean` property representing whether the notification is silent.
|
||||
|
||||
#### `notification.hasReply`
|
||||
|
||||
A `Boolean` property representing whether the notification has a reply action.
|
||||
|
||||
#### `notification.urgency` _Linux_
|
||||
|
||||
A `String` property representing the urgency level of the notification. Can be 'normal', 'critical', or 'low'.
|
||||
|
||||
Default is 'low' - see [NotifyUrgency](https://developer.gnome.org/notification-spec/#urgency-levels) for more information.
|
||||
|
||||
#### `notification.timeoutType` _Linux_ _Windows_
|
||||
|
||||
A `String` property representing the type of timeout duration for the notification. Can be 'default' or 'never'.
|
||||
|
||||
If `timeoutType` is set to 'never', the notification never expires. It stays open until closed by the calling API or the user.
|
||||
|
||||
#### `notification.actions`
|
||||
|
||||
A [`NotificationAction[]`](latest/api/structures/notification-action.md) property representing the actions of the notification.
|
||||
|
||||
#### `notification.toastXml` _Windows_
|
||||
|
||||
A `String` property representing the custom Toast XML of the notification.
|
||||
|
||||
### Playing Sounds
|
||||
|
||||
On macOS, you can specify the name of the sound you'd like to play when the
|
||||
notification is shown. Any of the default sounds (under System Preferences >
|
||||
Sound) can be used, in addition to custom sound files. Be sure that the sound
|
||||
file is copied under the app bundle (e.g., `YourApp.app/Contents/Resources`),
|
||||
or one of the following locations:
|
||||
|
||||
* `~/Library/Sounds`
|
||||
* `/Library/Sounds`
|
||||
* `/Network/Library/Sounds`
|
||||
* `/System/Library/Sounds`
|
||||
|
||||
See the [`NSSound`](https://developer.apple.com/documentation/appkit/nssound) docs for more information.
|
||||
|
||||
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
|
|
@ -0,0 +1,89 @@
|
|||
---
|
||||
title: "powerMonitor"
|
||||
description: "Monitor power state changes."
|
||||
slug: power-monitor
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# powerMonitor
|
||||
|
||||
> Monitor power state changes.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
## Events
|
||||
|
||||
The `powerMonitor` module emits the following events:
|
||||
|
||||
### Event: 'suspend'
|
||||
|
||||
Emitted when the system is suspending.
|
||||
|
||||
### Event: 'resume'
|
||||
|
||||
Emitted when system is resuming.
|
||||
|
||||
### Event: 'on-ac' _macOS_ _Windows_
|
||||
|
||||
Emitted when the system changes to AC power.
|
||||
|
||||
### Event: 'on-battery' _macOS_ _Windows_
|
||||
|
||||
Emitted when system changes to battery power.
|
||||
|
||||
### Event: 'shutdown' _Linux_ _macOS_
|
||||
|
||||
Emitted when the system is about to reboot or shut down. If the event handler
|
||||
invokes `e.preventDefault()`, Electron will attempt to delay system shutdown in
|
||||
order for the app to exit cleanly. If `e.preventDefault()` is called, the app
|
||||
should exit as soon as possible by calling something like `app.quit()`.
|
||||
|
||||
### Event: 'lock-screen' _macOS_ _Windows_
|
||||
|
||||
Emitted when the system is about to lock the screen.
|
||||
|
||||
### Event: 'unlock-screen' _macOS_ _Windows_
|
||||
|
||||
Emitted as soon as the systems screen is unlocked.
|
||||
|
||||
### Event: 'user-did-become-active' _macOS_
|
||||
|
||||
Emitted when a login session is activated. See [documentation](https://developer.apple.com/documentation/appkit/nsworkspacesessiondidbecomeactivenotification?language=objc) for more information.
|
||||
|
||||
### Event: 'user-did-resign-active' _macOS_
|
||||
|
||||
Emitted when a login session is deactivated. See [documentation](https://developer.apple.com/documentation/appkit/nsworkspacesessiondidresignactivenotification?language=objc) for more information.
|
||||
|
||||
## Methods
|
||||
|
||||
The `powerMonitor` module has the following methods:
|
||||
|
||||
### `powerMonitor.getSystemIdleState(idleThreshold)`
|
||||
|
||||
* `idleThreshold` Integer
|
||||
|
||||
Returns `String` - The system's current state. Can be `active`, `idle`, `locked` or `unknown`.
|
||||
|
||||
Calculate the system idle state. `idleThreshold` is the amount of time (in seconds)
|
||||
before considered idle. `locked` is available on supported systems only.
|
||||
|
||||
### `powerMonitor.getSystemIdleTime()`
|
||||
|
||||
Returns `Integer` - Idle time in seconds
|
||||
|
||||
Calculate system idle time in seconds.
|
||||
|
||||
### `powerMonitor.isOnBatteryPower()`
|
||||
|
||||
Returns `Boolean` - Whether the system is on battery power.
|
||||
|
||||
To monitor for changes in this property, use the `on-battery` and `on-ac`
|
||||
events.
|
||||
|
||||
## Properties
|
||||
|
||||
### `powerMonitor.onBatteryPower`
|
||||
|
||||
A `Boolean` property. True if the system is on battery power.
|
||||
|
||||
See [`powerMonitor.isOnBatteryPower()`](#powermonitorisonbatterypower).
|
|
@ -0,0 +1,63 @@
|
|||
---
|
||||
title: "powerSaveBlocker"
|
||||
description: "Block the system from entering low-power (sleep) mode."
|
||||
slug: power-save-blocker
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# powerSaveBlocker
|
||||
|
||||
> Block the system from entering low-power (sleep) mode.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
For example:
|
||||
|
||||
```javascript
|
||||
const { powerSaveBlocker } = require('electron')
|
||||
|
||||
const id = powerSaveBlocker.start('prevent-display-sleep')
|
||||
console.log(powerSaveBlocker.isStarted(id))
|
||||
|
||||
powerSaveBlocker.stop(id)
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
The `powerSaveBlocker` module has the following methods:
|
||||
|
||||
### `powerSaveBlocker.start(type)`
|
||||
|
||||
* `type` String - Power save blocker type.
|
||||
* `prevent-app-suspension` - Prevent the application from being suspended.
|
||||
Keeps system active but allows screen to be turned off. Example use cases:
|
||||
downloading a file or playing audio.
|
||||
* `prevent-display-sleep` - Prevent the display from going to sleep. Keeps
|
||||
system and screen active. Example use case: playing video.
|
||||
|
||||
Returns `Integer` - The blocker ID that is assigned to this power blocker.
|
||||
|
||||
Starts preventing the system from entering lower-power mode. Returns an integer
|
||||
identifying the power save blocker.
|
||||
|
||||
**Note:** `prevent-display-sleep` has higher precedence over
|
||||
`prevent-app-suspension`. Only the highest precedence type takes effect. In
|
||||
other words, `prevent-display-sleep` always takes precedence over
|
||||
`prevent-app-suspension`.
|
||||
|
||||
For example, an API calling A requests for `prevent-app-suspension`, and
|
||||
another calling B requests for `prevent-display-sleep`. `prevent-display-sleep`
|
||||
will be used until B stops its request. After that, `prevent-app-suspension`
|
||||
is used.
|
||||
|
||||
### `powerSaveBlocker.stop(id)`
|
||||
|
||||
* `id` Integer - The power save blocker id returned by `powerSaveBlocker.start`.
|
||||
|
||||
Stops the specified power save blocker.
|
||||
|
||||
### `powerSaveBlocker.isStarted(id)`
|
||||
|
||||
* `id` Integer - The power save blocker id returned by `powerSaveBlocker.start`.
|
||||
|
||||
Returns `Boolean` - Whether the corresponding `powerSaveBlocker` has started.
|
|
@ -0,0 +1,258 @@
|
|||
---
|
||||
title: "process"
|
||||
description: "Extensions to process object."
|
||||
slug: process
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# process
|
||||
|
||||
> Extensions to process object.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process), [Renderer](latest/glossary.md#renderer-process)
|
||||
|
||||
Electron's `process` object is extended from the
|
||||
[Node.js `process` object](https://nodejs.org/api/process.html).
|
||||
It adds the following events, properties, and methods:
|
||||
|
||||
## Sandbox
|
||||
|
||||
In sandboxed renderers the `process` object contains only a subset of the APIs:
|
||||
|
||||
* `crash()`
|
||||
* `hang()`
|
||||
* `getCreationTime()`
|
||||
* `getHeapStatistics()`
|
||||
* `getBlinkMemoryInfo()`
|
||||
* `getProcessMemoryInfo()`
|
||||
* `getSystemMemoryInfo()`
|
||||
* `getSystemVersion()`
|
||||
* `getCPUUsage()`
|
||||
* `getIOCounters()`
|
||||
* `uptime()`
|
||||
* `argv`
|
||||
* `execPath`
|
||||
* `env`
|
||||
* `pid`
|
||||
* `arch`
|
||||
* `platform`
|
||||
* `sandboxed`
|
||||
* `contextIsolated`
|
||||
* `type`
|
||||
* `version`
|
||||
* `versions`
|
||||
* `mas`
|
||||
* `windowsStore`
|
||||
* `contextId`
|
||||
|
||||
## Events
|
||||
|
||||
### Event: 'loaded'
|
||||
|
||||
Emitted when Electron has loaded its internal initialization script and is
|
||||
beginning to load the web page or the main script.
|
||||
|
||||
## Properties
|
||||
|
||||
### `process.defaultApp` _Readonly_
|
||||
|
||||
A `Boolean`. When app is started by being passed as parameter to the default app, this
|
||||
property is `true` in the main process, otherwise it is `undefined`.
|
||||
|
||||
### `process.isMainFrame` _Readonly_
|
||||
|
||||
A `Boolean`, `true` when the current renderer context is the "main" renderer
|
||||
frame. If you want the ID of the current frame you should use `webFrame.routingId`.
|
||||
|
||||
### `process.mas` _Readonly_
|
||||
|
||||
A `Boolean`. For Mac App Store build, this property is `true`, for other builds it is
|
||||
`undefined`.
|
||||
|
||||
### `process.noAsar`
|
||||
|
||||
A `Boolean` that controls ASAR support inside your application. Setting this to `true`
|
||||
will disable the support for `asar` archives in Node's built-in modules.
|
||||
|
||||
### `process.noDeprecation`
|
||||
|
||||
A `Boolean` that controls whether or not deprecation warnings are printed to `stderr`.
|
||||
Setting this to `true` will silence deprecation warnings. This property is used
|
||||
instead of the `--no-deprecation` command line flag.
|
||||
|
||||
### `process.resourcesPath` _Readonly_
|
||||
|
||||
A `String` representing the path to the resources directory.
|
||||
|
||||
### `process.sandboxed` _Readonly_
|
||||
|
||||
A `Boolean`. When the renderer process is sandboxed, this property is `true`,
|
||||
otherwise it is `undefined`.
|
||||
|
||||
### `process.contextIsolated` _Readonly_
|
||||
|
||||
A `Boolean` that indicates whether the current renderer context has `contextIsolation` enabled.
|
||||
It is `undefined` in the main process.
|
||||
|
||||
### `process.throwDeprecation`
|
||||
|
||||
A `Boolean` that controls whether or not deprecation warnings will be thrown as
|
||||
exceptions. Setting this to `true` will throw errors for deprecations. This
|
||||
property is used instead of the `--throw-deprecation` command line flag.
|
||||
|
||||
### `process.traceDeprecation`
|
||||
|
||||
A `Boolean` that controls whether or not deprecations printed to `stderr` include
|
||||
their stack trace. Setting this to `true` will print stack traces for deprecations.
|
||||
This property is instead of the `--trace-deprecation` command line flag.
|
||||
|
||||
### `process.traceProcessWarnings`
|
||||
|
||||
A `Boolean` that controls whether or not process warnings printed to `stderr` include
|
||||
their stack trace. Setting this to `true` will print stack traces for process warnings
|
||||
(including deprecations). This property is instead of the `--trace-warnings` command
|
||||
line flag.
|
||||
|
||||
### `process.type` _Readonly_
|
||||
|
||||
A `String` representing the current process's type, can be:
|
||||
|
||||
* `browser` - The main process
|
||||
* `renderer` - A renderer process
|
||||
* `worker` - In a web worker
|
||||
|
||||
### `process.versions.chrome` _Readonly_
|
||||
|
||||
A `String` representing Chrome's version string.
|
||||
|
||||
### `process.versions.electron` _Readonly_
|
||||
|
||||
A `String` representing Electron's version string.
|
||||
|
||||
### `process.windowsStore` _Readonly_
|
||||
|
||||
A `Boolean`. If the app is running as a Windows Store app (appx), this property is `true`,
|
||||
for otherwise it is `undefined`.
|
||||
|
||||
### `process.contextId` _Readonly_
|
||||
|
||||
A `String` (optional) representing a globally unique ID of the current JavaScript context.
|
||||
Each frame has its own JavaScript context. When contextIsolation is enabled, the isolated
|
||||
world also has a separate JavaScript context.
|
||||
This property is only available in the renderer process.
|
||||
|
||||
## Methods
|
||||
|
||||
The `process` object has the following methods:
|
||||
|
||||
### `process.crash()`
|
||||
|
||||
Causes the main thread of the current process crash.
|
||||
|
||||
### `process.getCreationTime()`
|
||||
|
||||
Returns `Number | null` - The number of milliseconds since epoch, or `null` if the information is unavailable
|
||||
|
||||
Indicates the creation time of the application.
|
||||
The time is represented as number of milliseconds since epoch. It returns null if it is unable to get the process creation time.
|
||||
|
||||
### `process.getCPUUsage()`
|
||||
|
||||
Returns [`CPUUsage`](latest/api/structures/cpu-usage.md)
|
||||
|
||||
### `process.getIOCounters()` _Windows_ _Linux_
|
||||
|
||||
Returns [`IOCounters`](latest/api/structures/io-counters.md)
|
||||
|
||||
### `process.getHeapStatistics()`
|
||||
|
||||
Returns `Object`:
|
||||
|
||||
* `totalHeapSize` Integer
|
||||
* `totalHeapSizeExecutable` Integer
|
||||
* `totalPhysicalSize` Integer
|
||||
* `totalAvailableSize` Integer
|
||||
* `usedHeapSize` Integer
|
||||
* `heapSizeLimit` Integer
|
||||
* `mallocedMemory` Integer
|
||||
* `peakMallocedMemory` Integer
|
||||
* `doesZapGarbage` Boolean
|
||||
|
||||
Returns an object with V8 heap statistics. Note that all statistics are reported in Kilobytes.
|
||||
|
||||
### `process.getBlinkMemoryInfo()`
|
||||
|
||||
Returns `Object`:
|
||||
|
||||
* `allocated` Integer - Size of all allocated objects in Kilobytes.
|
||||
* `marked` Integer - Size of all marked objects in Kilobytes.
|
||||
* `total` Integer - Total allocated space in Kilobytes.
|
||||
|
||||
Returns an object with Blink memory information.
|
||||
It can be useful for debugging rendering / DOM related memory issues.
|
||||
Note that all values are reported in Kilobytes.
|
||||
|
||||
### `process.getProcessMemoryInfo()`
|
||||
|
||||
Returns `Promise<ProcessMemoryInfo>` - Resolves with a [ProcessMemoryInfo](latest/api/structures/process-memory-info.md)
|
||||
|
||||
Returns an object giving memory usage statistics about the current process. Note
|
||||
that all statistics are reported in Kilobytes.
|
||||
This api should be called after app ready.
|
||||
|
||||
Chromium does not provide `residentSet` value for macOS. This is because macOS
|
||||
performs in-memory compression of pages that haven't been recently used. As a
|
||||
result the resident set size value is not what one would expect. `private` memory
|
||||
is more representative of the actual pre-compression memory usage of the process
|
||||
on macOS.
|
||||
|
||||
### `process.getSystemMemoryInfo()`
|
||||
|
||||
Returns `Object`:
|
||||
|
||||
* `total` Integer - The total amount of physical memory in Kilobytes available to the
|
||||
system.
|
||||
* `free` Integer - The total amount of memory not being used by applications or disk
|
||||
cache.
|
||||
* `swapTotal` Integer _Windows_ _Linux_ - The total amount of swap memory in Kilobytes available to the
|
||||
system.
|
||||
* `swapFree` Integer _Windows_ _Linux_ - The free amount of swap memory in Kilobytes available to the
|
||||
system.
|
||||
|
||||
Returns an object giving memory usage statistics about the entire system. Note
|
||||
that all statistics are reported in Kilobytes.
|
||||
|
||||
### `process.getSystemVersion()`
|
||||
|
||||
Returns `String` - The version of the host operating system.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
const version = process.getSystemVersion()
|
||||
console.log(version)
|
||||
// On macOS -> '10.13.6'
|
||||
// On Windows -> '10.0.17763'
|
||||
// On Linux -> '4.15.0-45-generic'
|
||||
```
|
||||
|
||||
**Note:** It returns the actual operating system version instead of kernel version on macOS unlike `os.release()`.
|
||||
|
||||
### `process.takeHeapSnapshot(filePath)`
|
||||
|
||||
* `filePath` String - Path to the output file.
|
||||
|
||||
Returns `Boolean` - Indicates whether the snapshot has been created successfully.
|
||||
|
||||
Takes a V8 heap snapshot and saves it to `filePath`.
|
||||
|
||||
### `process.hang()`
|
||||
|
||||
Causes the main thread of the current process hang.
|
||||
|
||||
### `process.setFdLimit(maxDescriptors)` _macOS_ _Linux_
|
||||
|
||||
* `maxDescriptors` Integer
|
||||
|
||||
Sets the file descriptor soft limit to `maxDescriptors` or the OS hard
|
||||
limit, whichever is lower for the current process.
|
|
@ -0,0 +1,336 @@
|
|||
---
|
||||
title: "protocol"
|
||||
description: "Register a custom protocol and intercept existing protocol requests."
|
||||
slug: protocol
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# protocol
|
||||
|
||||
> Register a custom protocol and intercept existing protocol requests.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
An example of implementing a protocol that has the same effect as the
|
||||
`file://` protocol:
|
||||
|
||||
```javascript
|
||||
const { app, protocol } = require('electron')
|
||||
const path = require('path')
|
||||
|
||||
app.whenReady().then(() => {
|
||||
protocol.registerFileProtocol('atom', (request, callback) => {
|
||||
const url = request.url.substr(7)
|
||||
callback({ path: path.normalize(`${__dirname}/${url}`) })
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
**Note:** All methods unless specified can only be used after the `ready` event
|
||||
of the `app` module gets emitted.
|
||||
|
||||
## Using `protocol` with a custom `partition` or `session`
|
||||
|
||||
A protocol is registered to a specific Electron [`session`](latest/api/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.
|
||||
|
||||
```javascript
|
||||
const { session, app, protocol } = require('electron')
|
||||
const path = require('path')
|
||||
|
||||
app.whenReady().then(() => {
|
||||
const partition = 'persist:example'
|
||||
const ses = session.fromPartition(partition)
|
||||
|
||||
ses.protocol.registerFileProtocol('atom', (request, callback) => {
|
||||
const url = request.url.substr(7)
|
||||
callback({ path: path.normalize(`${__dirname}/${url}`) })
|
||||
})
|
||||
|
||||
mainWindow = new BrowserWindow({ webPreferences: { partition } })
|
||||
})
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
The `protocol` module has the following methods:
|
||||
|
||||
### `protocol.registerSchemesAsPrivileged(customSchemes)`
|
||||
|
||||
* `customSchemes` [CustomScheme[]](latest/api/structures/custom-scheme.md)
|
||||
|
||||
**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, supports fetch API, and streaming
|
||||
video/audio. Specify a privilege with the value of `true` to enable the capability.
|
||||
|
||||
An example of registering a privileged scheme, that bypasses Content Security
|
||||
Policy:
|
||||
|
||||
```javascript
|
||||
const { protocol } = require('electron')
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
{ scheme: 'foo', privileges: { bypassCSP: true } }
|
||||
])
|
||||
```
|
||||
|
||||
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 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.
|
||||
|
||||
For example when you load following page with custom protocol without
|
||||
registering it as standard scheme, the image will not be loaded because
|
||||
non-standard schemes can not recognize relative URLs:
|
||||
|
||||
```html
|
||||
<body>
|
||||
<img src='test.png'>
|
||||
</body>
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
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
|
||||
expect streaming responses.
|
||||
|
||||
### `protocol.registerFileProtocol(scheme, handler)`
|
||||
|
||||
* `scheme` String
|
||||
* `handler` Function
|
||||
* `request` [ProtocolRequest](latest/api/structures/protocol-request.md)
|
||||
* `callback` Function
|
||||
* `response` (String | [ProtocolResponse](latest/api/structures/protocol-response.md))
|
||||
|
||||
Returns `Boolean` - Whether the protocol was successfully registered
|
||||
|
||||
Registers a protocol of `scheme` that will send a file as the response. The
|
||||
`handler` will be called with `request` and `callback` where `request` is
|
||||
an incoming request for the `scheme`.
|
||||
|
||||
To handle the `request`, the `callback` should be called with either the file's
|
||||
path or an object that has a `path` property, e.g. `callback(filePath)` or
|
||||
`callback({ path: filePath })`. The `filePath` must be an absolute path.
|
||||
|
||||
By default the `scheme` is treated like `http:`, which is parsed differently
|
||||
from protocols that follow the "generic URI syntax" like `file:`.
|
||||
|
||||
### `protocol.registerBufferProtocol(scheme, handler)`
|
||||
|
||||
* `scheme` String
|
||||
* `handler` Function
|
||||
* `request` [ProtocolRequest](latest/api/structures/protocol-request.md)
|
||||
* `callback` Function
|
||||
* `response` (Buffer | [ProtocolResponse](latest/api/structures/protocol-response.md))
|
||||
|
||||
Returns `Boolean` - Whether the protocol was successfully registered
|
||||
|
||||
Registers a protocol of `scheme` that will send a `Buffer` as a response.
|
||||
|
||||
The usage is the same with `registerFileProtocol`, except that the `callback`
|
||||
should be called with either a `Buffer` object or an object that has the `data`
|
||||
property.
|
||||
|
||||
Example:
|
||||
|
||||
```javascript
|
||||
protocol.registerBufferProtocol('atom', (request, callback) => {
|
||||
callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') })
|
||||
})
|
||||
```
|
||||
|
||||
### `protocol.registerStringProtocol(scheme, handler)`
|
||||
|
||||
* `scheme` String
|
||||
* `handler` Function
|
||||
* `request` [ProtocolRequest](latest/api/structures/protocol-request.md)
|
||||
* `callback` Function
|
||||
* `response` (String | [ProtocolResponse](latest/api/structures/protocol-response.md))
|
||||
|
||||
Returns `Boolean` - Whether the protocol was successfully registered
|
||||
|
||||
Registers a protocol of `scheme` that will send a `String` as a response.
|
||||
|
||||
The usage is the same with `registerFileProtocol`, except that the `callback`
|
||||
should be called with either a `String` or an object that has the `data`
|
||||
property.
|
||||
|
||||
### `protocol.registerHttpProtocol(scheme, handler)`
|
||||
|
||||
* `scheme` String
|
||||
* `handler` Function
|
||||
* `request` [ProtocolRequest](latest/api/structures/protocol-request.md)
|
||||
* `callback` Function
|
||||
* `response` ProtocolResponse
|
||||
|
||||
Returns `Boolean` - Whether the protocol was successfully registered
|
||||
|
||||
Registers a protocol of `scheme` that will send an HTTP request as a response.
|
||||
|
||||
The usage is the same with `registerFileProtocol`, except that the `callback`
|
||||
should be called with an object that has the `url` property.
|
||||
|
||||
### `protocol.registerStreamProtocol(scheme, handler)`
|
||||
|
||||
* `scheme` String
|
||||
* `handler` Function
|
||||
* `request` [ProtocolRequest](latest/api/structures/protocol-request.md)
|
||||
* `callback` Function
|
||||
* `response` (ReadableStream | [ProtocolResponse](latest/api/structures/protocol-response.md))
|
||||
|
||||
Returns `Boolean` - Whether the protocol was successfully registered
|
||||
|
||||
Registers a protocol of `scheme` that will send a stream as a response.
|
||||
|
||||
The usage is the same with `registerFileProtocol`, except that the
|
||||
`callback` should be called with either a [`ReadableStream`](https://nodejs.org/api/stream.html#stream_class_stream_readable) object or an object that
|
||||
has the `data` property.
|
||||
|
||||
Example:
|
||||
|
||||
```javascript
|
||||
const { protocol } = require('electron')
|
||||
const { PassThrough } = require('stream')
|
||||
|
||||
function createStream (text) {
|
||||
const rv = new PassThrough() // PassThrough is also a Readable stream
|
||||
rv.push(text)
|
||||
rv.push(null)
|
||||
return rv
|
||||
}
|
||||
|
||||
protocol.registerStreamProtocol('atom', (request, callback) => {
|
||||
callback({
|
||||
statusCode: 200,
|
||||
headers: {
|
||||
'content-type': 'text/html'
|
||||
},
|
||||
data: createStream('<h5>Response</h5>')
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
It is possible to pass any object that implements the readable stream API (emits
|
||||
`data`/`end`/`error` events). For example, here's how a file could be returned:
|
||||
|
||||
```javascript
|
||||
protocol.registerStreamProtocol('atom', (request, callback) => {
|
||||
callback(fs.createReadStream('index.html'))
|
||||
})
|
||||
```
|
||||
|
||||
### `protocol.unregisterProtocol(scheme)`
|
||||
|
||||
* `scheme` String
|
||||
|
||||
Returns `Boolean` - Whether the protocol was successfully unregistered
|
||||
|
||||
Unregisters the custom protocol of `scheme`.
|
||||
|
||||
### `protocol.isProtocolRegistered(scheme)`
|
||||
|
||||
* `scheme` String
|
||||
|
||||
Returns `Boolean` - Whether `scheme` is already registered.
|
||||
|
||||
### `protocol.interceptFileProtocol(scheme, handler)`
|
||||
|
||||
* `scheme` String
|
||||
* `handler` Function
|
||||
* `request` [ProtocolRequest](latest/api/structures/protocol-request.md)
|
||||
* `callback` Function
|
||||
* `response` (String | [ProtocolResponse](latest/api/structures/protocol-response.md))
|
||||
|
||||
Returns `Boolean` - Whether the protocol was successfully intercepted
|
||||
|
||||
Intercepts `scheme` protocol and uses `handler` as the protocol's new handler
|
||||
which sends a file as a response.
|
||||
|
||||
### `protocol.interceptStringProtocol(scheme, handler)`
|
||||
|
||||
* `scheme` String
|
||||
* `handler` Function
|
||||
* `request` [ProtocolRequest](latest/api/structures/protocol-request.md)
|
||||
* `callback` Function
|
||||
* `response` (String | [ProtocolResponse](latest/api/structures/protocol-response.md))
|
||||
|
||||
Returns `Boolean` - Whether the protocol was successfully intercepted
|
||||
|
||||
Intercepts `scheme` protocol and uses `handler` as the protocol's new handler
|
||||
which sends a `String` as a response.
|
||||
|
||||
### `protocol.interceptBufferProtocol(scheme, handler)`
|
||||
|
||||
* `scheme` String
|
||||
* `handler` Function
|
||||
* `request` [ProtocolRequest](latest/api/structures/protocol-request.md)
|
||||
* `callback` Function
|
||||
* `response` (Buffer | [ProtocolResponse](latest/api/structures/protocol-response.md))
|
||||
|
||||
Returns `Boolean` - Whether the protocol was successfully intercepted
|
||||
|
||||
Intercepts `scheme` protocol and uses `handler` as the protocol's new handler
|
||||
which sends a `Buffer` as a response.
|
||||
|
||||
### `protocol.interceptHttpProtocol(scheme, handler)`
|
||||
|
||||
* `scheme` String
|
||||
* `handler` Function
|
||||
* `request` [ProtocolRequest](latest/api/structures/protocol-request.md)
|
||||
* `callback` Function
|
||||
* `response` [ProtocolResponse](latest/api/structures/protocol-response.md)
|
||||
|
||||
Returns `Boolean` - Whether the protocol was successfully intercepted
|
||||
|
||||
Intercepts `scheme` protocol and uses `handler` as the protocol's new handler
|
||||
which sends a new HTTP request as a response.
|
||||
|
||||
### `protocol.interceptStreamProtocol(scheme, handler)`
|
||||
|
||||
* `scheme` String
|
||||
* `handler` Function
|
||||
* `request` [ProtocolRequest](latest/api/structures/protocol-request.md)
|
||||
* `callback` Function
|
||||
* `response` (ReadableStream | [ProtocolResponse](latest/api/structures/protocol-response.md))
|
||||
|
||||
Returns `Boolean` - Whether the protocol was successfully intercepted
|
||||
|
||||
Same as `protocol.registerStreamProtocol`, except that it replaces an existing
|
||||
protocol handler.
|
||||
|
||||
### `protocol.uninterceptProtocol(scheme)`
|
||||
|
||||
* `scheme` String
|
||||
|
||||
Returns `Boolean` - Whether the protocol was successfully unintercepted
|
||||
|
||||
Remove the interceptor installed for `scheme` and restore its original handler.
|
||||
|
||||
### `protocol.isProtocolIntercepted(scheme)`
|
||||
|
||||
* `scheme` String
|
||||
|
||||
Returns `Boolean` - Whether `scheme` is already intercepted.
|
||||
|
||||
[file-system-api]: https://developer.mozilla.org/en-US/docs/Web/API/LocalFileSystem
|
|
@ -0,0 +1,47 @@
|
|||
---
|
||||
title: "safeStorage"
|
||||
description: "Allows access to simple encryption and decryption of strings for storage on the local machine."
|
||||
slug: safe-storage
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# safeStorage
|
||||
|
||||
> Allows access to simple encryption and decryption of strings for storage on the local machine.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
This module protects data stored on disk from being accessed by other applications or users with full disk access.
|
||||
|
||||
Note that on Mac, access to the system Keychain is required and
|
||||
these calls can block the current thread to collect user input.
|
||||
The same is true for Linux, if a password management tool is available.
|
||||
|
||||
## Methods
|
||||
|
||||
The `safeStorage` module has the following methods:
|
||||
|
||||
### `safeStorage.isEncryptionAvailable()`
|
||||
|
||||
Returns `Boolean` - Whether encryption is available.
|
||||
|
||||
On Linux, returns true if the secret key is
|
||||
available. On MacOS, returns true if Keychain is available.
|
||||
On Windows, returns true with no other preconditions.
|
||||
|
||||
### `safeStorage.encryptString(plainText)`
|
||||
|
||||
* `plainText` String
|
||||
|
||||
Returns `Buffer` - An array of bytes representing the encrypted string.
|
||||
|
||||
This function will throw an error if encryption fails.
|
||||
|
||||
### `safeStorage.decryptString(encrypted)`
|
||||
|
||||
* `encrypted` Buffer
|
||||
|
||||
Returns `String` - the decrypted string. Decrypts the encrypted buffer
|
||||
obtained with `safeStorage.encryptString` back into a string.
|
||||
|
||||
This function will throw an error if decryption fails.
|
|
@ -0,0 +1,165 @@
|
|||
---
|
||||
title: "screen"
|
||||
description: "Retrieve information about screen size, displays, cursor position, etc."
|
||||
slug: screen
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# screen
|
||||
|
||||
> Retrieve information about screen size, displays, cursor position, etc.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
This module cannot be used until the `ready` event of the `app`
|
||||
module is emitted.
|
||||
|
||||
`screen` is an [EventEmitter][event-emitter].
|
||||
|
||||
**Note:** In the renderer / DevTools, `window.screen` is a reserved DOM
|
||||
property, so writing `let { screen } = require('electron')` will not work.
|
||||
|
||||
An example of creating a window that fills the whole screen:
|
||||
|
||||
```fiddle docs/latest/fiddles/screen/fit-screen
|
||||
const { app, BrowserWindow, screen } = require('electron')
|
||||
|
||||
let win
|
||||
app.whenReady().then(() => {
|
||||
const { width, height } = screen.getPrimaryDisplay().workAreaSize
|
||||
win = new BrowserWindow({ width, height })
|
||||
win.loadURL('https://github.com')
|
||||
})
|
||||
```
|
||||
|
||||
Another example of creating a window in the external display:
|
||||
|
||||
```javascript
|
||||
const { app, BrowserWindow, screen } = require('electron')
|
||||
|
||||
let win
|
||||
|
||||
app.whenReady().then(() => {
|
||||
const displays = screen.getAllDisplays()
|
||||
const externalDisplay = displays.find((display) => {
|
||||
return display.bounds.x !== 0 || display.bounds.y !== 0
|
||||
})
|
||||
|
||||
if (externalDisplay) {
|
||||
win = new BrowserWindow({
|
||||
x: externalDisplay.bounds.x + 50,
|
||||
y: externalDisplay.bounds.y + 50
|
||||
})
|
||||
win.loadURL('https://github.com')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Events
|
||||
|
||||
The `screen` module emits the following events:
|
||||
|
||||
### Event: 'display-added'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `newDisplay` [Display](latest/api/structures/display.md)
|
||||
|
||||
Emitted when `newDisplay` has been added.
|
||||
|
||||
### Event: 'display-removed'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `oldDisplay` [Display](latest/api/structures/display.md)
|
||||
|
||||
Emitted when `oldDisplay` has been removed.
|
||||
|
||||
### Event: 'display-metrics-changed'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `display` [Display](latest/api/structures/display.md)
|
||||
* `changedMetrics` String[]
|
||||
|
||||
Emitted when one or more metrics change in a `display`. The `changedMetrics` is
|
||||
an array of strings that describe the changes. Possible changes are `bounds`,
|
||||
`workArea`, `scaleFactor` and `rotation`.
|
||||
|
||||
## Methods
|
||||
|
||||
The `screen` module has the following methods:
|
||||
|
||||
### `screen.getCursorScreenPoint()`
|
||||
|
||||
Returns [`Point`](latest/api/structures/point.md)
|
||||
|
||||
The current absolute position of the mouse pointer.
|
||||
|
||||
**Note:** The return value is a DIP point, not a screen physical point.
|
||||
|
||||
### `screen.getPrimaryDisplay()`
|
||||
|
||||
Returns [`Display`](latest/api/structures/display.md) - The primary display.
|
||||
|
||||
### `screen.getAllDisplays()`
|
||||
|
||||
Returns [`Display[]`](latest/api/structures/display.md) - An array of displays that are currently available.
|
||||
|
||||
### `screen.getDisplayNearestPoint(point)`
|
||||
|
||||
* `point` [Point](latest/api/structures/point.md)
|
||||
|
||||
Returns [`Display`](latest/api/structures/display.md) - The display nearest the specified point.
|
||||
|
||||
### `screen.getDisplayMatching(rect)`
|
||||
|
||||
* `rect` [Rectangle](latest/api/structures/rectangle.md)
|
||||
|
||||
Returns [`Display`](latest/api/structures/display.md) - The display that most closely
|
||||
intersects the provided bounds.
|
||||
|
||||
### `screen.screenToDipPoint(point)` _Windows_
|
||||
|
||||
* `point` [Point](latest/api/structures/point.md)
|
||||
|
||||
Returns [`Point`](latest/api/structures/point.md)
|
||||
|
||||
Converts a screen physical point to a screen DIP point.
|
||||
The DPI scale is performed relative to the display containing the physical point.
|
||||
|
||||
### `screen.dipToScreenPoint(point)` _Windows_
|
||||
|
||||
* `point` [Point](latest/api/structures/point.md)
|
||||
|
||||
Returns [`Point`](latest/api/structures/point.md)
|
||||
|
||||
Converts a screen DIP point to a screen physical point.
|
||||
The DPI scale is performed relative to the display containing the DIP point.
|
||||
|
||||
### `screen.screenToDipRect(window, rect)` _Windows_
|
||||
|
||||
* `window` [BrowserWindow](latest/api/browser-window.md) | null
|
||||
* `rect` [Rectangle](latest/api/structures/rectangle.md)
|
||||
|
||||
Returns [`Rectangle`](latest/api/structures/rectangle.md)
|
||||
|
||||
Converts a screen physical rect to a screen DIP rect.
|
||||
The DPI scale is performed relative to the display nearest to `window`.
|
||||
If `window` is null, scaling will be performed to the display nearest to `rect`.
|
||||
|
||||
### `screen.dipToScreenRect(window, rect)` _Windows_
|
||||
|
||||
* `window` [BrowserWindow](latest/api/browser-window.md) | null
|
||||
* `rect` [Rectangle](latest/api/structures/rectangle.md)
|
||||
|
||||
Returns [`Rectangle`](latest/api/structures/rectangle.md)
|
||||
|
||||
Converts a screen DIP rect to a screen physical rect.
|
||||
The DPI scale is performed relative to the display nearest to `window`.
|
||||
If `window` is null, scaling will be performed to the display nearest to `rect`.
|
||||
|
||||
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
|
|
@ -0,0 +1,80 @@
|
|||
---
|
||||
title: "Class: ServiceWorkers"
|
||||
description: "Query and receive events from a sessions active service workers."
|
||||
slug: service-workers
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
## Class: ServiceWorkers
|
||||
|
||||
> Query and receive events from a sessions active service workers.
|
||||
|
||||
Process: [Main](latest/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._
|
||||
|
||||
Instances of the `ServiceWorkers` class are accessed by using `serviceWorkers` property of
|
||||
a `Session`.
|
||||
|
||||
For example:
|
||||
|
||||
```javascript
|
||||
const { session } = require('electron')
|
||||
|
||||
// Get all service workers.
|
||||
console.log(session.defaultSession.serviceWorkers.getAllRunning())
|
||||
|
||||
// Handle logs and get service worker info
|
||||
session.defaultSession.serviceWorkers.on('console-message', (event, messageDetails) => {
|
||||
console.log(
|
||||
'Got service worker message',
|
||||
messageDetails,
|
||||
'from',
|
||||
session.defaultSession.serviceWorkers.getFromVersionID(messageDetails.versionId)
|
||||
)
|
||||
})
|
||||
```
|
||||
|
||||
### Instance Events
|
||||
|
||||
The following events are available on instances of `ServiceWorkers`:
|
||||
|
||||
#### Event: 'console-message'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `messageDetails` Object - Information about the console message
|
||||
* `message` String - The actual console message
|
||||
* `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`.
|
||||
* `sourceUrl` String - The URL the message came from
|
||||
* `lineNumber` Number - The line number of the source that triggered this console message
|
||||
|
||||
Emitted when a service worker logs something to the console.
|
||||
|
||||
#### Event: 'registration-completed'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `details` Object - Information about the registered service worker
|
||||
* `scope` String - The base URL that a service worker is registered for
|
||||
|
||||
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.
|
||||
|
||||
### Instance Methods
|
||||
|
||||
The following methods are available on instances of `ServiceWorkers`:
|
||||
|
||||
#### `serviceWorkers.getAllRunning()`
|
||||
|
||||
Returns `Record<Number, ServiceWorkerInfo>` - A [ServiceWorkerInfo](latest/api/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)`
|
||||
|
||||
* `versionId` Number
|
||||
|
||||
Returns [`ServiceWorkerInfo`](latest/api/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.
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1,54 @@
|
|||
---
|
||||
title: "ShareMenu"
|
||||
description: "The ShareMenu class creates Share Menu on macOS, which can be used to share information from the current context to apps, social media accounts, and other services."
|
||||
slug: share-menu
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# ShareMenu
|
||||
|
||||
The `ShareMenu` class creates [Share Menu][share-menu] on macOS, which can be
|
||||
used to share information from the current context to apps, social media
|
||||
accounts, and other services.
|
||||
|
||||
For including the share menu as a submenu of other menus, please use the
|
||||
`shareMenu` role of [`MenuItem`](latest/api/menu-item.md).
|
||||
|
||||
## Class: ShareMenu
|
||||
|
||||
> Create share menu on macOS.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process)
|
||||
|
||||
### `new ShareMenu(sharingItem)`
|
||||
|
||||
* `sharingItem` SharingItem - The item to share.
|
||||
|
||||
Creates a new share menu.
|
||||
|
||||
### Instance Methods
|
||||
|
||||
The `shareMenu` object has the following instance methods:
|
||||
|
||||
#### `shareMenu.popup([options])`
|
||||
|
||||
* `options` PopupOptions (optional)
|
||||
* `browserWindow` [BrowserWindow](latest/api/browser-window.md) (optional) - Default is the focused window.
|
||||
* `x` Number (optional) - Default is the current mouse cursor position.
|
||||
Must be declared if `y` is declared.
|
||||
* `y` Number (optional) - Default is the current mouse cursor position.
|
||||
Must be declared if `x` is declared.
|
||||
* `positioningItem` Number (optional) _macOS_ - The index of the menu item to
|
||||
be positioned under the mouse cursor at the specified coordinates. Default
|
||||
is -1.
|
||||
* `callback` Function (optional) - Called when menu is closed.
|
||||
|
||||
Pops up this menu as a context menu in the [`BrowserWindow`](latest/api/browser-window.md).
|
||||
|
||||
#### `shareMenu.closePopup([browserWindow])`
|
||||
|
||||
* `browserWindow` [BrowserWindow](latest/api/browser-window.md) (optional) - Default is the focused window.
|
||||
|
||||
Closes the context menu in the `browserWindow`.
|
||||
|
||||
[share-menu]: https://developer.apple.com/design/human-interface-guidelines/macos/extensions/share-extensions/
|
|
@ -0,0 +1,91 @@
|
|||
---
|
||||
title: "shell"
|
||||
description: "Manage files and URLs using their default applications."
|
||||
slug: shell
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# shell
|
||||
|
||||
> Manage files and URLs using their default applications.
|
||||
|
||||
Process: [Main](latest/glossary.md#main-process), [Renderer](latest/glossary.md#renderer-process) (non-sandboxed only)
|
||||
|
||||
The `shell` module provides functions related to desktop integration.
|
||||
|
||||
An example of opening a URL in the user's default browser:
|
||||
|
||||
```javascript
|
||||
const { shell } = require('electron')
|
||||
|
||||
shell.openExternal('https://github.com')
|
||||
```
|
||||
|
||||
**Note:** While the `shell` module can be used in the renderer process, it will not function in a sandboxed renderer.
|
||||
|
||||
## Methods
|
||||
|
||||
The `shell` module has the following methods:
|
||||
|
||||
### `shell.showItemInFolder(fullPath)`
|
||||
|
||||
* `fullPath` String
|
||||
|
||||
Show the given file in a file manager. If possible, select the file.
|
||||
|
||||
### `shell.openPath(path)`
|
||||
|
||||
* `path` String
|
||||
|
||||
Returns `Promise<String>` - Resolves with a string containing the error message corresponding to the failure if a failure occurred, otherwise "".
|
||||
|
||||
Open the given file in the desktop's default manner.
|
||||
|
||||
### `shell.openExternal(url[, options])`
|
||||
|
||||
* `url` String - Max 2081 characters on windows.
|
||||
* `options` Object (optional)
|
||||
* `activate` Boolean (optional) _macOS_ - `true` to bring the opened application to the foreground. The default is `true`.
|
||||
* `workingDirectory` String (optional) _Windows_ - The working directory.
|
||||
|
||||
Returns `Promise<void>`
|
||||
|
||||
Open the given external protocol URL in the desktop's default manner. (For example, mailto: URLs in the user's default mail agent).
|
||||
|
||||
### `shell.trashItem(path)`
|
||||
|
||||
* `path` String - path to the item to be moved to the trash.
|
||||
|
||||
Returns `Promise<void>` - Resolves when the operation has been completed.
|
||||
Rejects if there was an error while deleting the requested item.
|
||||
|
||||
This moves a path to the OS-specific trash location (Trash on macOS, Recycle
|
||||
Bin on Windows, and a desktop-environment-specific location on Linux).
|
||||
|
||||
### `shell.beep()`
|
||||
|
||||
Play the beep sound.
|
||||
|
||||
### `shell.writeShortcutLink(shortcutPath[, operation], options)` _Windows_
|
||||
|
||||
* `shortcutPath` String
|
||||
* `operation` String (optional) - Default is `create`, can be one of following:
|
||||
* `create` - Creates a new shortcut, overwriting if necessary.
|
||||
* `update` - Updates specified properties only on an existing shortcut.
|
||||
* `replace` - Overwrites an existing shortcut, fails if the shortcut doesn't
|
||||
exist.
|
||||
* `options` [ShortcutDetails](latest/api/structures/shortcut-details.md)
|
||||
|
||||
Returns `Boolean` - Whether the shortcut was created successfully.
|
||||
|
||||
Creates or updates a shortcut link at `shortcutPath`.
|
||||
|
||||
### `shell.readShortcutLink(shortcutPath)` _Windows_
|
||||
|
||||
* `shortcutPath` String
|
||||
|
||||
Returns [`ShortcutDetails`](latest/api/structures/shortcut-details.md)
|
||||
|
||||
Resolves the shortcut link at `shortcutPath`.
|
||||
|
||||
An exception will be thrown when any error happens.
|
|
@ -0,0 +1,11 @@
|
|||
---
|
||||
title: "BluetoothDevice Object"
|
||||
description: ""
|
||||
slug: bluetooth-device
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# BluetoothDevice Object
|
||||
|
||||
* `deviceName` String
|
||||
* `deviceId` String
|
|
@ -0,0 +1,15 @@
|
|||
---
|
||||
title: "CertificatePrincipal Object"
|
||||
description: ""
|
||||
slug: certificate-principal
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# CertificatePrincipal Object
|
||||
|
||||
* `commonName` String - Common Name.
|
||||
* `organizations` String[] - Organization names.
|
||||
* `organizationUnits` String[] - Organization Unit names.
|
||||
* `locality` String - Locality.
|
||||
* `state` String - State or province.
|
||||
* `country` String - Country or region.
|
|
@ -0,0 +1,19 @@
|
|||
---
|
||||
title: "Certificate Object"
|
||||
description: ""
|
||||
slug: certificate
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Certificate Object
|
||||
|
||||
* `data` String - PEM encoded data
|
||||
* `issuer` [CertificatePrincipal](latest/api/structures/certificate-principal.md) - Issuer principal
|
||||
* `issuerName` String - Issuer's Common Name
|
||||
* `issuerCert` Certificate - Issuer certificate (if not self-signed)
|
||||
* `subject` [CertificatePrincipal](latest/api/structures/certificate-principal.md) - Subject principal
|
||||
* `subjectName` String - Subject's Common Name
|
||||
* `serialNumber` String - Hex value represented string
|
||||
* `validStart` Number - Start date of the certificate being valid in seconds
|
||||
* `validExpiry` Number - End date of the certificate being valid in seconds
|
||||
* `fingerprint` String - Fingerprint of the certificate
|
|
@ -0,0 +1,22 @@
|
|||
---
|
||||
title: "Cookie Object"
|
||||
description: ""
|
||||
slug: cookie
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Cookie Object
|
||||
|
||||
* `name` String - The name of the cookie.
|
||||
* `value` String - The value of the cookie.
|
||||
* `domain` String (optional) - The domain of the cookie; this will be normalized with a preceding dot so that it's also valid for subdomains.
|
||||
* `hostOnly` Boolean (optional) - Whether the cookie is a host-only cookie; this will only be `true` if no domain was passed.
|
||||
* `path` String (optional) - The path of the cookie.
|
||||
* `secure` Boolean (optional) - Whether the cookie is marked as secure.
|
||||
* `httpOnly` Boolean (optional) - Whether the cookie is marked as HTTP only.
|
||||
* `session` Boolean (optional) - Whether the cookie is a session cookie or a persistent
|
||||
cookie with an expiration date.
|
||||
* `expirationDate` Double (optional) - The expiration date of the cookie as
|
||||
the number of seconds since the UNIX epoch. Not provided for session
|
||||
cookies.
|
||||
* `sameSite` String - The [Same Site](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#SameSite_cookies) policy applied to this cookie. Can be `unspecified`, `no_restriction`, `lax` or `strict`.
|
|
@ -0,0 +1,14 @@
|
|||
---
|
||||
title: "CPUUsage Object"
|
||||
description: ""
|
||||
slug: cpu-usage
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# CPUUsage Object
|
||||
|
||||
* `percentCPUUsage` Number - Percentage of CPU used since the last call to getCPUUsage.
|
||||
First call returns 0.
|
||||
* `idleWakeupsPerSecond` Number - The number of average idle CPU wakeups per second
|
||||
since the last call to getCPUUsage. First call returns 0. Will always return 0 on
|
||||
Windows.
|
|
@ -0,0 +1,11 @@
|
|||
---
|
||||
title: "CrashReport Object"
|
||||
description: ""
|
||||
slug: crash-report
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# CrashReport Object
|
||||
|
||||
* `date` Date
|
||||
* `id` String
|
|
@ -0,0 +1,18 @@
|
|||
---
|
||||
title: "CustomScheme Object"
|
||||
description: ""
|
||||
slug: custom-scheme
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# CustomScheme Object
|
||||
|
||||
* `scheme` String - Custom schemes to be registered with options.
|
||||
* `privileges` Object (optional)
|
||||
* `standard` Boolean (optional) - Default false.
|
||||
* `secure` Boolean (optional) - Default false.
|
||||
* `bypassCSP` Boolean (optional) - Default false.
|
||||
* `allowServiceWorkers` Boolean (optional) - Default false.
|
||||
* `supportFetchAPI` Boolean (optional) - Default false.
|
||||
* `corsEnabled` Boolean (optional) - Default false.
|
||||
* `stream` Boolean (optional) - Default false.
|
|
@ -0,0 +1,33 @@
|
|||
---
|
||||
title: "DesktopCapturerSource Object"
|
||||
description: ""
|
||||
slug: desktop-capturer-source
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# DesktopCapturerSource Object
|
||||
|
||||
* `id` String - The identifier of a window or screen that can be used as a
|
||||
`chromeMediaSourceId` constraint when calling
|
||||
[`navigator.webkitGetUserMedia`]. The format of the identifier will be
|
||||
`window:XX:YY` or `screen:ZZ:0`. XX is the windowID/handle. YY is 1 for
|
||||
the current process, and 0 for all others. ZZ is a sequential number
|
||||
that represents the screen, and it does not equal to the index in the
|
||||
source's name.
|
||||
* `name` String - A screen source will be named either `Entire Screen` or
|
||||
`Screen <index>`, while the name of a window source will match the window
|
||||
title.
|
||||
* `thumbnail` [NativeImage](latest/api/native-image.md) - A thumbnail image. **Note:**
|
||||
There is no guarantee that the size of the thumbnail is the same as the
|
||||
`thumbnailSize` specified in the `options` passed to
|
||||
`desktopCapturer.getSources`. The actual size depends on the scale of the
|
||||
screen or window.
|
||||
* `display_id` String - A unique identifier that will correspond to the `id` of
|
||||
the matching [Display](latest/api/structures/display.md) returned by the [Screen API](latest/api/screen.md).
|
||||
On some platforms, this is equivalent to the `XX` portion of the `id` field
|
||||
above and on others it will differ. It will be an empty string if not
|
||||
available.
|
||||
* `appIcon` [NativeImage](latest/api/native-image.md) - An icon image of the
|
||||
application that owns the window or null if the source has a type screen.
|
||||
The size of the icon is not known in advance and depends on what
|
||||
the application provides.
|
|
@ -0,0 +1,29 @@
|
|||
---
|
||||
title: "Display Object"
|
||||
description: ""
|
||||
slug: display
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Display Object
|
||||
|
||||
* `id` Number - Unique identifier associated with the display.
|
||||
* `rotation` Number - Can be 0, 90, 180, 270, represents screen rotation in
|
||||
clock-wise degrees.
|
||||
* `scaleFactor` Number - Output device's pixel scale factor.
|
||||
* `touchSupport` String - Can be `available`, `unavailable`, `unknown`.
|
||||
* `monochrome` Boolean - Whether or not the display is a monochrome display.
|
||||
* `accelerometerSupport` String - Can be `available`, `unavailable`, `unknown`.
|
||||
* `colorSpace` String - represent a color space (three-dimensional object which contains all realizable color combinations) for the purpose of color conversions
|
||||
* `colorDepth` Number - The number of bits per pixel.
|
||||
* `depthPerComponent` Number - The number of bits per color component.
|
||||
* `displayFrequency` Number - The display refresh rate.
|
||||
* `bounds` [Rectangle](latest/api/structures/rectangle.md) - the bounds of the display in DIP points.
|
||||
* `size` [Size](latest/api/structures/size.md)
|
||||
* `workArea` [Rectangle](latest/api/structures/rectangle.md) - the work area of the display in DIP points.
|
||||
* `workAreaSize` [Size](latest/api/structures/size.md)
|
||||
* `internal` Boolean - `true` for an internal display and `false` for an external display
|
||||
|
||||
The `Display` object represents a physical display connected to the system. A
|
||||
fake `Display` may exist on a headless system, or a `Display` may correspond to
|
||||
a remote, virtual display.
|
|
@ -0,0 +1,10 @@
|
|||
---
|
||||
title: "Event Object extends `GlobalEvent`"
|
||||
description: ""
|
||||
slug: event
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Event Object extends `GlobalEvent`
|
||||
|
||||
* `preventDefault` VoidFunction
|
|
@ -0,0 +1,11 @@
|
|||
---
|
||||
title: "ExtensionInfo Object"
|
||||
description: ""
|
||||
slug: extension-info
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# ExtensionInfo Object
|
||||
|
||||
* `name` String
|
||||
* `version` String
|
|
@ -0,0 +1,15 @@
|
|||
---
|
||||
title: "Extension Object"
|
||||
description: ""
|
||||
slug: extension
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Extension Object
|
||||
|
||||
* `id` String
|
||||
* `manifest` any - Copy of the [extension's manifest data](https://developer.chrome.com/extensions/manifest).
|
||||
* `name` String
|
||||
* `path` String - The extension's file path.
|
||||
* `version` String
|
||||
* `url` String - The extension's `chrome-extension://` URL.
|
|
@ -0,0 +1,11 @@
|
|||
---
|
||||
title: "FileFilter Object"
|
||||
description: ""
|
||||
slug: file-filter
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# FileFilter Object
|
||||
|
||||
* `name` String
|
||||
* `extensions` String[]
|
|
@ -0,0 +1,11 @@
|
|||
---
|
||||
title: "FilePathWithHeaders Object"
|
||||
description: ""
|
||||
slug: file-path-with-headers
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# FilePathWithHeaders Object
|
||||
|
||||
* `path` String - The path to the file to send.
|
||||
* `headers` Record<string, string> (optional) - Additional headers to be sent.
|
|
@ -0,0 +1,36 @@
|
|||
---
|
||||
title: "GPUFeatureStatus Object"
|
||||
description: ""
|
||||
slug: gpu-feature-status
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# GPUFeatureStatus Object
|
||||
|
||||
* `2d_canvas` String - Canvas.
|
||||
* `flash_3d` String - Flash.
|
||||
* `flash_stage3d` String - Flash Stage3D.
|
||||
* `flash_stage3d_baseline` String - Flash Stage3D Baseline profile.
|
||||
* `gpu_compositing` String - Compositing.
|
||||
* `multiple_raster_threads` String - Multiple Raster Threads.
|
||||
* `native_gpu_memory_buffers` String - Native GpuMemoryBuffers.
|
||||
* `rasterization` String - Rasterization.
|
||||
* `video_decode` String - Video Decode.
|
||||
* `video_encode` String - Video Encode.
|
||||
* `vpx_decode` String - VPx Video Decode.
|
||||
* `webgl` String - WebGL.
|
||||
* `webgl2` String - WebGL2.
|
||||
|
||||
Possible values:
|
||||
|
||||
* `disabled_software` - Software only. Hardware acceleration disabled (yellow)
|
||||
* `disabled_off` - Disabled (red)
|
||||
* `disabled_off_ok` - Disabled (yellow)
|
||||
* `unavailable_software` - Software only, hardware acceleration unavailable (yellow)
|
||||
* `unavailable_off` - Unavailable (red)
|
||||
* `unavailable_off_ok` - Unavailable (yellow)
|
||||
* `enabled_readback` - Hardware accelerated but at reduced performance (yellow)
|
||||
* `enabled_force` - Hardware accelerated on all pages (green)
|
||||
* `enabled` - Hardware accelerated (green)
|
||||
* `enabled_on` - Enabled (green)
|
||||
* `enabled_force_on` - Force enabled (green)
|
|
@ -0,0 +1,15 @@
|
|||
---
|
||||
title: "HIDDevice Object"
|
||||
description: ""
|
||||
slug: hid-device
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# HIDDevice Object
|
||||
|
||||
* `deviceId` String - Unique identifier for the device.
|
||||
* `name` String - Name of the device.
|
||||
* `vendorId` Integer - The USB vendor ID.
|
||||
* `productId` Integer - The USB product ID.
|
||||
* `serialNumber` String (optional) - The USB device serial number.
|
||||
* `guid` String (optional) - Unique identifier for the HID interface. A device may have multiple HID interfaces.
|
|
@ -0,0 +1,13 @@
|
|||
---
|
||||
title: "InputEvent Object"
|
||||
description: ""
|
||||
slug: input-event
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# InputEvent Object
|
||||
|
||||
* `modifiers` String[] (optional) - An array of modifiers of the event, can
|
||||
be `shift`, `control`, `ctrl`, `alt`, `meta`, `command`, `cmd`, `isKeypad`,
|
||||
`isAutoRepeat`, `leftButtonDown`, `middleButtonDown`, `rightButtonDown`,
|
||||
`capsLock`, `numLock`, `left`, `right`.
|
|
@ -0,0 +1,15 @@
|
|||
---
|
||||
title: "IOCounters Object"
|
||||
description: ""
|
||||
slug: io-counters
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# IOCounters Object
|
||||
|
||||
* `readOperationCount` Number - The number of I/O read operations.
|
||||
* `writeOperationCount` Number - The number of I/O write operations.
|
||||
* `otherOperationCount` Number - Then number of I/O other operations.
|
||||
* `readTransferCount` Number - The number of I/O read transfers.
|
||||
* `writeTransferCount` Number - The number of I/O write transfers.
|
||||
* `otherTransferCount` Number - Then number of I/O other transfers.
|
|
@ -0,0 +1,18 @@
|
|||
---
|
||||
title: "IpcMainEvent Object extends `Event`"
|
||||
description: ""
|
||||
slug: ipc-main-event
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# IpcMainEvent Object extends `Event`
|
||||
|
||||
* `processId` Integer - The internal ID of the renderer process that sent this message
|
||||
* `frameId` Integer - The ID of the renderer frame that sent this message
|
||||
* `returnValue` any - Set this to the value to be returned in a synchronous message
|
||||
* `sender` WebContents - Returns the `webContents` that sent the message
|
||||
* `senderFrame` WebFrameMain _Readonly_ - The frame that sent this message
|
||||
* `ports` MessagePortMain[] - A list of MessagePorts that were transferred with this message
|
||||
* `reply` Function - A function that will send an IPC message to the renderer frame that sent the original message that you are currently handling. You should use this method to "reply" to the sent message in order to guarantee the reply will go to the correct process and frame.
|
||||
* `channel` String
|
||||
* `...args` any[]
|
|
@ -0,0 +1,13 @@
|
|||
---
|
||||
title: "IpcMainInvokeEvent Object extends `Event`"
|
||||
description: ""
|
||||
slug: ipc-main-invoke-event
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# IpcMainInvokeEvent Object extends `Event`
|
||||
|
||||
* `processId` Integer - The internal ID of the renderer process that sent this message
|
||||
* `frameId` Integer - The ID of the renderer frame that sent this message
|
||||
* `sender` WebContents - Returns the `webContents` that sent the message
|
||||
* `senderFrame` WebFrameMain _Readonly_ - The frame that sent this message
|
|
@ -0,0 +1,14 @@
|
|||
---
|
||||
title: "IpcRendererEvent Object extends `Event`"
|
||||
description: ""
|
||||
slug: ipc-renderer-event
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# IpcRendererEvent Object extends `Event`
|
||||
|
||||
* `sender` IpcRenderer - The `IpcRenderer` instance that emitted the event originally
|
||||
* `senderId` Integer - The `webContents.id` that sent the message, you can call `event.sender.sendTo(event.senderId, ...)` to reply to the message, see [ipcRenderer.sendTo][ipc-renderer-sendto] for more information. This only applies to messages sent from a different renderer. Messages sent directly from the main process set `event.senderId` to `0`.
|
||||
* `ports` MessagePort[] - A list of MessagePorts that were transferred with this message
|
||||
|
||||
[ipc-renderer-sendto]: latest/api/ipc-renderer.md#ipcrenderersendtowebcontentsid-channel-args
|
|
@ -0,0 +1,32 @@
|
|||
---
|
||||
title: "JumpListCategory Object"
|
||||
description: ""
|
||||
slug: jump-list-category
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# JumpListCategory Object
|
||||
|
||||
* `type` String (optional) - One of the following:
|
||||
* `tasks` - Items in this category will be placed into the standard `Tasks`
|
||||
category. There can be only one such category, and it will always be
|
||||
displayed at the bottom of the Jump List.
|
||||
* `frequent` - Displays a list of files frequently opened by the app, the
|
||||
name of the category and its items are set by Windows.
|
||||
* `recent` - Displays a list of files recently opened by the app, the name
|
||||
of the category and its items are set by Windows. Items may be added to
|
||||
this category indirectly using `app.addRecentDocument(path)`.
|
||||
* `custom` - Displays tasks or file links, `name` must be set by the app.
|
||||
* `name` String (optional) - Must be set if `type` is `custom`, otherwise it should be
|
||||
omitted.
|
||||
* `items` JumpListItem[] (optional) - Array of [`JumpListItem`](latest/api/structures/jump-list-item.md) objects if `type` is `tasks` or
|
||||
`custom`, otherwise it should be omitted.
|
||||
|
||||
**Note:** If a `JumpListCategory` object has neither the `type` nor the `name`
|
||||
property set then its `type` is assumed to be `tasks`. If the `name` property
|
||||
is set but the `type` property is omitted then the `type` is assumed to be
|
||||
`custom`.
|
||||
|
||||
**Note:** 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.
|
|
@ -0,0 +1,36 @@
|
|||
---
|
||||
title: "JumpListItem Object"
|
||||
description: ""
|
||||
slug: jump-list-item
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# JumpListItem Object
|
||||
|
||||
* `type` String (optional) - One of the following:
|
||||
* `task` - A task will launch an app with specific arguments.
|
||||
* `separator` - Can be used to separate items in the standard `Tasks`
|
||||
category.
|
||||
* `file` - A file link will open a file using the app that created the
|
||||
Jump List, for this to work the app must be registered as a handler for
|
||||
the file type (though it doesn't have to be the default handler).
|
||||
* `path` String (optional) - Path of the file to open, should only be set if `type` is
|
||||
`file`.
|
||||
* `program` String (optional) - Path of the program to execute, usually you should
|
||||
specify `process.execPath` which opens the current program. Should only be
|
||||
set if `type` is `task`.
|
||||
* `args` String (optional) - The command line arguments when `program` is executed. Should
|
||||
only be set if `type` is `task`.
|
||||
* `title` String (optional) - The text to be displayed for the item in the Jump List.
|
||||
Should only be set if `type` is `task`.
|
||||
* `description` String (optional) - Description of the task (displayed in a tooltip).
|
||||
Should only be set if `type` is `task`. Maximum length 260 characters.
|
||||
* `iconPath` String (optional) - The absolute path to an icon to be displayed in a
|
||||
Jump List, which can be an arbitrary resource file that contains an icon
|
||||
(e.g. `.ico`, `.exe`, `.dll`). You can usually specify `process.execPath` to
|
||||
show the program icon.
|
||||
* `iconIndex` Number (optional) - The index of the icon in the resource file. If a
|
||||
resource file contains multiple icons this value can be used to specify the
|
||||
zero-based index of the icon that should be displayed for this task. If a
|
||||
resource file contains only one icon, this property should be set to zero.
|
||||
* `workingDirectory` String (optional) - The working directory. Default is empty.
|
|
@ -0,0 +1,14 @@
|
|||
---
|
||||
title: "KeyboardEvent Object"
|
||||
description: ""
|
||||
slug: keyboard-event
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# KeyboardEvent Object
|
||||
|
||||
* `ctrlKey` Boolean (optional) - whether the Control key was used in an accelerator to trigger the Event
|
||||
* `metaKey` Boolean (optional) - whether a meta key was used in an accelerator to trigger the Event
|
||||
* `shiftKey` Boolean (optional) - whether a Shift key was used in an accelerator to trigger the Event
|
||||
* `altKey` Boolean (optional) - whether an Alt key was used in an accelerator to trigger the Event
|
||||
* `triggeredByAccelerator` Boolean (optional) - whether an accelerator was used to trigger the event as opposed to another user gesture like mouse click
|
|
@ -0,0 +1,13 @@
|
|||
---
|
||||
title: "KeyboardInputEvent Object extends `InputEvent`"
|
||||
description: ""
|
||||
slug: keyboard-input-event
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# KeyboardInputEvent Object extends `InputEvent`
|
||||
|
||||
* `type` String - The type of the event, can be `keyDown`, `keyUp` or `char`.
|
||||
* `keyCode` String - The character that will be sent
|
||||
as the keyboard event. Should only use the valid key codes in
|
||||
[Accelerator](latest/api/accelerator.md).
|
|
@ -0,0 +1,16 @@
|
|||
---
|
||||
title: "MemoryInfo Object"
|
||||
description: ""
|
||||
slug: memory-info
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# MemoryInfo Object
|
||||
|
||||
* `workingSetSize` Integer - The amount of memory currently pinned to actual physical RAM.
|
||||
* `peakWorkingSetSize` Integer - The maximum amount of memory that has ever been pinned
|
||||
to actual physical RAM.
|
||||
* `privateBytes` Integer (optional) _Windows_ - The amount of memory not shared by other processes, such as
|
||||
JS heap or HTML content.
|
||||
|
||||
Note that all statistics are reported in Kilobytes.
|
|
@ -0,0 +1,12 @@
|
|||
---
|
||||
title: "MemoryUsageDetails Object"
|
||||
description: ""
|
||||
slug: memory-usage-details
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# MemoryUsageDetails Object
|
||||
|
||||
* `count` Number
|
||||
* `size` Number
|
||||
* `liveSize` Number
|
|
@ -0,0 +1,12 @@
|
|||
---
|
||||
title: "MimeTypedBuffer Object"
|
||||
description: ""
|
||||
slug: mime-typed-buffer
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# MimeTypedBuffer Object
|
||||
|
||||
* `mimeType` String (optional) - MIME type of the buffer.
|
||||
* `charset` String (optional) - Charset of the buffer.
|
||||
* `data` Buffer - The actual Buffer content.
|
|
@ -0,0 +1,19 @@
|
|||
---
|
||||
title: "MouseInputEvent Object extends `InputEvent`"
|
||||
description: ""
|
||||
slug: mouse-input-event
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# MouseInputEvent Object extends `InputEvent`
|
||||
|
||||
* `type` String - The type of the event, can be `mouseDown`,
|
||||
`mouseUp`, `mouseEnter`, `mouseLeave`, `contextMenu`, `mouseWheel` or `mouseMove`.
|
||||
* `x` Integer
|
||||
* `y` Integer
|
||||
* `button` String (optional) - The button pressed, can be `left`, `middle`, `right`.
|
||||
* `globalX` Integer (optional)
|
||||
* `globalY` Integer (optional)
|
||||
* `movementX` Integer (optional)
|
||||
* `movementY` Integer (optional)
|
||||
* `clickCount` Integer (optional)
|
|
@ -0,0 +1,18 @@
|
|||
---
|
||||
title: "MouseWheelInputEvent Object extends `MouseInputEvent`"
|
||||
description: ""
|
||||
slug: mouse-wheel-input-event
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# MouseWheelInputEvent Object extends `MouseInputEvent`
|
||||
|
||||
* `type` String - The type of the event, can be `mouseWheel`.
|
||||
* `deltaX` Integer (optional)
|
||||
* `deltaY` Integer (optional)
|
||||
* `wheelTicksX` Integer (optional)
|
||||
* `wheelTicksY` Integer (optional)
|
||||
* `accelerationRatioX` Integer (optional)
|
||||
* `accelerationRatioY` Integer (optional)
|
||||
* `hasPreciseScrollingDeltas` Boolean (optional)
|
||||
* `canScroll` Boolean (optional)
|
|
@ -0,0 +1,10 @@
|
|||
---
|
||||
title: "NewWindowWebContentsEvent Object extends `Event`"
|
||||
description: ""
|
||||
slug: new-window-web-contents-event
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# NewWindowWebContentsEvent Object extends `Event`
|
||||
|
||||
* `newGuest` BrowserWindow (optional)
|
|
@ -0,0 +1,27 @@
|
|||
---
|
||||
title: "NotificationAction Object"
|
||||
description: ""
|
||||
slug: notification-action
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# NotificationAction Object
|
||||
|
||||
* `type` String - The type of action, can be `button`.
|
||||
* `text` String (optional) - The label for the given action.
|
||||
|
||||
## Platform / Action Support
|
||||
|
||||
| Action Type | Platform Support | Usage of `text` | Default `text` | Limitations |
|
||||
|-------------|------------------|-----------------|----------------|-------------|
|
||||
| `button` | macOS | Used as the label for the button | "Show" (or a localized string by system default if first of such `button`, otherwise empty) | Only the first one is used. If multiple are provided, those beyond the first will be listed as additional actions (displayed when mouse active over the action button). Any such action also is incompatible with `hasReply` and will be ignored if `hasReply` is `true`. |
|
||||
|
||||
### Button support on macOS
|
||||
|
||||
In order for extra notification buttons to work on macOS your app must meet the
|
||||
following criteria.
|
||||
|
||||
* App is signed
|
||||
* App has it's `NSUserNotificationAlertStyle` set to `alert` in the `Info.plist`.
|
||||
|
||||
If either of these requirements are not met the button won't appear.
|
|
@ -0,0 +1,14 @@
|
|||
---
|
||||
title: "NotificationResponse Object"
|
||||
description: ""
|
||||
slug: notification-response
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# NotificationResponse Object
|
||||
|
||||
* `actionIdentifier` String - The identifier string of the action that the user selected.
|
||||
* `date` Number - The delivery date of the notification.
|
||||
* `identifier` String - The unique identifier for this notification request.
|
||||
* `userInfo` Record<String, any> - A dictionary of custom information associated with the notification.
|
||||
* `userText` String (optional) - The text entered or chosen by the user.
|
|
@ -0,0 +1,15 @@
|
|||
---
|
||||
title: "Point Object"
|
||||
description: ""
|
||||
slug: point
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Point Object
|
||||
|
||||
* `x` Number
|
||||
* `y` Number
|
||||
|
||||
**Note:** Both `x` and `y` must be whole integers, when providing a point object
|
||||
as input to an Electron API we will automatically round your `x` and `y` values
|
||||
to the nearest whole integer.
|
|
@ -0,0 +1,30 @@
|
|||
---
|
||||
title: "PostBody Object"
|
||||
description: ""
|
||||
slug: post-body
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# PostBody Object
|
||||
|
||||
* `data` ([UploadRawData](latest/api/structures/upload-raw-data.md) | [UploadFile](latest/api/structures/upload-file.md))[] - The post data to be sent to the
|
||||
new window.
|
||||
* `contentType` String - The `content-type` header used for the data. One of
|
||||
`application/x-www-form-urlencoded` or `multipart/form-data`. Corresponds to
|
||||
the `enctype` attribute of the submitted HTML form.
|
||||
* `boundary` String (optional) - The boundary used to separate multiple parts of
|
||||
the message. Only valid when `contentType` is `multipart/form-data`.
|
||||
|
||||
Note that keys starting with `--` are not currently supported. For example, this will errantly submit as `multipart/form-data` when `nativeWindowOpen` is set to `false` in webPreferences:
|
||||
|
||||
```html
|
||||
<form
|
||||
target="_blank"
|
||||
method="POST"
|
||||
enctype="application/x-www-form-urlencoded"
|
||||
action="https://postman-echo.com/post"
|
||||
>
|
||||
<input type="text" name="--theKey">
|
||||
<input type="submit">
|
||||
</form>
|
||||
```
|
|
@ -0,0 +1,56 @@
|
|||
---
|
||||
title: "PrinterInfo Object"
|
||||
description: ""
|
||||
slug: printer-info
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# PrinterInfo Object
|
||||
|
||||
* `name` String - the name of the printer as understood by the OS.
|
||||
* `displayName` String - the name of the printer as shown in Print Preview.
|
||||
* `description` String - a longer description of the printer's type.
|
||||
* `status` Number - the current status of the printer.
|
||||
* `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 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).
|
||||
|
||||
## Example
|
||||
|
||||
Below is an example of some of the additional options that may be set which
|
||||
may be different on each platform.
|
||||
|
||||
```javascript
|
||||
{
|
||||
name: 'Austin_4th_Floor_Printer___C02XK13BJHD4',
|
||||
displayName: 'Austin 4th Floor Printer @ C02XK13BJHD4',
|
||||
description: 'TOSHIBA ColorMFP',
|
||||
status: 3,
|
||||
isDefault: false,
|
||||
options: {
|
||||
copies: '1',
|
||||
'device-uri': 'dnssd://Austin%204th%20Floor%20Printer%20%40%20C02XK13BJHD4._ipps._tcp.local./?uuid=71687f1e-1147-3274-6674-22de61b110bd',
|
||||
finishings: '3',
|
||||
'job-cancel-after': '10800',
|
||||
'job-hold-until': 'no-hold',
|
||||
'job-priority': '50',
|
||||
'job-sheets': 'none,none',
|
||||
'marker-change-time': '0',
|
||||
'number-up': '1',
|
||||
'printer-commands': 'ReportLevels,PrintSelfTestPage,com.toshiba.ColourProfiles.update,com.toshiba.EFiling.update,com.toshiba.EFiling.checkPassword',
|
||||
'printer-info': 'Austin 4th Floor Printer @ C02XK13BJHD4',
|
||||
'printer-is-accepting-jobs': 'true',
|
||||
'printer-is-shared': 'false',
|
||||
'printer-is-temporary': 'false',
|
||||
'printer-location': '',
|
||||
'printer-make-and-model': 'TOSHIBA ColorMFP',
|
||||
'printer-state': '3',
|
||||
'printer-state-change-time': '1573472937',
|
||||
'printer-state-reasons': 'offline-report,com.toshiba.snmp.failed',
|
||||
'printer-type': '10531038',
|
||||
'printer-uri-supported': 'ipp://localhost/printers/Austin_4th_Floor_Printer___C02XK13BJHD4',
|
||||
system_driverinfo: 'T'
|
||||
}
|
||||
}
|
||||
```
|
|
@ -0,0 +1,14 @@
|
|||
---
|
||||
title: "ProcessMemoryInfo Object"
|
||||
description: ""
|
||||
slug: process-memory-info
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# ProcessMemoryInfo Object
|
||||
|
||||
* `residentSet` Integer _Linux_ _Windows_ - The amount of memory
|
||||
currently pinned to actual physical RAM in Kilobytes.
|
||||
* `private` Integer - The amount of memory not shared by other processes, such as JS heap or HTML content in Kilobytes.
|
||||
* `shared` Integer - The amount of memory shared between processes, typically
|
||||
memory consumed by the Electron code itself in Kilobytes.
|
|
@ -0,0 +1,36 @@
|
|||
---
|
||||
title: "ProcessMetric Object"
|
||||
description: ""
|
||||
slug: process-metric
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# ProcessMetric Object
|
||||
|
||||
* `pid` Integer - Process id of the process.
|
||||
* `type` String - Process type. One of the following values:
|
||||
* `Browser`
|
||||
* `Tab`
|
||||
* `Utility`
|
||||
* `Zygote`
|
||||
* `Sandbox helper`
|
||||
* `GPU`
|
||||
* `Pepper Plugin`
|
||||
* `Pepper Plugin Broker`
|
||||
* `Unknown`
|
||||
* `serviceName` String (optional) - The non-localized name of the process.
|
||||
* `name` String (optional) - The name of the process.
|
||||
Examples for utility: `Audio Service`, `Content Decryption Module Service`, `Network Service`, `Video Capture`, etc.
|
||||
* `cpu` [CPUUsage](latest/api/structures/cpu-usage.md) - CPU usage of the process.
|
||||
* `creationTime` Number - Creation time for this process.
|
||||
The time is represented as number of milliseconds since epoch.
|
||||
Since the `pid` can be reused after a process dies,
|
||||
it is useful to use both the `pid` and the `creationTime` to uniquely identify a process.
|
||||
* `memory` [MemoryInfo](latest/api/structures/memory-info.md) - Memory information for the process.
|
||||
* `sandboxed` Boolean (optional) _macOS_ _Windows_ - Whether the process is sandboxed on OS level.
|
||||
* `integrityLevel` String (optional) _Windows_ - One of the following values:
|
||||
* `untrusted`
|
||||
* `low`
|
||||
* `medium`
|
||||
* `high`
|
||||
* `unknown`
|
|
@ -0,0 +1,18 @@
|
|||
---
|
||||
title: "Product Object"
|
||||
description: ""
|
||||
slug: product
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Product Object
|
||||
|
||||
* `productIdentifier` String - The string that identifies the product to the Apple App Store.
|
||||
* `localizedDescription` String - A description of the product.
|
||||
* `localizedTitle` String - The name of the product.
|
||||
* `contentVersion` String - A string that identifies the version of the content.
|
||||
* `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.
|
|
@ -0,0 +1,14 @@
|
|||
---
|
||||
title: "ProtocolRequest Object"
|
||||
description: ""
|
||||
slug: protocol-request
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# ProtocolRequest Object
|
||||
|
||||
* `url` String
|
||||
* `referrer` String
|
||||
* `method` String
|
||||
* `uploadData` [UploadData[]](latest/api/structures/upload-data.md) (optional)
|
||||
* `headers` Record<String, String>
|
|
@ -0,0 +1,11 @@
|
|||
---
|
||||
title: "ProtocolResponseUploadData Object"
|
||||
description: ""
|
||||
slug: protocol-response-upload-data
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# ProtocolResponseUploadData Object
|
||||
|
||||
* `contentType` String - MIME type of the content.
|
||||
* `data` String | Buffer - Content to be sent.
|
|
@ -0,0 +1,41 @@
|
|||
---
|
||||
title: "ProtocolResponse Object"
|
||||
description: ""
|
||||
slug: protocol-response
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# ProtocolResponse Object
|
||||
|
||||
* `error` Integer (optional) - When assigned, the `request` will fail with the
|
||||
`error` number . For the available error numbers you can use, please see the
|
||||
[net error list][net-error].
|
||||
* `statusCode` Number (optional) - The HTTP response code, default is 200.
|
||||
* `charset` String (optional) - The charset of response body, default is
|
||||
`"utf-8"`.
|
||||
* `mimeType` String (optional) - The MIME type of response body, default is
|
||||
`"text/html"`. Setting `mimeType` would implicitly set the `content-type`
|
||||
header in response, but if `content-type` is already set in `headers`, the
|
||||
`mimeType` would be ignored.
|
||||
* `headers` Record<string, string | string[]> (optional) - An object containing the response headers. The
|
||||
keys must be String, and values must be either String or Array of String.
|
||||
* `data` (Buffer | String | ReadableStream) (optional) - The response body. When
|
||||
returning stream as response, this is a Node.js readable stream representing
|
||||
the response body. When returning `Buffer` as response, this is a `Buffer`.
|
||||
When returning `String` as response, this is a `String`. This is ignored for
|
||||
other types of responses.
|
||||
* `path` String (optional) - Path to the file which would be sent as response
|
||||
body. This is only used for file responses.
|
||||
* `url` String (optional) - Download the `url` and pipe the result as response
|
||||
body. This is only used for URL responses.
|
||||
* `referrer` String (optional) - The `referrer` URL. This is only used for file
|
||||
and URL responses.
|
||||
* `method` String (optional) - The HTTP `method`. This is only used for file
|
||||
and URL responses.
|
||||
* `session` Session (optional) - The session used for requesting URL, by default
|
||||
the HTTP request will reuse the current session. Setting `session` to `null`
|
||||
would use a random independent session. This is only used for URL responses.
|
||||
* `uploadData` [ProtocolResponseUploadData](latest/api/structures/protocol-response-upload-data.md) (optional) - The data used as upload data. This is only
|
||||
used for URL responses when `method` is `"POST"`.
|
||||
|
||||
[net-error]: https://source.chromium.org/chromium/chromium/src/+/master:net/base/net_error_list.h
|
|
@ -0,0 +1,13 @@
|
|||
---
|
||||
title: "Rectangle Object"
|
||||
description: ""
|
||||
slug: rectangle
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Rectangle Object
|
||||
|
||||
* `x` Number - The x coordinate of the origin of the rectangle (must be an integer).
|
||||
* `y` Number - The y coordinate of the origin of the rectangle (must be an integer).
|
||||
* `width` Number - The width of the rectangle (must be an integer).
|
||||
* `height` Number - The height of the rectangle (must be an integer).
|
|
@ -0,0 +1,17 @@
|
|||
---
|
||||
title: "Referrer Object"
|
||||
description: ""
|
||||
slug: referrer
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# Referrer Object
|
||||
|
||||
* `url` String - HTTP Referrer URL.
|
||||
* `policy` String - Can be `default`, `unsafe-url`,
|
||||
`no-referrer-when-downgrade`, `no-referrer`, `origin`,
|
||||
`strict-origin-when-cross-origin`, `same-origin` or `strict-origin`.
|
||||
See the [Referrer-Policy spec][1] for more details on the
|
||||
meaning of these values.
|
||||
|
||||
[1]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy
|
|
@ -0,0 +1,11 @@
|
|||
---
|
||||
title: "ScrubberItem Object"
|
||||
description: ""
|
||||
slug: scrubber-item
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# ScrubberItem Object
|
||||
|
||||
* `label` String (optional) - The text to appear in this item.
|
||||
* `icon` NativeImage (optional) - The image to appear in this item.
|
|
@ -0,0 +1,12 @@
|
|||
---
|
||||
title: "SegmentedControlSegment Object"
|
||||
description: ""
|
||||
slug: segmented-control-segment
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# SegmentedControlSegment Object
|
||||
|
||||
* `label` String (optional) - The text to appear in this segment.
|
||||
* `icon` NativeImage (optional) - The image to appear in this segment.
|
||||
* `enabled` Boolean (optional) - Whether this segment is selectable. Default: true.
|
|
@ -0,0 +1,17 @@
|
|||
---
|
||||
title: "SerialPort Object"
|
||||
description: ""
|
||||
slug: serial-port
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# SerialPort Object
|
||||
|
||||
* `portId` String - Unique identifier for the port.
|
||||
* `portName` String - Name of the port.
|
||||
* `displayName` String - A string suitable for display to the user for describing this device.
|
||||
* `vendorId` String - Optional USB vendor ID.
|
||||
* `productId` String - Optional USB product ID.
|
||||
* `serialNumber` String - The USB device serial number.
|
||||
* `usbDriverName` String (optional) - Represents a single serial port on macOS can be enumerated by multiple drivers.
|
||||
* `deviceInstanceId` String (optional) - A stable identifier on Windows that can be used for device permissions.
|
|
@ -0,0 +1,12 @@
|
|||
---
|
||||
title: "ServiceWorkerInfo Object"
|
||||
description: ""
|
||||
slug: service-worker-info
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# ServiceWorkerInfo Object
|
||||
|
||||
* `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()`.
|
|
@ -0,0 +1,11 @@
|
|||
---
|
||||
title: "SharedWorkerInfo Object"
|
||||
description: ""
|
||||
slug: shared-worker-info
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# SharedWorkerInfo Object
|
||||
|
||||
* `id` String - The unique id of the shared worker.
|
||||
* `url` String - The url of the shared worker.
|
|
@ -0,0 +1,12 @@
|
|||
---
|
||||
title: "SharingItem Object"
|
||||
description: ""
|
||||
slug: sharing-item
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# SharingItem Object
|
||||
|
||||
* `texts` String[] (optional) - An array of text to share.
|
||||
* `filePaths` String[] (optional) - An array of files to share.
|
||||
* `urls` String[] (optional) - An array of URLs to share.
|
Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше
Загрузка…
Ссылка в новой задаче