Merge branch 'master' into add-env-to-release-docs

This commit is contained in:
Charles Kerr
2018-03-07 16:38:14 +09:00
453 changed files with 13682 additions and 6855 deletions

View File

@@ -14,34 +14,89 @@ an issue:
* [Electron FAQ](faq.md)
## Guides
## Guides and Tutorials
* [Setting up the Development Environment](tutorial/development-environment.md)
* [Setting up macOS](tutorial/development-environment.md#setting-up-macos)
* [Setting up Windows](tutorial/development-environment.md#setting-up-windows)
* [Setting up Linux](tutorial/development-environment.md#setting-up-linux)
* [Choosing an Editor](tutorial/development-environment.md#a-good-editor)
* [Creating your First App](tutorial/first-app.md)
* [Installing Electron](tutorial/first-app.md#installing-electron)
* [Electron Development in a Nutshell](tutorial/first-app.md#electron-development-in-a-nutshell)
* [Running Your App](tutorial/first-app.md#running-your-app)
* [Boilerplates and CLIs](tutorial/boilerplates-and-clis.md)
* [Boilerplate vs CLI](tutorial/boilerplates-and-clis.md#boilerplate-vs-cli)
* [electron-forge](tutorial/boilerplates-and-clis.md#electron-forge)
* [electron-builder](tutorial/boilerplates-and-clis.md#electron-builder)
* [electron-react-boilerplate](tutorial/boilerplates-and-clis.md#electron-react-boilerplate)
* [Other Tools and Boilerplates](tutorial/boilerplates-and-clis.md#other-tools-and-boilerplates)
* [Application Architecture](tutorial/application-architecture.md)
* [Main and Renderer Processes](tutorial/application-architecture.md#main-and-renderer-processes)
* [Using Electron's APIs](tutorial/application-architecture.md#using-electron-apis)
* [Using Node.js APIs](tutorial/application-architecture.md#using-node.js-apis)
* [Using Native Node.js Modules](tutorial/using-native-node-modules.md)
* [Inter-Process Communication](tutorial/application-architecture.md#)
* Adding Features to Your App
* [Notifications](tutorial/notifications.md)
* [Recent Documents](tutorial/desktop-environment-integration.md#recent-documents-windows-mac-os)
* [Application Progress](tutorial/progress-bar.md)
* [Custom Dock Menu](tutorial/desktop-environment-integration.md#custom-dock-menu-mac-os)
* [Custom Windows Taskbar](tutorial/windows-taskbar.md)
* [Custom Linux Desktop Actions](tutorial/linux-desktop-actions.md)
* [Keyboard Shortcuts](tutorial/keyboard-shortcuts.md)
* [Offline/Online Detection](tutorial/online-offline-events.md)
* [Represented File for macOS BrowserWindows](tutorial/represented-file.md)
* [Native File Drag & Drop](tutorial/native-file-drag-drop.md)
* [Application Accessibility](tutorial/accessibility.md)
* [Spectron](tutorial/accessibility.md#spectron)
* [Devtron](tutorial/accessibility.md#devtron)
* [Enabling Accessibility](tutorial/accessibility.md#enabling-accessibility)
* [Application Testing and Debugging](tutorial/application-debugging.md)
* [Debugging the Main Process](tutorial/debugging-main-process.md)
* [Using Selenium and WebDriver](tutorial/using-selenium-and-webdriver.md)
* [Testing on Headless CI Systems (Travis, Jenkins)](tutorial/testing-on-headless-ci.md)
* [DevTools Extension](tutorial/devtools-extension.md)
* [Application Distribution](tutorial/application-distribution.md)
* [Supported Platforms](tutorial/supported-platforms.md)
* [Mac App Store](tutorial/mac-app-store-submission-guide.md)
* [Windows Store](tutorial/windows-store-guide.md)
* [Snapcraft](tutorial/snapcraft.md)
* [Application Security](tutorial/security.md)
* [Reporting Security Issues](tutorial/security.md#reporting-security-issues)
* [Chromium Security Issues and Upgrades](tutorial/security.md#chromium-security-issues-and-upgrades)
* [Electron Security Warnings](tutorial/security.md#electron-security-warnings)
* [Security Checklist](tutorial/security.md#checklist-security-recommendations)
* [Application Updates](tutorial/updates.md)
* [Deploying an Update Server](tutorial/updates.md#deploying-an-update-server)
* [Implementing Updates in Your App](tutorial/updates.md#implementing-updates-in-your-app)
* [Applying Updates](tutorial/updates.md#applying-updates)
## Detailed Tutorials
These individual tutorials expand on topics discussed in the guide above.
* [In Detail: Installing Electron](tutorial/installation.md)
* [Global versus Local Installation](tutorial/installation.md#global-versus-local-installation)
* [Proxies](tutorial/installation.md#proxies)
* [Custom Mirrors and Caches](tutorial/installation.md#custom-mirrors-and-caches)
* [Troubleshooting](tutorial/installation.md#troubleshooting)
* [In Detail: Electron's Versioning Scheme](tutorial/electron-versioning.md)
* [semver](tutorial/electron-versioning.md#semver)
* [Stabilization Branches](tutorial/electron-versioning.md#stabilization-branches)
* [Beta Releases and Bug Fixes](tutorial/electron-versioning.md#beta-releases-and-bug-fixes)
* [In Detail: Packaging App Source Code with asar](tutorial/application-packaging.md)
* [Generating asar Archives](tutorial/application-packaging.md#generating-asar-archives)
* [Using asar Archives](tutorial/application-packaging.md#using-asar-archives)
* [Limitations](tutorial/application-packaging.md#limitations-of-the-node-api)
* [Adding Unpacked Files to asar Archives](tutorial/application-packaging.md#adding-unpacked-files-to-asar-archives)
* [In Detail: Using Pepper Flash Plugin](tutorial/using-pepper-flash-plugin.md)
* [In Detail: Using Widevine CDM Plugin](tutorial/using-widevine-cdm-plugin.md)
* [Offscreen Rendering](tutorial/offscreen-rendering.md)
---
* [Glossary of Terms](glossary.md)
* [Supported Platforms](tutorial/supported-platforms.md)
* [Security](tutorial/security.md)
* [Electron Versioning](tutorial/electron-versioning.md)
* [Application Distribution](tutorial/application-distribution.md)
* [Mac App Store Submission Guide](tutorial/mac-app-store-submission-guide.md)
* [Windows Store Guide](tutorial/windows-store-guide.md)
* [Application Packaging](tutorial/application-packaging.md)
* [Using Native Node Modules](tutorial/using-native-node-modules.md)
* [Debugging Main Process](tutorial/debugging-main-process.md)
* [Using Selenium and WebDriver](tutorial/using-selenium-and-webdriver.md)
* [DevTools Extension](tutorial/devtools-extension.md)
* [Using Pepper Flash Plugin](tutorial/using-pepper-flash-plugin.md)
* [Using Widevine CDM Plugin](tutorial/using-widevine-cdm-plugin.md)
* [Testing on Headless CI Systems (Travis, Jenkins)](tutorial/testing-on-headless-ci.md)
* [Offscreen Rendering](tutorial/offscreen-rendering.md)
* [Keyboard Shortcuts](tutorial/keyboard-shortcuts.md)
* [Updating Applications](tutorial/updates.md)
## Tutorials
* [Quick Start](tutorial/quick-start.md)
* [Desktop Environment Integration](tutorial/desktop-environment-integration.md)
* [Online/Offline Event Detection](tutorial/online-offline-events.md)
* [REPL](tutorial/repl.md)
* [Native Notifications](tutorial/notifications.md)
## API References
@@ -65,6 +120,7 @@ an issue:
* [contentTracing](api/content-tracing.md)
* [dialog](api/dialog.md)
* [globalShortcut](api/global-shortcut.md)
* [inAppPurchase](api/in-app-purchase.md)
* [ipcMain](api/ipc-main.md)
* [Menu](api/menu.md)
* [MenuItem](api/menu-item.md)
@@ -96,6 +152,7 @@ an issue:
* [Coding Style](development/coding-style.md)
* [Using clang-format on C++ Code](development/clang-format.md)
* [Testing](development/testing.md)
* [Source Code Directory Structure](development/source-code-directory-structure.md)
* [Technical Differences to NW.js (formerly node-webkit)](development/atom-shell-vs-node-webkit.md)
* [Build System Overview](development/build-system-overview.md)
@@ -106,6 +163,9 @@ an issue:
* [Debug Instructions (Windows)](development/debug-instructions-windows.md)
* [Setting Up Symbol Server in debugger](development/setting-up-symbol-server.md)
* [Documentation Styleguide](styleguide.md)
* [Upgrading Chrome](development/upgrading-chrome.md)
* [Contributing to Electron](../CONTRIBUTING.md)
* [Issues](development/issues.md)
* [Pull Requests](development/pull-requests.md)
* [Upgrading Chromium](development/upgrading-chromium.md)
* [Chromium Development](development/chromium-development.md)
* [V8 Development](development/v8-development.md)

View File

@@ -194,7 +194,7 @@ Returns:
[`NSUserActivity.activityType`][activity-type].
* `userInfo` Object - Contains app-specific state stored by the activity.
Emitted when [Handoff][handoff] is about to be resumed on another device. If you need to update the state to be transferred, you should call `event.preventDefault()` immediatelly, construct a new `userInfo` dictionary and call `app.updateCurrentActiviy()` in a timely manner. Otherwise the operation will fail and `continue-activity-error` will be called.
Emitted when [Handoff][handoff] is about to be resumed on another device. If you need to update the state to be transferred, you should call `event.preventDefault()` immediately, construct a new `userInfo` dictionary and call `app.updateCurrentActiviy()` in a timely manner. Otherwise the operation will fail and `continue-activity-error` will be called.
### Event: 'new-window-for-tab' _macOS_
@@ -844,11 +844,6 @@ disables that behaviour.
This method can only be called before app is ready.
### `app.getAppMemoryInfo()` _Deprecated_
Returns [`ProcessMetric[]`](structures/process-metric.md): Array of `ProcessMetric` objects that correspond to memory and cpu usage statistics of all the processes associated with the app.
**Note:** This method is deprecated, use `app.getAppMetrics()` instead.
### `app.getAppMetrics()`
Returns [`ProcessMetric[]`](structures/process-metric.md): Array of `ProcessMetric` objects that correspond to memory and cpu usage statistics of all the processes associated with the app.
@@ -970,6 +965,23 @@ details. Disabled by default.
Set the about panel options. This will override the values defined in the app's
`.plist` file. See the [Apple docs][about-panel-options] for more details.
### `app.startAccessingSecurityScopedResource(bookmarkData)` _macOS (mas)_
* `bookmarkData` String - The base64 encoded security scoped bookmark data returned by the `dialog.showOpenDialog` or `dialog.showSaveDialog` methods.
Returns `Function` - This function **must** be called once you have finished accessing the security scoped file. If you do not remember to stop accessing the bookmark, [kernel resources will be leaked](https://developer.apple.com/reference/foundation/nsurl/1417051-startaccessingsecurityscopedreso?language=objc) and your app will lose its ability to reach outside the sandbox completely, until your app is restarted.
```js
// Start accessing the file.
const stopAccessingSecurityScopedResource = app.startAccessingSecurityScopedResource(data)
// You can now access the file outside of the sandbox 🎉
// Remember to stop accessing the file once you've finished with it.
stopAccessingSecurityScopedResource()
```
Start accessing a security scoped resource. With this method electron applications that are packaged for the Mac App Store may reach outside their sandbox to access files chosen by the user. See [Apple's documentation](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) for a description of how this system works.
### `app.commandLine.appendSwitch(switch[, value])`
* `switch` String - A command-line switch
@@ -1078,7 +1090,7 @@ Sets the application's [dock menu][dock-menu].
Sets the `image` associated with this dock icon.
[dock-menu]:https://developer.apple.com/library/mac/documentation/Carbon/Conceptual/customizing_docktile/concepts/dockconcepts.html#//apple_ref/doc/uid/TP30000986-CH2-TPXREF103
[tasks]:http://msdn.microsoft.com/en-us/library/windows/desktop/dd378460(v=vs.85).aspx#tasks
[tasks]:https://msdn.microsoft.com/en-us/library/windows/desktop/dd378460(v=vs.85).aspx#tasks
[app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx
[CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115
[LSCopyDefaultHandlerForURLScheme]: https://developer.apple.com/library/mac/documentation/Carbon/Reference/LaunchServicesReference/#//apple_ref/c/func/LSCopyDefaultHandlerForURLScheme

View File

@@ -88,10 +88,13 @@ On Windows only `releaseName` is available.
The `autoUpdater` object has the following methods:
### `autoUpdater.setFeedURL(url[, requestHeaders])`
### `autoUpdater.setFeedURL(options)`
* `url` String
* `requestHeaders` Object (optional) _macOS_ - HTTP request headers.
* `options` Object
* `url` String
* `headers` Object (optional) _macOS_ - HTTP request headers.
* `serverType` String (optional) _macOS_ - Either `json` or `default`, see the [Squirrel.Mac][squirrel-mac]
README for more information.
Sets the `url` and initialize the auto updater.
@@ -109,9 +112,13 @@ using this API.
Restarts the app and installs the update after it has been downloaded. It
should only be called after `update-downloaded` has been emitted.
**Note:** `autoUpdater.quitAndInstall()` will close all application windows
first and only emit `before-quit` event on `app` after that. This is different
from the normal quit event sequence.
Under the hood calling `autoUpdater.quitAndInstall()` will close all application
windows first, and automatically call `app.quit()` after all windows have been
closed.
**Note:** If the application is quit without calling this API after the
`update-downloaded` event has been emitted, the application will still be
replaced by the updated one on the next run.
[squirrel-mac]: https://github.com/Squirrel/Squirrel.Mac
[server-support]: https://github.com/Squirrel/Squirrel.Mac#server-support

View File

@@ -133,7 +133,7 @@ state is `hidden` in order to minimize power consumption.
Process: [Main](../glossary.md#main-process)
`BrowserWindow` is an
[EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter).
[EventEmitter](https://nodejs.org/api/events.html#events_class_events_eventemitter).
It creates a new `BrowserWindow` with native properties as set by the `options`.
@@ -220,7 +220,6 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
* `hidden` - Results in a hidden title bar and a full size content window, yet
the title bar still has the standard window controls ("traffic lights") in
the top left.
* `hidden-inset` - Deprecated, use `hiddenInset` instead.
* `hiddenInset` - Results in a hidden title bar with an alternative look
where the traffic light buttons are slightly more inset from the window edge.
* `customButtonsOnHover` Boolean (optional) - Draw custom close, minimize,
@@ -229,7 +228,7 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
buttons prevent issues with mouse events that occur with the standard
window toolbar buttons. **Note:** This option is currently experimental.
* `fullscreenWindowTitle` Boolean (optional) - Shows the title in the
tile bar in full screen mode on macOS for all `titleBarStyle` options.
title bar in full screen mode on macOS for all `titleBarStyle` options.
Default is `false`.
* `thickFrame` Boolean (optional) - Use `WS_THICKFRAME` style for frameless windows on
Windows, which adds standard window frame. Setting it to `false` will remove
@@ -280,6 +279,13 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
same `partition`. If there is no `persist:` prefix, the page will use an
in-memory session. By assigning the same `partition`, multiple pages can share
the same session. Default is the default session.
* `affinity` String (optional) - When specified, web pages with the same
`affinity` will run in the same renderer process. Note that due to reusing
the renderer process, certain `webPreferences` options will also be shared
between the web pages even when you specified different values for them,
including but not limited to `preload`, `sandbox` and `nodeIntegration`.
So it is suggested to use exact same `webPreferences` for web pages with
the same `affinity`.
* `zoomFactor` Number (optional) - The default zoom factor of the page, `3.0` represents
`300%`. Default is `1.0`.
* `javascript` Boolean (optional) - Enables JavaScript support. Default is `true`.
@@ -343,7 +349,7 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
Console tab. **Note:** This option is currently experimental and may
change or be removed in future Electron releases.
* `nativeWindowOpen` Boolean (optional) - Whether to use native
`window.open()`. Defaults to `false`. **Note:** This option is currently
`window.open()`. Defaults to `false`. **Note:** This option is currently
experimental.
* `webviewTag` Boolean (optional) - Whether to enable the [`<webview>` tag](webview-tag.md).
Defaults to the value of the `nodeIntegration` option. **Note:** The
@@ -353,6 +359,15 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
script. You can use the `will-attach-webview` event on [webContents](web-contents.md)
to strip away the `preload` script and to validate or alter the
`<webview>`'s initial settings.
* `additionArguments` String[] (optional) - A list of strings that will be appended
to `process.argv` in the renderer process of this app. Useful for passing small
bits of data down to renderer process preload scripts.
* `safeDialogs` Boolean (optional) - Whether to enable browser style
consecutive dialog protection. Default is `false`.
* `safeDialogsMessage` String (optional) - The message to display when
consecutive dialog protection is triggered. If not defined the default
message would be used, note that currently the default message is in
English and not localized.
When setting minimum or maximum window size with `minWidth`/`maxWidth`/
`minHeight`/`maxHeight`, it only constrains the users. It won't prevent you from
@@ -572,7 +587,7 @@ Returns `BrowserWindow[]` - An array of all opened browser windows.
#### `BrowserWindow.getFocusedWindow()`
Returns `BrowserWindow` - The window that is focused in this application, otherwise returns `null`.
Returns `BrowserWindow | null` - The window that is focused in this application, otherwise returns `null`.
#### `BrowserWindow.fromWebContents(webContents)`
@@ -847,6 +862,12 @@ the supplied bounds.
Returns [`Rectangle`](structures/rectangle.md)
#### `win.setEnabled(enable)`
* `enable` Boolean
Disable or enable the window.
#### `win.setSize(width, height[, animate])`
* `width` Integer
@@ -1159,6 +1180,14 @@ win.loadURL('http://localhost:8000/post', {
})
```
#### `win.loadFile(filePath)`
* `filePath` String
Same as `webContents.loadFile`, `filePath` should be a path to an HTML
file relative to the root of your application. See the `webContents` docs
for more information.
#### `win.reload()`
Same as `webContents.reload`.
@@ -1459,6 +1488,6 @@ removed in future Electron releases.
[blink-feature-string]: https://cs.chromium.org/chromium/src/third_party/WebKit/Source/platform/runtime_enabled_features.json5?l=70
[page-visibility-api]: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
[quick-look]: https://en.wikipedia.org/wiki/Quick_Look
[vibrancy-docs]: https://developer.apple.com/reference/appkit/nsvisualeffectview?language=objc
[vibrancy-docs]: https://developer.apple.com/documentation/appkit/nsvisualeffectview?preferredLanguage=objc
[window-levels]: https://developer.apple.com/reference/appkit/nswindow/1664726-window_levels
[chrome-content-scripts]: https://developer.chrome.com/extensions/content_scripts#execution-environment

View File

@@ -28,6 +28,10 @@ Disables the disk cache for HTTP requests.
Disable HTTP/2 and SPDY/3.1 protocols.
## --lang
Set a custom locale.
## --inspect=`port` and --inspect-brk=`port`
Debug-related flags, see the [Debugging the Main Process][debugging-main-process] guide for details.

View File

@@ -32,7 +32,7 @@ the hostname and the port number 'hostname:port'.
* `redirect` String (optional) - The redirect mode for this request. Should be
one of `follow`, `error` or `manual`. Defaults to `follow`. When mode is `error`,
any redirection will be aborted. When mode is `manual` the redirection will be
deferred until [`request.followRedirect`](#requestfollowRedirect) is invoked. Listen for the [`redirect`](#event-redirect) event in
deferred until [`request.followRedirect`](#requestfollowredirect) is invoked. Listen for the [`redirect`](#event-redirect) event in
this mode to get more details about the redirect request.
`options` properties such as `protocol`, `host`, `hostname`, `port` and `path`
@@ -137,7 +137,7 @@ Returns:
* `responseHeaders` Object
Emitted when there is redirection and the mode is `manual`. Calling
[`request.followRedirect`](#requestfollowRedirect) will continue with the redirection.
[`request.followRedirect`](#requestfollowredirect) will continue with the redirection.
### Instance Properties

View File

@@ -24,6 +24,10 @@ 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 I/O](https://backtrace.io/electron/)
Crash reports are saved locally in an application-specific temp directory folder.
For a `productName` of `YourName`, crash reports will be stored in a folder
named `YourName Crashes` inside the temp directory. You can customize this temp
@@ -62,7 +66,7 @@ This will start the process that will monitor and send the crash reports. Replac
and `crashesDirectory` with appropriate values.
**Note:** If you need send additional/updated `extra` parameters after your
first call `start` you can call `setExtraParameter` on macOS or call `start`
first call `start` you can call `addExtraParameter` on macOS or call `start`
again with the new/updated `extra` parameters on Linux and Windows.
```js

View File

@@ -50,8 +50,10 @@ The `dialog` module has the following methods:
as a directory instead of a file.
* `message` String (optional) _macOS_ - Message to display above input
boxes.
* `securityScopedBookmarks` Boolean (optional) _masOS_ _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.
* `callback` Function (optional)
* `filePaths` String[] - An array of file paths chosen by the user
* `bookmarks` String[] _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.
Returns `String[]`, an array of file paths chosen by the user,
if the callback is provided it returns `undefined`.
@@ -99,8 +101,10 @@ shown.
displayed in front of the filename text field.
* `showsTagField` Boolean (optional) _macOS_ - Show the tags input box,
defaults to `true`.
* `securityScopedBookmarks` Boolean (optional) _masOS_ _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.
* `callback` Function (optional)
* `filename` String
* `bookmark` String _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.
Returns `String`, the path of the file chosen by the user,
if a callback is provided it returns `undefined`.

View File

@@ -44,7 +44,7 @@ win.webContents.session.on('will-download', (event, item, webContents) => {
Returns:
* `event` Event
* `state` String
* `state` String - Can be `progressing` or `interrupted`.
Emitted when the download has been updated and is not done.
@@ -58,7 +58,7 @@ The `state` can be one of following:
Returns:
* `event` Event
* `state` String
* `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

View File

@@ -0,0 +1,39 @@
# inAppPurchase
> In-app purchases on Mac App Store.
Process: [Main](../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`](structures/transaction) objects.
## Methods
The `inAppPurchase` module has the following methods:
### `inAppPurchase.purchaseProduct(productID, quantity, callback)`
* `productID` String - The id of the product to purchase. (the id of `com.example.app.product1` is `product1`).
* `quantity` Integer (optional) - The number of items the user wants to purchase.
* `callback` Function (optional) - The callback called when the payment is added to the PaymentQueue.
* `isProductValid` Boolean - Determine 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.canMakePayments()`
Returns `true` if the user can make a payment and `false` otherwise.
### `inAppPurchase.getReceiptURL()`
Returns `String`, the path to the receipt.

View File

@@ -54,19 +54,19 @@ The `role` property can have following values:
* `cut`
* `copy`
* `paste`
* `pasteandmatchstyle`
* `selectall`
* `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%.
* `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%.
* `editMenu` - Whole default "Edit" menu (Undo, Copy, etc.).
* `windowMenu` - Whole default "Window" menu (Minimize, Close, etc.).
@@ -74,25 +74,26 @@ The following additional roles are available on _macOS_:
* `about` - Map to the `orderFrontStandardAboutPanel` action.
* `hide` - Map to the `hide` action.
* `hideothers` - Map to the `hideOtherApplications` 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.
* `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.
* `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" menu.
* `recentdocuments` - The submenu is an "Open Recent" menu.
* `clearrecentdocuments` - Map to the `clearRecentDocuments` action.
* `recentDocuments` - The submenu is an "Open Recent" menu.
* `clearRecentDocuments` - Map to the `clearRecentDocuments` action.
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.
### Instance Properties

View File

@@ -59,10 +59,10 @@ will become properties of the constructed menu items.
The `menu` object has the following instance methods:
#### `menu.popup([browserWindow, options])`
#### `menu.popup(options)`
* `browserWindow` [BrowserWindow](browser-window.md) (optional) - Default is the focused window.
* `options` Object (optional)
* `options` Object
* `window` [BrowserWindow](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.
@@ -70,6 +70,7 @@ The `menu` object has the following instance methods:
* `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`](browser-window.md).
@@ -98,6 +99,29 @@ Returns `MenuItem` the item with the specified `id`
Inserts the `menuItem` to the `pos` position of the menu.
### Instance Events
Objects created with `new Menu` 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:
@@ -109,6 +133,11 @@ A `MenuItem[]` array containing the menu's items.
Each `Menu` consists of multiple [`MenuItem`](menu-item.md)s and each `MenuItem`
can have a submenu.
### Instance Events
Objects created with `new Menu` or returned by `Menu.buildFromTemplate` emit
the following events:
## Examples
The `Menu` class is only available in the main process, but you can also use it
@@ -230,7 +259,7 @@ menu.append(new MenuItem({label: 'MenuItem2', type: 'checkbox', checked: true}))
window.addEventListener('contextmenu', (e) => {
e.preventDefault()
menu.popup(remote.getCurrentWindow())
menu.popup({window: remote.getCurrentWindow()})
}, false)
</script>
```

View File

@@ -15,7 +15,7 @@ If you want to show Notifications from a renderer process you should use the [HT
Process: [Main](../glossary.md#main-process)
`Notification` is an
[EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter).
[EventEmitter](https://nodejs.org/api/events.html#events_class_events_eventemitter).
It creates a new `Notification` with native properties as set by the `options`.
@@ -39,7 +39,7 @@ Returns `Boolean` - Whether or not desktop notifications are supported on the cu
* `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.
* `actions` [NotificationAction[]](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.
### Instance Events

View File

@@ -39,3 +39,10 @@ Emitted when the system changes to AC power.
### Event: 'on-battery' _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()`.

View File

@@ -119,7 +119,7 @@ event is emitted.
To avoid this problem, ensure you clean up any references to renderer callbacks
passed to the main process. This involves cleaning up event handlers, or
ensuring the main process is explicitly told to deference callbacks that came
ensuring the main process is explicitly told to dereference callbacks that came
from a renderer process that is exiting.
## Accessing built-in modules in the main process
@@ -195,5 +195,5 @@ process.
The `process` object in the main process. This is the same as
`remote.getGlobal('process')` but is cached.
[rmi]: http://en.wikipedia.org/wiki/Java_remote_method_invocation
[rmi]: https://en.wikipedia.org/wiki/Java_remote_method_invocation
[enumerable-properties]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties

View File

@@ -189,7 +189,7 @@ feature. We are still not aware of the security implications of exposing some
electron renderer APIs to the preload script, but here are some things to
consider before rendering untrusted content:
- A preload script can accidentaly leak privileged APIs to untrusted code.
- A preload script can accidentally leak privileged APIs to untrusted code.
- Some bug in V8 engine may allow malicious code to access the renderer preload
APIs, effectively granting full access to the system through the `remote`
module.

View File

@@ -187,7 +187,7 @@ The `proxyBypassRules` is a comma separated list of rules described below:
Examples:
"127.0.1", "[0:0::1]", "[::1]", "http://[::1]:99"
* `IP_LITERAL "/" PREFIX_LENGHT_IN_BITS`
* `IP_LITERAL "/" PREFIX_LENGTH_IN_BITS`
Match any URL that is to an IP literal that falls between the
given range. IP range is specified using CIDR notation.
@@ -195,7 +195,7 @@ The `proxyBypassRules` is a comma separated list of rules described below:
Examples:
"192.168.1.1/16", "fefe:13::abc/33".
* `<local>`
* `<local>`
Match local addresses. The meaning of `<local>` is whether the
host matches one of: "127.0.0.1", "::1", "localhost".
@@ -293,6 +293,8 @@ win.webContents.session.setCertificateVerifyProc((request, callback) => {
'pointerLock', 'fullscreen', 'openExternal'.
* `callback` Function
* `permissionGranted` Boolean - Allow or deny the permission.
* `details` Object - Some properties are only available on certain permission types.
* `externalURL` String - The url of the `openExternal` request.
Sets the handler which can be used to respond to permission requests for the `session`.
Calling `callback(true)` will allow the permission and `callback(false)` will reject it.
@@ -317,7 +319,7 @@ Clears the host resolver cache.
#### `ses.allowNTLMCredentialsForDomains(domains)`
* `domains` String - A comma-seperated list of servers for which
* `domains` String - A comma-separated list of servers for which
integrated authentication is enabled.
Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate
@@ -356,8 +358,6 @@ Returns `String` - The user agent for this session.
* `callback` Function
* `result` Buffer - Blob data.
Returns `Blob` - The blob data associated with the `identifier`.
#### `ses.createInterruptedDownload(options)`
* `options` Object
@@ -384,6 +384,18 @@ the initial state will be `interrupted`. The download will start only when the
Clears the sessions HTTP authentication cache.
#### `ses.setPreloads(preloads)`
* `preloads` String[] - An array of absolute path to preload scripts
Adds scripts that will be executed on ALL web contents that are associated with
this session just before normal `preload` scripts run.
#### `ses.getPreloads()`
Returns `String[]` an array of paths to preload scripts that have been
registered.
### Instance Properties
The following properties are available on instances of `Session`:

View File

@@ -36,7 +36,7 @@ Open the given file in the desktop's default manner.
### `shell.openExternal(url[, options, callback])`
* `url` String - max 2081 characters on windows, or the function returns false.
* `url` String - Max 2081 characters on windows, or the function returns false.
* `options` Object (optional) _macOS_
* `activate` Boolean - `true` to bring the opened application to the
foreground. The default is `true`.

View File

@@ -1,4 +1,4 @@
# CrashReport Object
* `date` String
* `ID` Integer
* `date` Date
* `id` String

View File

@@ -7,7 +7,7 @@
| Action Type | Platform Support | Usage of `text` | Default `text` | Limitations |
|-------------|------------------|-----------------|----------------|-------------|
| `button` | macOS | Used as the label for the button | "Show" | Maximum of one button, if multiple are provided only the last is used. This action is also incompatible with `hasReply` and will be ignored if `hasReply` is `true`. |
| `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
@@ -15,6 +15,6 @@ 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`.
* App has it's `NSUserNotificationAlertStyle` set to `alert` in the `Info.plist`.
If either of these requirements are not met the button simply won't appear.

View File

@@ -0,0 +1,11 @@
# Transaction Object
* `transactionIdentifier` String
* `transactionDate` String
* `originalTransactionIdentifier` String
* `transactionState` String - The transaction sate (`"purchasing"`, `"purchased"`, `"failed"`, `"restored"`, or `"deferred"`)
* `errorCode` Integer
* `errorMessage` String
* `payment` Object
* `productIdentifier` String
* `quantity` Integer

View File

@@ -0,0 +1,5 @@
# WebSource Object
* `code` String
* `url` String (optional)
* `startLine` Integer (optional) - Default is 1.

View File

@@ -106,6 +106,12 @@ This is necessary for events such as `NSUserDefaultsDidChangeNotification`.
Same as `unsubscribeNotification`, but removes the subscriber from `NSNotificationCenter`.
### `systemPreferences.registerDefaults(defaults)` _macOS_
* `defaults` Object - a dictionary of (`key: value`) user defaults
Add the specified defaults to your application's `NSUserDefaults`.
### `systemPreferences.getUserDefault(key, type)` _macOS_
* `key` String

View File

@@ -8,7 +8,7 @@ Process: [Main](../tutorial/quick-start.md#main-process)
* `options` Object
* `items` ([TouchBarButton](touch-bar-button.md) | [TouchBarColorPicker](touch-bar-color-picker.md) | [TouchBarGroup](touch-bar-group.md) | [TouchBarLabel](touch-bar-label.md) | [TouchBarPopover](touch-bar-popover.md) | [TouchBarScrubber](touch-bar-scrubber.md) | [TouchBarSegmentedControl](touch-bar-segmented-control.md) | [TouchBarSlider](touch-bar-slider.md) | [TouchBarSpacer](touch-bar-spacer.md))[]
* `escapeItem` ([TouchBarButton](touch-bar-button.md) | [TouchBarColorPicker](touch-bar-color-picker.md) | [TouchBarGroup](touch-bar-group.md) | [TouchBarLabel](touch-bar-label.md) | [TouchBarPopover](touch-bar-popover.md) | [TouchBarScrubber](touch-bar-scrubber.md) | [TouchBarSegmentedControl](touch-bar-segmented-control.md) | [TouchBarSlider](touch-bar-slider.md) | [TouchBarSpacer](touch-bar-spacer.md)) (optional)
* `escapeItem` ([TouchBarButton](touch-bar-button.md) | [TouchBarColorPicker](touch-bar-color-picker.md) | [TouchBarGroup](touch-bar-group.md) | [TouchBarLabel](touch-bar-label.md) | [TouchBarPopover](touch-bar-popover.md) | [TouchBarScrubber](touch-bar-scrubber.md) | [TouchBarSegmentedControl](touch-bar-segmented-control.md) | [TouchBarSlider](touch-bar-slider.md) | [TouchBarSpacer](touch-bar-spacer.md) | null) (optional)
Creates a new touch bar with the specified items. Use
`BrowserWindow.setTouchBar` to add the `TouchBar` to a window.
@@ -26,7 +26,7 @@ The following properties are available on instances of `TouchBar`:
#### `touchBar.escapeItem`
The `TouchBarButton` that will replace the "esc" button on the touch bar when set.
A `TouchBarItem` that will replace the "esc" button on the touch bar when set.
Setting to `null` restores the default "esc" button. Changing this value
immediately updates the escape item in the touch bar.

View File

@@ -291,7 +291,7 @@ Calling `event.preventDefault` will prevent the page `keydown`/`keyup` events
and the menu shortcuts.
To only prevent the menu shortcuts, use
[`setIgnoreMenuShortcuts`](#contentssetignoremenushortcuts):
[`setIgnoreMenuShortcuts`](#contentssetignoremenushortcutsignore-experimental):
```javascript
const {BrowserWindow} = require('electron')
@@ -625,6 +625,28 @@ const options = {extraHeaders: 'pragma: no-cache\n'}
webContents.loadURL('https://github.com', options)
```
#### `contents.loadFile(filePath)`
* `filePath` String
Loads the given file in the window, `filePath` should be a path to
an HTML file relative to the root of your application. For instance
an app structure like this:
```sh
| root
| - package.json
| - src
| - main.js
| - index.html
```
Would require code like this
```js
win.loadFile('src/index.html')
```
#### `contents.downloadURL(url)`
* `url` String
@@ -809,7 +831,8 @@ Sends a request to get current zoom factor, the `callback` will be called with
Changes the zoom level to the specified level. The original size is 0 and each
increment above or below represents zooming 20% larger or smaller to default
limits of 300% and 50% of original size, respectively.
limits of 300% and 50% of original size, respectively. The formula for this is
`scale := 1.2 ^ level`.
#### `contents.getZoomLevel(callback)`
@@ -819,14 +842,6 @@ limits of 300% and 50% of original size, respectively.
Sends a request to get current zoom level, the `callback` will be called with
`callback(zoomLevel)`.
#### `contents.setZoomLevelLimits(minimumLevel, maximumLevel)`
* `minimumLevel` Number
* `maximumLevel` Number
**Deprecated:** Call `setVisualZoomLevelLimits` instead to set the visual zoom
level limits. This method will be removed in Electron 2.0.
#### `contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)`
* `minimumLevel` Number
@@ -1074,6 +1089,68 @@ win.webContents.on('devtools-opened', () => {
Removes the specified path from DevTools workspace.
#### `contents.setDevToolsWebContents(devToolsWebContents)`
* `devToolsWebContents` WebContents
Uses the `devToolsWebContents` as the target `WebContents` to show devtools.
The `devToolsWebContents` must not have done any navigation, and it should not
be used for other purposes after the call.
By default Electron manages the devtools by creating an internal `WebContents`
with native view, which developers have very limited control of. With the
`setDevToolsWebContents` method, developers can use any `WebContents` to show
the devtools in it, including `BrowserWindow`, `BrowserView` and `<webview>`
tag.
Note that closing the devtools does not destroy the `devToolsWebContents`, it
is caller's responsibility to destroy `devToolsWebContents`.
An example of showing devtools in a `<webview>` tag:
```html
<html>
<head>
<style type="text/css">
* { margin: 0; }
#browser { height: 70%; }
#devtools { height: 30%; }
</style>
</head>
<body>
<webview id="browser" src="https://github.com"></webview>
<webview id="devtools"></webview>
<script>
const browserView = document.getElementById('browser')
const devtoolsView = document.getElementById('devtools')
browserView.addEventListener('dom-ready', () => {
const browser = browserView.getWebContents()
browser.setDevToolsWebContents(devtoolsView.getWebContents())
browser.openDevTools()
})
</script>
</body>
</html>
```
An example of showing devtools in a `BrowserWindow`:
```js
const {app, BrowserWindow} = require('electron')
let win = null
let devtools = null
app.once('ready', () => {
win = new BrowserWindow()
devtools = new BrowserWindow()
win.loadURL('https://github.com')
win.webContents.setDevToolsWebContents(devtools.webContents)
win.webContents.openDevTools({mode: 'detach'})
})
```
#### `contents.openDevTools([options])`
* `options` Object (optional)
@@ -1083,6 +1160,9 @@ Removes the specified path from DevTools workspace.
Opens the devtools.
When `contents` is a `<webview>` tag, the `mode` would be `detach` by default,
explicitly passing an empty `mode` can force using last used dock state.
#### `contents.closeDevTools()`
Closes the devtools.
@@ -1288,7 +1368,7 @@ Set the size of the page. This is only supported for `<webview>` guest contents.
* `options` Object
* `normal` Object (optional) - Normal size of the page. This can be used in
combination with the [`disableguestresize`](web-view-tag.md#disableguestresize)
combination with the [`disableguestresize`](webview-tag.md#disableguestresize)
attribute to manually resize the webview guest contents.
* `width` Integer
* `height` Integer

View File

@@ -4,6 +4,10 @@
Process: [Renderer](../glossary.md#renderer-process)
`webFrame` export of the electron module is an instance of the `WebFrame`
class representing the top frame of the current `BrowserWindow`. Sub-frames can
be retrieved by certain properties and methods (e.g. `webFrame.firstChild`).
An example of zooming current page to 200%.
```javascript
@@ -14,7 +18,7 @@ webFrame.setZoomFactor(2)
## Methods
The `webFrame` module has the following methods:
The `WebFrame` class has the following instance methods:
### `webFrame.setZoomFactor(factor)`
@@ -39,14 +43,6 @@ limits of 300% and 50% of original size, respectively.
Returns `Number` - The current zoom level.
### `webFrame.setZoomLevelLimits(minimumLevel, maximumLevel)`
* `minimumLevel` Number
* `maximumLevel` Number
**Deprecated:** Call `setVisualZoomLevelLimits` instead to set the visual zoom
level limits. This method will be removed in Electron 2.0.
### `webFrame.setVisualZoomLevelLimits(minimumLevel, maximumLevel)`
* `minimumLevel` Number
@@ -145,6 +141,37 @@ In the browser window some HTML APIs like `requestFullScreen` can only be
invoked by a gesture from the user. Setting `userGesture` to `true` will remove
this limitation.
### `webFrame.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture, callback])`
* `worldId` Integer
* `scripts` [WebSource[]](structures/web-source.md)
* `userGesture` Boolean (optional) - Default is `false`.
* `callback` Function (optional) - Called after script has been executed.
* `result` Any
Work like `executeJavaScript` but evaluates `scripts` in isolated context.
### `webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp)`
* `worldId` Integer
* `csp` String
Set the content security policy of the isolated world.
### `webFrame.setIsolatedWorldHumanReadableName(worldId, name)`
* `worldId` Integer
* `name` String
Set the name of the isolated world. Useful in devtools.
### `webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin)`
* `worldId` Integer
* `securityOrigin` String
Set the security origin of the isolated world.
### `webFrame.getResourceUsage()`
Returns `Object`:
@@ -191,3 +218,49 @@ memory (i.e. you have navigated from a super heavy page to a mostly empty one,
and intend to stay there).
[spellchecker]: https://github.com/atom/node-spellchecker
### `webFrame.getFrameForSelector(selector)`
* `selector` String - CSS selector for a frame element.
Returns `WebFrame` - The frame element in `webFrame's` document selected by
`selector`, `null` would be returned if `selector` does not select a frame or
if the frame is not in the current renderer process.
### `webFrame.findFrameByName(name)`
* `name` String
Returns `WebFrame` - A child of `webFrame` with the supplied `name`, `null`
would be returned if there's no such frame or if the frame is not in the current
renderer process.
## Properties
### `webFrame.top`
A `WebFrame` representing top frame in frame hierarchy to which `webFrame`
belongs, the property would be `null` if top frame is not in the current
renderer process.
### `webFrame.opener`
A `WebFrame` representing the frame which opened `webFrame`, the property would
be `null` if there's no opener or opener is not in the current renderer process.
### `webFrame.parent`
A `WebFrame` representing parent frame of `webFrame`, the property would be
`null` if `webFrame` is top or parent is not in the current renderer process.
### `webFrame.firstChild`
A `WebFrame` representing the first child frame of `webFrame`, the property
would be `null` if `webFrame` has no children or if first child is not in the
current renderer process.
### `webFrame.nextSibling`
A `WebFrame` representing next sibling frame, the property would be `null` if
`webFrame` is the last frame its parent or if the next sibling is not in the
current renderer process.

View File

@@ -528,7 +528,7 @@ can be obtained by subscribing to [`found-in-page`](webview-tag.md#event-found-i
### `<webview>.stopFindInPage(action)`
* `action` String - Specifies the action to take place when ending
[`<webview>.findInPage`](webview-tag.md#webviewtagfindinpage) request.
[`<webview>.findInPage`](#webviewfindinpagetext-options) request.
* `clearSelection` - Clear the selection.
* `keepSelection` - Translate the selection into a normal selection.
* `activateSelection` - Focus and click the selection node.
@@ -579,7 +579,7 @@ Send an asynchronous message to renderer process via `channel`, you can also
send arbitrary arguments. The renderer process can handle the message by
listening to the `channel` event with the [`ipcRenderer`](ipc-renderer.md) module.
See [webContents.send](web-contents.md#webcontentssendchannel-args) for
See [webContents.send](web-contents.md#contentssendchannel-arg1-arg2-) for
examples.
### `<webview>.sendInputEvent(event)`
@@ -588,7 +588,7 @@ examples.
Sends an input `event` to the page.
See [webContents.sendInputEvent](web-contents.md#webcontentssendinputeventevent)
See [webContents.sendInputEvent](web-contents.md#contentssendinputeventevent)
for detailed description of `event` object.
### `<webview>.setZoomFactor(factor)`
@@ -752,7 +752,7 @@ Returns:
* `finalUpdate` Boolean
Fired when a result is available for
[`webview.findInPage`](webview-tag.md#webviewtagfindinpage) request.
[`webview.findInPage`](#webviewfindinpagetext-options) request.
```javascript
const webview = document.querySelector('webview')

View File

@@ -8,7 +8,7 @@ Follow the guidelines below for building Electron on Linux.
* Python 2.7.x. Some distributions like CentOS 6.x still use Python 2.6.x
so you may need to check your Python version with `python -V`.
* Node.js. There are various ways to install Node. You can download
source code from [nodejs.org](http://nodejs.org) and compile it.
source code from [nodejs.org](https://nodejs.org) and compile it.
Doing so permits installing Node on your own home directory as a standard user.
Or try repositories such as [NodeSource](https://nodesource.com/blog/nodejs-v012-iojs-and-the-nodesource-linux-repositories).
* [clang](https://clang.llvm.org/get_started.html) 3.4 or later.
@@ -17,7 +17,7 @@ Follow the guidelines below for building Electron on Linux.
On Ubuntu, install the following libraries:
```sh
$ sudo apt-get install build-essential clang libdbus-1-dev libgtk2.0-dev \
$ sudo apt-get install build-essential clang libdbus-1-dev libgtk-3-dev \
libnotify-dev libgnome-keyring-dev libgconf2-dev \
libasound2-dev libcap-dev libcups2-dev libxtst-dev \
libxss1 libnss3-dev gcc-multilib g++-multilib curl \
@@ -27,7 +27,7 @@ $ sudo apt-get install build-essential clang libdbus-1-dev libgtk2.0-dev \
On RHEL / CentOS, install the following libraries:
```sh
$ sudo yum install clang dbus-devel gtk2-devel libnotify-devel \
$ sudo yum install clang dbus-devel gtk3-devel libnotify-devel \
libgnome-keyring-devel xorg-x11-server-utils libcap-devel \
cups-devel libXtst-devel alsa-lib-devel libXrandr-devel \
GConf2-devel nss-devel
@@ -36,7 +36,7 @@ $ sudo yum install clang dbus-devel gtk2-devel libnotify-devel \
On Fedora, install the following libraries:
```sh
$ sudo dnf install clang dbus-devel gtk2-devel libnotify-devel \
$ sudo dnf install clang dbus-devel gtk3-devel libnotify-devel \
libgnome-keyring-devel xorg-x11-server-utils libcap-devel \
cups-devel libXtst-devel alsa-lib-devel libXrandr-devel \
GConf2-devel nss-devel
@@ -155,12 +155,12 @@ information may help you.
### Building `libchromiumcontent` locally
To avoid using the prebuilt binaries of `libchromiumcontent`, you can build `libchromiumcontent` locally. To do so, follow these steps:
To avoid using the prebuilt binaries of `libchromiumcontent`, you can build `libchromiumcontent` locally. To do so, follow these steps:
1. Install [depot_tools](https://chromium.googlesource.com/chromium/src/+/master/docs/linux_build_instructions.md#Install)
2. Install [additional build dependencies](https://chromium.googlesource.com/chromium/src/+/master/docs/linux_build_instructions.md#Install-additional-build-dependencies)
3. Fetch the git submodules:
```sh
$ git submodule update --init --recursive
```
@@ -179,11 +179,11 @@ $ ./script/build.py -c R
### Using system `clang` instead of downloaded `clang` binaries
By default Electron is built with prebuilt
By default Electron is built with prebuilt
[`clang`](https://clang.llvm.org/get_started.html) binaries provided by the
Chromium project. If for some reason you want to build with the `clang`
installed in your system, you can call `bootstrap.py` with `--clang_dir=<path>`
switch. By passing it the build script will assume the `clang` binaries reside
Chromium project. If for some reason you want to build with the `clang`
installed in your system, you can call `bootstrap.py` with `--clang_dir=<path>`
switch. By passing it the build script will assume the `clang` binaries reside
in `<path>/bin/`.
For example if you installed `clang` under `/user/local/bin/clang`:
@@ -208,8 +208,8 @@ $ ./script/build.py -c R
### Environment variables
Apart from `CC` and `CXX`, you can also set following environment variables to
custom the building configurations:
Apart from `CC` and `CXX`, you can also set the following environment variables to
customise the build configuration:
* `CPPFLAGS`
* `CPPFLAGS_host`
@@ -226,4 +226,4 @@ custom the building configurations:
* `LDFLAGS`
The environment variables have to be set when executing the `bootstrap.py`
script, it won't work in the `build.py` script.
script, it won't work in the `build.py` script.

View File

@@ -6,7 +6,7 @@ Follow the guidelines below for building Electron on macOS.
* macOS >= 10.11.6
* [Xcode](https://developer.apple.com/technologies/tools/) >= 8.2.1
* [node.js](http://nodejs.org) (external)
* [node.js](https://nodejs.org) (external)
If you are using the Python downloaded by Homebrew, you also need to install
the following Python modules:

View File

@@ -8,7 +8,7 @@ Follow the guidelines below for building Electron on Windows.
* Visual Studio 2015 Update 3 - [download VS 2015 Community Edition for
free](https://www.visualstudio.com/vs/older-downloads/)
* [Python 2.7](http://www.python.org/download/releases/2.7/)
* [Node.js](http://nodejs.org/download/)
* [Node.js](https://nodejs.org/download/)
* [Git](http://git-scm.com)
* [Debugging Tools for Windows](https://msdn.microsoft.com/en-us/library/windows/hardware/ff551063.aspx)
if you plan on creating a full distribution since `symstore.exe` is used for
@@ -143,7 +143,7 @@ Try reinstalling 32bit Node.js.
### Error: ENOENT, stat 'C:\Users\USERNAME\AppData\Roaming\npm'
Simply making that directory [should fix the problem](http://stackoverflow.com/a/25095327/102704):
Simply making that directory [should fix the problem](https://stackoverflow.com/a/25095327/102704):
```powershell
$ mkdir ~\AppData\Roaming\npm

View File

@@ -5,10 +5,27 @@ These are the style guidelines for coding in Electron.
You can run `npm run lint` to show any style issues detected by `cpplint` and
`eslint`.
## General Code
* End files with a newline.
* Place requires in the following order:
* Built in Node Modules (such as `path`)
* Built in Electron Modules (such as `ipc`, `app`)
* Local Modules (using relative paths)
* Place class properties in the following order:
* Class methods and properties (methods starting with a `@`)
* Instance methods and properties
* Avoid platform-dependent code:
* Use `path.join()` to concatenate filenames.
* Use `os.tmpdir()` rather than `/tmp` when you need to reference the
temporary directory.
* Using a plain `return` when returning explicitly at the end of a function.
* Not `return null`, `return undefined`, `null`, or `undefined`
## C++ and Python
For C++ and Python, we follow Chromium's [Coding
Style](http://www.chromium.org/developers/coding-style). You can use
Style](https://www.chromium.org/developers/coding-style). You can use
[clang-format](clang-format.md) to format the C++ code automatically. There is
also a script `script/cpplint.py` to check whether all files conform.
@@ -21,9 +38,16 @@ document. The document mentions some special types, scoped types (that
automatically release their memory when going out of scope), logging mechanisms
etc.
## Documentation
* Write [remark](https://github.com/remarkjs/remark) markdown style
You can run `npm run lint-docs` to ensure that your documentation changes are
formatted correctly.
## JavaScript
* Write [standard](http://npm.im/standard) JavaScript style.
* Write [standard](https://npm.im/standard) JavaScript style.
* File names should be concatenated with `-` instead of `_`, e.g.
`file-name.js` rather than `file_name.js`, because in
[github/atom](https://github.com/github/atom) module names are usually in

View File

@@ -0,0 +1,52 @@
## Debugging with XCode
### Build Debug Electron with Release libchromiumcontent
You can create a debug build of electron by following [build instructions for macOS](build-instructions-osx.md).
The bootstrap process will download Release version of libchromiumcontent by default,
so you will not be able to step through the chromium source.
### Build Debug Electron with Debug libchromiumcontent
If you want to debug and step through libchromiumcontent, you will have to run the
bootsrap script with the `--build_debug_libcc` argument.
```sh
$ cd electron
$ ./script/bootstrap.py -v --build_debug_libcc
```
This can take a significant amount of time depending on build machine as it has to
build all of the libchromium source.
Once, the lib is built, create a symlink to the built directory under download
`ln -s vendor/libchromiumcontent/dist/main/shared_library vendor/download/libchromiumcontent/shared_library`
Electron debug builds will use this shared library to link against.
```sh
$ ./script/build.py -c D --libcc
```
This will build debug electron with debug version of libchromiumcontent.
### Generate xcode project for debugging sources (cannot build code from xcode)
Run the update script with the --xcode argument.
```sh
$ ./script/update.py --xcode
```
This will generate the electron.ninjs.xcworkspace. You will have to open this workspace
to set breakpoints and inspect.
### Debugging and breakpoints
Launch electron app after build.
You can now open the xcode workspace created above and attach to the electron process
through the Debug > Attach To Process > Electron debug menu. [Note: If you want to debug
the renderer process, you need to attach to the Electron Helper as well.]
You can now set breakpoints in any of the indexed files. However, you will not be able
to set breakpoints directly in the chromium source.
To set break points in the chromium source, you can choose Debug > Breakpoints > Create
Symbolic Breakpoint and set any function name as the symbol. This will set the breakpoint
for all functions with that name, from all the classes if there are more than one.
You can also do this step of setting break points prior to attaching the debugger,
however, actual breakpoints for symbolic breakpoint functions may not show up until the
debugger is attached to the app.

View File

@@ -5,6 +5,8 @@ by your JavaScript application, but instead by Electron itself, debugging can
be a little bit tricky, especially for developers not used to native/C++
debugging. However, using lldb, and the Electron source code, it is fairly easy
to enable step-through debugging with breakpoints inside Electron's source code.
You can also use [XCode for debugging](debugging-instructions-macos-xcode.md) if
you prefer a graphical interface.
## Requirements

109
docs/development/issues.md Normal file
View File

@@ -0,0 +1,109 @@
# Issues In Electron
# Issues
* [How to Contribute in Issues](#how-to-contribute-in-issues)
* [Asking for General Help](#asking-for-general-help)
* [Submitting a Bug Report](#submitting-a-bug-report)
* [Triaging a Bug Report](#triaging-a-bug-report)
* [Resolving a Bug Report](#resolving-a-bug-report)
## How to Contribute in Issues
For any issue, there are fundamentally three ways an individual can
contribute:
1. By opening the issue for discussion: If you believe that you have found
a new bug in Electron, you should report it by creating a new issue in
the `electron/electron` issue tracker.
2. By helping to triage the issue: You can do this either by providing
assistive details (a reproducible test case that demonstrates a bug) or by
providing suggestions to address the issue.
3. By helping to resolve the issue: This can be done by demonstrating
that the issue is not a bug or is fixed; but more often, by opening
a pull request that changes the source in `electron/electron` in a
concrete and reviewable manner.
## Asking for General Help
Because the level of activity in the `electron/electron` repository is
so high, questions or requests for general help using Electron should
be directed at the [community slack channel](https://atomio.slack.com)
or the [forum](https://discuss.atom.io/c/electron).
## Submitting a Bug Report
When opening a new issue in the `electron/electron` issue tracker, users
will be presented with a template that should be filled in.
```markdown
<!--
Thanks for opening an issue! A few things to keep in mind:
- The issue tracker is only for bugs and feature requests.
- Before reporting a bug, please try reproducing your issue against
the latest version of Electron.
- If you need general advice, join our Slack: http://atom-slack.herokuapp.com
-->
* Electron version:
* Operating system:
### Expected behavior
<!-- What do you think should happen? -->
### Actual behavior
<!-- What actually happens? -->
### How to reproduce
<!--
Your best chance of getting this bug looked at quickly is to provide a REPOSITORY that can be cloned and run.
You can fork https://github.com/electron/electron-quick-start and include a link to the branch with your changes.
If you provide a URL, please list the commands required to clone/setup/run your repo e.g.
$ git clone $YOUR_URL -b $BRANCH
$ npm install
$ npm start || electron .
-->
```
If you believe that you have found a bug in Electron, please fill out this
form to the best of your ability.
The two most important pieces of information needed to evaluate the report are
a description of the bug and a simple test case to recreate it. It easier to fix
a bug if it can be reproduced.
See [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
## Triaging a Bug Report
It's common for open issues to involve discussion. Some contributors may
have differing opinions, including whether the behavior is a bug or feature.
This discussion is part of the process and should be kept focused, helpful,
and professional.
Terse responses that provide neither additional context nor supporting detail
are not helpful or professional. To many, such responses are annoying and
unfriendly.
Contributors are encouraged to solve issues collaboratively and help one
another make progress. If encounter an issue that you feel is invalid, or
which contains incorrect information, explain *why* you feel that way with
additional supporting context, and be willing to be convinced that you may
be wrong. By doing so, we can often reach the correct outcome faster.
## Resolving a Bug Report
Most issues are resolved by opening a pull request. The process for opening and
reviewing a pull request is similar to that of opening and triaging issues, but
carries with it a necessary review and approval workflow that ensures that the
proposed changes meet the minimal quality and functional guidelines of the
Electron project.

View File

@@ -0,0 +1,235 @@
# Pull Requests
* [Dependencies](#dependencies)
* [Setting up your local environment](#setting-up-your-local-environment)
* [Step 1: Fork](#step-1-fork)
* [Step 2: Build](#step-2-build)
* [Step 3: Branch](#step-3-branch)
* [Making Changes](#making-changes)
* [Step 4: Code](#step-4-code)
* [Step 5: Commit](#step-5-commit)
* [Commit message guidelines](#commit-message-guidelines)
* [Step 6: Rebase](#step-6-rebase)
* [Step 7: Test](#step-7-test)
* [Step 8: Push](#step-8-push)
* [Step 9: Opening the Pull Request](#step-8-opening-the-pull-request)
* [Step 10: Discuss and Update](#step-9-discuss-and-update)
* [Approval and Request Changes Workflow](#approval-and-request-changes-workflow)
* [Step 11: Landing](#step-10-landing)
* [Continuous Integration Testing](#continuous-integration-testing)
## Setting up your local environment
### Step 1: Fork
Fork the project [on GitHub](https://github.com/electron/electron) and clone your fork
locally.
```sh
$ git clone git@github.com:username/electron.git
$ cd electron
$ git remote add upstream https://github.com/electron/electron.git
$ git fetch upstream
```
### Step 2: Build
Build steps and dependencies differ slightly depending on your operating system.
See these detailed guides on building Electron locally:
* [Building on MacOS](https://electronjs.org/docs/development/build-instructions-osx)
* [Building on Linux](https://electronjs.org/docs/development/build-instructions-linux)
* [Building on Windows](https://electronjs.org/docs/development/build-instructions-windows)
Once you've built the project locally, you're ready to start making changes!
### Step 3: Branch
To keep your development environment organized, create local branches to
hold your work. These should be branched directly off of the `master` branch.
```sh
$ git checkout -b my-branch -t upstream/master
```
## Making Changes
### Step 4: Code
Most pull requests opened against the `electron/electron` repository include
changes to either the C/C++ code in the `atom/` or `brightray/` folders,
the JavaScript code in the `lib/` folder, the documentation in `docs/api/`
or tests in the `spec/` folder.
Please be sure to run `npm run lint` from time to time on any code changes
to ensure that they follow the project's code style.
See [coding style](https://electronjs.org/docs/development/coding-style) for
more information about best practice when modifying code in different parts of
the project.
### Step 5: Commit
It is recommended to keep your changes grouped logically within individual
commits. Many contributors find it easier to review changes that are split
across multiple commits. There is no limit to the number of commits in a
pull request.
```sh
$ git add my/changed/files
$ git commit
```
Note that multiple commits often get squashed when they are landed.
#### Commit message guidelines
A good commit message should describe what changed and why.
1. The first line should:
- contain a short description of the change (preferably 50 characters or less,
and no more than 72 characters)
- be entirely in lowercase with the exception of proper nouns, acronyms, and
the words that refer to code, like function/variable names
Examples:
- `updated osx build documentation for new sdk`
- `fixed typos in atom_api_menu.h`
2. Keep the second line blank.
3. Wrap all other lines at 72 columns.
See [this article](https://chris.beams.io/posts/git-commit/) for more examples
of how to write good git commit messages.
### Step 6: Rebase
Once you have committed your changes, it is a good idea to use `git rebase`
(not `git merge`) to synchronize your work with the main repository.
```sh
$ git fetch upstream
$ git rebase upstream/master
```
This ensures that your working branch has the latest changes from `electron/electron`
master.
### Step 7: Test
Bug fixes and features should always come with tests. A
[testing guide](https://electronjs.org/docs/development/testing) has been
provided to make the process easier. Looking at other tests to see how they
should be structured can also help.
Before submitting your changes in a pull request, always run the full
test suite. To run the tests:
```sh
$ npm run test
```
Make sure the linter does not report any issues and that all tests pass.
Please do not submit patches that fail either check.
If you are updating tests and just want to run a single spec to check it:
```sh
$ npm run test -match=menu
```
The above would only run spec modules matching `menu`, which is useful for
anyone who's working on tests that would otherwise be at the very end of
the testing cycle.
### Step 8: Push
Once your commits are ready to go -- with passing tests and linting --
begin the process of opening a pull request by pushing your working branch
to your fork on GitHub.
```sh
$ git push origin my-branch
```
### Step 9: Opening the Pull Request
From within GitHub, opening a new pull request will present you with a template
that should be filled out:
```markdown
<!--
Thank you for your pull request. Please provide a description above and review
the requirements below.
Bug fixes and new features should include tests and possibly benchmarks.
Contributors guide: https://github.com/electron/electron/blob/master/CONTRIBUTING.md
-->
```
### Step 10: Discuss and update
You will probably get feedback or requests for changes to your pull request.
This is a big part of the submission process so don't be discouraged! Some
contributors may sign off on the pull request right away. Others may have
detailed comments or feedback. This is a necessary part of the process
in order to evaluate whether the changes are correct and necessary.
To make changes to an existing pull request, make the changes to your local
branch, add a new commit with those changes, and push those to your fork.
GitHub will automatically update the pull request.
```sh
$ git add my/changed/files
$ git commit
$ git push origin my-branch
```
There are a number of more advanced mechanisms for managing commits using
`git rebase` that can be used, but are beyond the scope of this guide.
Feel free to post a comment in the pull request to ping reviewers if you are
awaiting an answer on something. If you encounter words or acronyms that
seem unfamiliar, refer to this
[glossary](https://sites.google.com/a/chromium.org/dev/glossary).
#### Approval and Request Changes Workflow
All pull requests require approval from a [Code Owner](https://github.com/orgs/electron/teams/code-owners) of the area you
modified in order to land. Whenever a maintainer reviews a pull request they
may request changes. These may be small, such as fixing a typo, or may involve
substantive changes. Such requests are intended to be helpful, but at times
may come across as abrupt or unhelpful, especially if they do not include
concrete suggestions on *how* to change them.
Try not to be discouraged. If you feel that a review is unfair, say so or seek
the input of another project contributor. Often such comments are the result of
a reviewer having taken insufficient time to review and are not ill-intended.
Such difficulties can often be resolved with a bit of patience. That said,
reviewers should be expected to provide helpful feeback.
### Step 11: Landing
In order to land, a pull request needs to be reviewed and approved by
at least one Electron Code Owner and pass CI. After that, if there are no
objections from other contributors, the pull request can be merged.
Congratulations and thanks for your contribution!
### Continuous Integration Testing
Every pull request is tested on the Continuous Integration (CI) system to
confirm that it works on Electron's supported platforms.
Ideally, the pull request will pass ("be green") on all of CI's platforms.
This means that all tests pass and there are no linting errors. However,
it is not uncommon for the CI infrastructure itself to fail on specific
platforms or for so-called "flaky" tests to fail ("be red"). Each CI
failure must be manually inspected to determine the cause.
CI starts automatically when you open a pull request, but only
[Releasers](https://github.com/orgs/electron/teams/releasers/members)
can restart a CI run. If you believe CI is giving a false negative,
ask a Releaser to restart the tests.

View File

@@ -5,7 +5,7 @@ about the functions contained in executables and dynamic libraries and provide
you with information to get clean call stacks. A Symbol Server allows the
debugger to load the correct symbols, binaries and sources automatically without
forcing users to download large debugging files. The server functions like
[Microsoft's symbol server](http://support.microsoft.com/kb/311503) so the
[Microsoft's symbol server](https://support.microsoft.com/kb/311503) so the
documentation there can be useful.
Note that because released Electron builds are heavily optimized, debugging is
@@ -38,7 +38,7 @@ or by typing the `.sympath` command. If you would like to get symbols from
Microsoft's symbol server as well, you should list that first:
```powershell
SRV*c:\code\symbols\*http://msdl.microsoft.com/download/symbols;SRV*c:\code\symbols\*https://electron-symbols.githubapp.com
SRV*c:\code\symbols\*https://msdl.microsoft.com/download/symbols;SRV*c:\code\symbols\*https://electron-symbols.githubapp.com
```
## Using the symbol server in Visual Studio

View File

@@ -4,12 +4,12 @@ The source code of Electron is separated into a few parts, mostly
following Chromium on the separation conventions.
You may need to become familiar with [Chromium's multi-process
architecture](http://dev.chromium.org/developers/design-documents/multi-process-architecture)
architecture](https://dev.chromium.org/developers/design-documents/multi-process-architecture)
to understand the source code better.
## Structure of Source Code
```sh
```diff
Electron
├── atom/ - C++ source code.
| ├── app/ - System entry code.
@@ -30,6 +30,7 @@ Electron
| loop into Chromium's message loop.
| └── api/ - The implementation of common APIs, and foundations of
| Electron's built-in modules.
├── brightray/ - Thin shim over libcc that makes it easier to use.
├── chromium_src/ - Source code copied from Chromium. See below.
├── default_app/ - The default page to show when Electron is started without
| providing an app.
@@ -49,15 +50,15 @@ Electron
## `/chromium_src`
The files in `/chromium_src` tend to be pieces of Chromium that aren't part of
the content layer. For example to implement Pepper API, we need some wiring
similar to what official Chrome does. We could have built the relevant
sources as a part of [libcc](../glossary.md#libchromiumcontent) but most
often we don't require all the features (some tend to be proprietary,
analytics stuff) so we just took parts of the code. These could have easily
been patches in libcc, but at the time when these were written the goal of
libcc was to maintain very minimal patches and chromium_src changes tend to be
big ones. Also, note that these patches can never be upstreamed unlike other
The files in `/chromium_src` tend to be pieces of Chromium that aren't part of
the content layer. For example to implement Pepper API, we need some wiring
similar to what official Chrome does. We could have built the relevant
sources as a part of [libcc](../glossary.md#libchromiumcontent) but most
often we don't require all the features (some tend to be proprietary,
analytics stuff) so we just took parts of the code. These could have easily
been patches in libcc, but at the time when these were written the goal of
libcc was to maintain very minimal patches and chromium_src changes tend to be
big ones. Also, note that these patches can never be upstreamed unlike other
libcc patches we maintain now.
## Structure of Other Directories

View File

@@ -0,0 +1,44 @@
# Testing
We aim to keep the code coverage of Electron high. We ask that all pull
request not only pass all existing tests, but ideally also add new tests
to cover changed code and new scenarios. Ensuring that we capture as
many code paths and use cases of Electron as possible ensures that we
all ship apps with fewer bugs.
This repository comes with linting rules for both JavaScript and C++
as well as unit and integration tests. To learn more about Electron's
coding style, please see the [coding-style(coding-style.md) document.
## Linting
To ensure that your JavaScript is in compliance with the Electron coding
style, run `npm run lint-js`, which will run `standard` against both
Electron itself as well as the unit tests. If you are using an editor
with a plugin/addon system, you might want to use one of the many
[StandardJS addons][standard-addons] to be informed of coding style
violations before you ever commit them.
To run `standard` with parameters, run `npm run lint-js --` followed by
arguments you want passed to `standard`.
To ensure that your C++ is in compliance with the Electron coding style,
run `npm run lint-cpp`, which runs a `cpplint` script. We recommend that
you use `clang-format` and prepared [a short tutorial](clang-format.md).
There is not a lot of Python in this repository, but it too is governed
by coding style rules. `npm run lint-py` will check all Python, using
`pylint` to do so.
## Unit Tests
To run all unit tests, run `npm run test`. The unit tests are an Electron
app (surprise!) that can be found in the `spec` folder. Note that it has
its own `package.json` and that its dependencies are therefore not defined
in the top-level `package.json`.
To run only a selected number of tests, run `npm run test -match=NAME`,
replacing the `NAME` with the file name of the test suite you would like
to run. As an example: If you want to run only IPC suites, you would run
`npm run test -match=ipc`.
[standard-addons]: https://standardjs.com/#are-there-text-editor-plugins

View File

@@ -12,10 +12,11 @@ This is an overview of the steps needed to upgrade Chromium in Electron.
## Upgrade `libcc` to a new Chromium version
1. Get the code and initialize the project:
- ```sh
```sh
$ git clone git@github.com:electron/libchromiumcontent.git
$ cd libchromiumcontent
$ ./script/bootstrap -v```
$ ./script/bootstrap -v
```
2. Update the Chromium snapshot
- Choose a version number from [OmahaProxy](https://omahaproxy.appspot.com/)
and update the `VERSION` file with it
@@ -36,7 +37,7 @@ This is an overview of the steps needed to upgrade Chromium in Electron.
- If some patches are no longer compatible with the Chromium code,
fix compilation errors.
6. When the build succeeds, create a `dist` for Electron
- `$ ./script/create-dist --no_zip`
- `$ ./script/create-dist --no_zip`
- It will create a `dist/main` folder in the libcc repo's root.
You will need this to build Electron.
7. (Optional) Update script contents if there are errors resulting from files
@@ -47,18 +48,18 @@ This is an overview of the steps needed to upgrade Chromium in Electron.
## Update Electron's code
1. Get the code:
- ```sh
$ git clone git@github.com:electron/electron.git
$ cd electron
```
```sh
$ git clone git@github.com:electron/electron.git
$ cd electron
```
2. If you have libcc built on your machine in its own repo,
tell Electron to use it:
- ```sh
$ ./script/bootstrap.py -v \
--libcc_source_path <libcc_folder>/src \
--libcc_shared_library_path <libcc_folder>/shared_library \
--libcc_static_library_path <libcc_folder>/static_library
```
```sh
$ ./script/bootstrap.py -v \
--libcc_source_path <libcc_folder>/src \
--libcc_shared_library_path <libcc_folder>/shared_library \
--libcc_static_library_path <libcc_folder>/static_library
```
3. If you haven't yet built libcc but it's already supposed to be upgraded
to a new Chromium, bootstrap Electron as usual
`$ ./script/bootstrap.py -v`
@@ -106,7 +107,7 @@ Follow all the steps above to fix Electron code on all supported platforms.
If there are any compilation errors related to the Crashpad, it probably means
you need to update the fork to a newer revision. See
[Upgrading Crashpad](https://github.com/electron/electron/tree/master/docs/development/upgrading-crashpad.md)
[Upgrading Crashpad](upgrading-crashpad.md)
for instructions on how to do that.
@@ -115,7 +116,7 @@ for instructions on how to do that.
Upgrade `vendor/node` to the Node release that corresponds to the v8 version
used in the new Chromium release. See the v8 versions in Node on
See [Upgrading Node](https://github.com/electron/electron/tree/master/docs/development/upgrading-node.md)
See [Upgrading Node](upgrading-node.md)
for instructions on this.
## Verify ffmpeg support

View File

@@ -2,7 +2,7 @@
1. Get the version of crashpad that we're going to use.
- `libcc/src/third_party/crashpad/README.chromium` will have a line `Revision:` with a checksum
- We need to check out the correponding branch.
- We need to check out the corresponding branch.
- Clone Google's crashpad (https://chromium.googlesource.com/crashpad/crashpad)
- `git clone https://chromium.googlesource.com/crashpad/crashpad`
- Check out the branch with the revision checksum:
@@ -16,10 +16,10 @@
2. Make a checklist of the Electron patches that need to be applied
with `git log --oneline`
- Or view http://github.com/electron/crashpad/commits/previous-branch-name
- Or view https://github.com/electron/crashpad/commits/previous-branch-name
3. For each patch:
- In `electron-crashpad-vA.B.C.D`, cherry-pick the patch's checksum
- In `electron-crashpad-vA.B.C.D`, cherry-pick the patch's checksum
- `git cherry-pick <checksum>`
- Resolve any conflicts
- Make sure it builds then add, commit, and push work to electron's crashpad fork
@@ -37,6 +37,3 @@
6. Push changes to submodule reference
- (From electron root) `git add vendor/crashpad`
- `git push origin upgrade-to-chromium-62`

View File

@@ -3,8 +3,8 @@
## Discussion
One upgrade issue is building all of Electron with a single copy
of V8 to ensure compatability. This is important because
upstream Node and [libchromiumcontent](upgrading-chrome.md)
of V8 to ensure compatibility. This is important because
upstream Node and [libchromiumcontent](upgrading-chromium.md)
both use their own versions of V8.
Upgrading Node is much easier than upgrading libchromiumcontent,
@@ -38,9 +38,10 @@ So in short, the primary steps are:
## Updating Electron's Node [fork](https://github.com/electron/node)
1. Create a branch in https://github.com/electron/node: `electron-node-vX.X.X`
1. Ensure that `master` on `electron/node` has updated release tags from `nodejs/node`
2. Create a branch in https://github.com/electron/node: `electron-node-vX.X.X` where the base that you're branching from is the tag for the desired update
- `vX.X.X` Must use a version of node compatible with our current version of chromium
2. Re-apply our commits from the previous version of node we were using (`vY.Y.Y`) to `v.X.X.X`
3. Re-apply our commits from the previous version of node we were using (`vY.Y.Y`) to `v.X.X.X`
- Check release tag and select the range of commits we need to re-apply
- Cherry-pick commit range:
1. Checkout both `vY.Y.Y` & `v.X.X.X`
@@ -82,7 +83,7 @@ We need to generate a patch file from each patch applied to V8.
Manually edit the `.patch` file to match upstream V8's directory:
- If a diff section has no instances of `deps/V8`, remove it altogether.
- We dont want those patches because were only patching V8.
- Replace instances of `a/deps/v8`/filename.ext` with `a/filename.ext`
- Replace instances of `a/deps/v8/filename.ext` with `a/filename.ext`
- This is needed because upstream Node keeps its V8 files in a subdirectory
- Ensure that local status is clean: `git status` to make sure there are no unstaged changes.
- Confirm that the patch applies cleanly with
@@ -96,7 +97,7 @@ We need to generate a patch file from each patch applied to V8.
- `mv test.patch patches/v8/xxx-patch_name.patch`
- Add the patched code to the index _without_ committing:
- `cd src/v8 && git add . && cd ../..`
- We don't want to commit the changes (they're kept in the patchfiles)
- We don't want to commit the changes (they're kept in the patchfiles)
but need them locally so that they don't show up in subsequent diffs
while we iterate through more patches
- Add the patch file to the index:
@@ -105,20 +106,20 @@ We need to generate a patch file from each patch applied to V8.
- `git commit patches/v8/`
8. Update `patches/v8/README.md` with references to all new patches that have been added so that the next person will know which need to be removed.
9. Update Electron's submodule references:
- ```sh
cd electron/vendor/node
electron/vendor/node$ git fetch
electron/vendor/node$ git checkout electron-node-vA.B.C
electron/vendor/node$ cd ../libchromiumcontent
electron/vendor/libchromiumcontent$ git fetch
electron/vendor/libchromiumcontent$ git checkout upgrade-to-chromium-X
electron/vendor/libchromiumcontent$ cd ../..
electron$ git add vendor
electron$ git commit -m "update submodule referefences for node and libc"
electron$ git pso upgrade-to-chromium-62
electron$ script/bootstrap.py -d
electron$ script/build.py -c -D
```
```sh
$ cd electron/vendor/node
electron/vendor/node$ git fetch
electron/vendor/node$ git checkout electron-node-vA.B.C
electron/vendor/node$ cd ../libchromiumcontent
electron/vendor/libchromiumcontent$ git fetch
electron/vendor/libchromiumcontent$ git checkout upgrade-to-chromium-X
electron/vendor/libchromiumcontent$ cd ../..
electron$ git add vendor
electron$ git commit -m "update submodule referefences for node and libc"
electron$ git pso upgrade-to-chromium-62
electron$ script/bootstrap.py -d
electron$ script/build.py -c -D
```
## Notes
@@ -143,16 +144,3 @@ We need to generate a patch file from each patch applied to V8.
- Building node:
- Theres a chance we need to change our build configuration
to match the build flags that node wants in `node/common.gypi`

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

View File

@@ -230,4 +230,4 @@ a module or a class.
## Documentation Translations
See [electron/electron-i18n](https://github.com/electron/electron-i18n#readme)
See [electron/i18n](https://github.com/electron/i18n#readme)

View File

@@ -27,7 +27,11 @@ In Electron, Node.js and Chromium share a single V8 instance—usually the versi
### Versioning
Due to the hard dependency on Node.js and Chromium, Electron is in a tricky versioning position and [does not follow `semver`](http://semver.org). You should therefore always reference a specific version of Electron. [Read more about Electron's versioning](https://electronjs.org/docs/tutorial/electron-versioning) or see the [versions currently in use](https://electronjs.org/#electron-versions).
As of version 2.0 Electron [follows `semver`](https://semver.org).
For most applications, and using any recent version of npm,
running `$ npm install electron` will do the right thing.
The version update process is detailed explicitly in our [Versioning Doc](electron-versioning.md).
### LTS
@@ -50,8 +54,8 @@ Below are milestones in Electron's history.
| :calendar: | :tada: |
| --- | --- |
| **April 2013**| [Atom Shell is started](https://github.com/electron/electron/commit/6ef8875b1e93787fa9759f602e7880f28e8e6b45).|
| **May 2014** | [Atom Shell is open sourced](http://blog.atom.io/2014/05/06/atom-is-now-open-source.html). |
| **May 2014** | [Atom Shell is open sourced](https://blog.atom.io/2014/05/06/atom-is-now-open-source.html). |
| **April 2015** | [Atom Shell is re-named Electron](https://github.com/electron/electron/pull/1389). |
| **May 2016** | [Electron releases `v1.0.0`](https://electronjs.org/blog/electron-1-0).|
| **May 2016** | [Electron apps compatible with Mac App Store](https://electronjs.org/docs/tutorial/mac-app-store-submission-guide).|
| **August 2016** | [Windows Store support for Electron apps](https://electronjs.org/docs/tutorial/windows-store-guide).|
| **May 2016** | [Electron apps compatible with Mac App Store](mac-app-store-submission-guide.md).|
| **August 2016** | [Windows Store support for Electron apps](windows-store-guide.md).|

View File

@@ -1,16 +1,24 @@
# Accessibility
Making accessible applications is important and we're happy to introduce new functionality to [Devtron](https://electron.atom.io/devtron) and [Spectron](https://electron.atom.io/spectron) that gives developers the opportunity to make their apps better for everyone.
Making accessible applications is important and we're happy to introduce new
functionality to [Devtron][devtron] and [Spectron][spectron] that gives
developers the opportunity to make their apps better for everyone.
---
Accessibility concerns in Electron applications are similar to those of websites because they're both ultimately HTML. With Electron apps, however, you can't use the online resources for accessibility audits because your app doesn't have a URL to point the auditor to.
Accessibility concerns in Electron applications are similar to those of
websites because they're both ultimately HTML. With Electron apps, however,
you can't use the online resources for accessibility audits because your app
doesn't have a URL to point the auditor to.
These new features bring those auditing tools to your Electron app. You can choose to add audits to your tests with Spectron or use them within DevTools with Devtron. Read on for a summary of the tools or checkout our [accessibility documentation](https://electronjs.org/docs/tutorial/accessibility) for more information.
These new features bring those auditing tools to your Electron app. You can
choose to add audits to your tests with Spectron or use them within DevTools
with Devtron. Read on for a summary of the tools.
## Spectron
In the testing framework Spectron, you can now audit each window and `<webview>` tag in your application. For example:
In the testing framework Spectron, you can now audit each window and `<webview>`
tag in your application. For example:
```javascript
app.client.auditAccessibility().then(function (audit) {
@@ -20,31 +28,43 @@ app.client.auditAccessibility().then(function (audit) {
})
```
You can read more about this feature in [Spectron's documentation](https://github.com/electron/spectron#accessibility-testing).
You can read more about this feature in [Spectron's documentation][spectron-a11y].
## Devtron
In Devtron, there is a new accessibility tab which will allow you to audit a page in your app, sort and filter the results.
In Devtron, there is a new accessibility tab which will allow you to audit a
page in your app, sort and filter the results.
![devtron screenshot](https://cloud.githubusercontent.com/assets/1305617/17156618/9f9bcd72-533f-11e6-880d-389115f40a2a.png)
![devtron screenshot][devtron-screenshot]
Both of these tools are using the [Accessibility Developer Tools](https://github.com/GoogleChrome/accessibility-developer-tools) library built by Google for Chrome. You can learn more about the accessibility audit rules this library uses on that [repository's wiki](https://github.com/GoogleChrome/accessibility-developer-tools/wiki/Audit-Rules).
Both of these tools are using the [Accessibility Developer Tools][a11y-devtools]
library built by Google for Chrome. You can learn more about the accessibility
audit rules this library uses on that [repository's wiki][a11y-devtools-wiki].
If you know of other great accessibility tools for Electron, add them to the [accessibility documentation](https://electronjs.org/docs/tutorial/accessibility) with a pull request.
If you know of other great accessibility tools for Electron, add them to the
accessibility documentation with a pull request.
## Enabling Accessibility
Electron applications keep accessibility disabled by default for performance reasons but there are multiple ways to enable it.
Electron applications keep accessibility disabled by default for performance
reasons but there are multiple ways to enable it.
### Inside Application
By using [`app.setAccessibilitySupportEnabled(enabled)`](https://electron.atom.io/docs/api/app.md#appsetaccessibilitysupportenabledenabled-macos-windows), you can expose accessibility switch to users in the application preferences. User's system assistive utilities have priority over this setting and will override it.
By using [`app.setAccessibilitySupportEnabled(enabled)`][setAccessibilitySupportEnabled],
you can expose accessibility switch to users in the application preferences.
User's system assistive utilities have priority over this setting and will
override it.
### Assistive Technology
Electron application will enable accessibility automatically when it detects assistive technology (Windows) or VoiceOver (macOS). See Chrome's [accessibility documentation](https://www.chromium.org/developers/design-documents/accessibility#TOC-How-Chrome-detects-the-presence-of-Assistive-Technology) for more details.
Electron application will enable accessibility automatically when it detects
assistive technology (Windows) or VoiceOver (macOS). See Chrome's
[accessibility documentation][a11y-docs] for more details.
On macOS, third-party assistive technology can switch accessibility inside Electron applications by setting the attribute `AXManualAccessibility` programmatically:
On macOS, third-party assistive technology can switch accessibility inside
Electron applications by setting the attribute `AXManualAccessibility`
programmatically:
```objc
CFStringRef kAXManualAccessibility = CFSTR("AXManualAccessibility");
@@ -54,9 +74,18 @@ CFStringRef kAXManualAccessibility = CFSTR("AXManualAccessibility");
AXUIElementRef appRef = AXUIElementCreateApplication(app.processIdentifier);
if (appRef == nil)
return;
CFBooleanRef value = enable ? kCFBooleanTrue : kCFBooleanFalse;
AXUIElementSetAttributeValue(appRef, kAXManualAccessibility, value);
CFRelease(appRef);
}
```
[devtron]: https://electronjs.org/devtron
[devtron-screenshot]: https://cloud.githubusercontent.com/assets/1305617/17156618/9f9bcd72-533f-11e6-880d-389115f40a2a.png
[spectron]: https://electronjs.org/spectron
[spectron-a11y]: https://github.com/electron/spectron#accessibility-testing
[a11y-docs]: https://www.chromium.org/developers/design-documents/accessibility#TOC-How-Chrome-detects-the-presence-of-Assistive-Technology
[a11y-devtools]: https://github.com/GoogleChrome/accessibility-developer-tools
[a11y-devtools-wiki]: https://github.com/GoogleChrome/accessibility-developer-tools/wiki/Audit-Rules
[setAccessibilitySupportEnabled]: ../api/app.md#appsetaccessibilitysupportenabledenabled-macos-windows

View File

@@ -0,0 +1,142 @@
# Electron Application Architecture
Before we can dive into Electron's APIs, we need to discuss the two process
types available in Electron. They are fundamentally different and important to
understand.
## Main and Renderer Processes
In Electron, the process that runs `package.json`'s `main` script is called
__the main process__. The script that runs in the main process can display a
GUI by creating web pages. An Electron app always has one main process, but
never more.
Since Electron uses Chromium for displaying web pages, Chromium's
multi-process architecture is also used. Each web page in Electron runs in
its own process, which is called __the renderer process__.
In normal browsers, web pages usually run in a sandboxed environment and are not
allowed access to native resources. Electron users, however, have the power to
use Node.js APIs in web pages allowing lower level operating system
interactions.
### Differences Between Main Process and Renderer Process
The main process creates web pages by creating `BrowserWindow` instances. Each
`BrowserWindow` instance runs the web page in its own renderer process. When a
`BrowserWindow` instance is destroyed, the corresponding renderer process
is also terminated.
The main process manages all web pages and their corresponding renderer
processes. Each renderer process is isolated and only cares about the web page
running in it.
In web pages, calling native GUI related APIs is not allowed because managing
native GUI resources in web pages is very dangerous and it is easy to leak
resources. If you want to perform GUI operations in a web page, the renderer
process of the web page must communicate with the main process to request that
the main process perform those operations.
> #### Aside: Communication Between Processes
> In Electron, we have several ways to communicate between the main process
and renderer processes. Like [`ipcRenderer`](../api/ipc-renderer.md) and
[`ipcMain`](../api/ipc-main.md) modules for sending messages, and the
[remote](../api/remote.md) module for RPC style communication. There is also
an FAQ entry on [how to share data between web pages][share-data].
## Using Electron APIs
Electron offers a number of APIs that support the development of a desktop
application in both the main process and the renderer process. In both
processes, you'd access Electron's APIs by requiring its included module:
```javascript
const electron = require('electron')
```
All Electron APIs are assigned a process type. Many of them can only be
used from the main process, some of them only from a renderer process,
some from both. The documentation for the individual API will clearly
state which process they can be used from.
A window in Electron is for instance created using the `BrowserWindow`
class. It is only available in the main process.
```javascript
// This will work in the main process, but be `undefined` in a
// renderer process:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
```
Since communication between the processes is possible, a renderer process
can call upon the main process to perform tasks. Electron comes with a
module called `remote` that exposes APIs usually only available on the
main process. In order to create a `BrowserWindow` from a renderer process,
we'd use the remote as a middle-man:
```javascript
// This will work in a renderer process, but be `undefined` in the
// main process:
const { remote } = require('electron')
const { BrowserWindow } = remote
const win = new BrowserWindow()
```
## Using Node.js APIs
Electron exposes full access to Node.js both in the main and the renderer
process. This has two important implications:
1) All APIs available in Node.js are available in Electron. Calling the
following code from an Electron app works:
```javascript
const fs = require('fs')
const root = fs.readdirSync('/')
// This will print all files at the root-level of the disk,
// either '/' or 'C:\'.
console.log(root)
```
As you might already be able to guess, this has important security implications
if you ever attempt to load remote content. You can find more information and
guidance on loading remote content in our [security documentation][security].
2) You can use Node.js modules in your application. Pick your favorite npm
module. npm offers currently the world's biggest repository of open-source
code  the ability to use well-maintained and tested code that used to be
reserved for server applications is one of the key features of Electron.
As an example, to use the official AWS SDK in your application, you'd first
install it as a dependency:
```sh
npm install --save aws-sdk
```
Then, in your Electron app, simply require and use the module as if you were
building a Node.js application:
```javascript
// A ready-to-use S3 Client
const S3 = require('aws-sdk/clients/s3')
```
There is one important caveat: Native Node.js modules (that is, modules that
require compilation of native code before they can be used) will need to be
compiled to be used with Electron.
The vast majority of Node.js modules are _not_ native. Only 400 out of the
~650.000 modules are native. However, if you do need native modules, please
consult [this guide on how to recompile them for Electron][native-node] (it's
easy).
[node-docs]: https://nodejs.org/en/docs/
[security]: ./security.md
[native-node]: ./using-native-node-modules.md
[share-data]: ../faq.md#how-to-share-data-between-web-pages

View File

@@ -0,0 +1,38 @@
# Application Debugging
Whenever your Electron application is not behaving the way you wanted it to,
an array of debugging tools might help you find coding errors, performance
bottlenecks, or optimization opportunities.
## Renderer Process
The most comprehensive tool to debug individual renderer processes is the
Chromium Developer Toolset. It is available for all renderer processes,
including instances of `BrowserWindow`, `BrowserView`, and `WebView`. You
can open them programmatically by calling the `openDevTools()` API on the
`webContents` of the instance:
```javascript
const { BrowserWindow } = require('electron')
let win = new BrowserWindow()
win.webContents.openDevTools()
```
Google offers [excellent documentation for their developer tools][devtools].
We recommend that you make yourself familiar with them - they are usually one
of the most powerful utilities in any Electron Developer's tool belt.
## Main Process
Debugging the main process is a bit trickier, since you cannot simply open
developer tools for them. The Chromium Developer Tools can [be used
to debug Electron's main process][node-inspect] thanks to a closer collaboration
between Google / Chrome and Node.js, but you might encounter oddities like
`require` not being present in the console.
For more information, see the [Debugging the Main Process documentation][main-debug].
[node-inspect]: https://nodejs.org/en/docs/inspector/
[devtools]: https://developer.chrome.com/devtools
[main-debug]: ./debugging-main-process.md

View File

@@ -5,7 +5,12 @@ path names on Windows, slightly speed up `require` and conceal your source code
from cursory inspection, you can choose to package your app into an [asar][asar]
archive with little changes to your source code.
## Generating `asar` Archive
Most users will get this feature for free, since it's supported out of the box
by [`electron-packager`][electron-packager], [`electron-forge`][electron-forge],
and [`electron-builder`][electron-builder]. If you are not using any of these
tools, read on.
## Generating `asar` Archives
An [asar][asar] archive is a simple tar-like format that concatenates files
into a single file. Electron can read arbitrary files from it without unpacking
@@ -71,8 +76,9 @@ require('/path/to/example.asar/dir/module.js')
You can also display a web page in an `asar` archive with `BrowserWindow`:
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({width: 800, height: 600})
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.loadURL('file:///path/to/example.asar/static/index.html')
```
@@ -164,22 +170,26 @@ and `command`s are executed under shell. There is no reliable way to determine
whether a command uses a file in asar archive, and even if we do, we can not be
sure whether we can replace the path in command without side effects.
## Adding Unpacked Files in `asar` Archive
## Adding Unpacked Files to `asar` Archives
As stated above, some Node APIs will unpack the file to filesystem when
calling, apart from the performance issues, it could also lead to false alerts
of virus scanners.
As stated above, some Node APIs will unpack the file to the filesystem when
called. Apart from the performance issues, various anti-virus scanners might
be triggered by this behavior.
To work around this, you can unpack some files creating archives by using the
`--unpack` option, an example of excluding shared libraries of native modules
is:
As a workaround, you can leave various files unpacked using the `--unpack` option.
In the following example, shared libraries of native Node.js modules will not be
packed:
```sh
$ asar pack app app.asar --unpack *.node
```
After running the command, apart from the `app.asar`, there is also an
`app.asar.unpacked` folder generated which contains the unpacked files, you
should copy it together with `app.asar` when shipping it to users.
After running the command, you will notice that a folder named `app.asar.unpacked`
was created together with the `app.asar` file. It contains the unpacked files
and should be shipped together with the `app.asar` archive.
[asar]: https://github.com/electron/asar
[electron-packager]: https://github.com/electron-userland/electron-packager
[electron-forge]: https://github.com/electron-userland/electron-forge
[electron-builder]: https://github.com/electron-userland/electron-builder

View File

@@ -0,0 +1,66 @@
# Boilerplates and CLIs
Electron development is un-opinionated - there is no "one true way" to develop,
build, package, or release an Electron application. Additional features for
Electron, both for build- and run-time, can usually be found on
[npm](https://www.npmjs.com/search?q=electron) in individual packages, allowing developers to build both
the app and build pipeline they need.
That level of modularity and extendability ensures that all developers working
with Electron, both big and small in team-size, are never restricted in what
they can or cannot do at any time during their development lifecycle. However,
for many developers, one of the community-driven boilerplates or command line
tools might make it dramatically easier to compile, package, and release an
app.
## Boilerplate vs CLI
A boilerplate is simply a starting point - a canvas, so to speak - from which
you build your application. They usually come in the form of a repository you
can clone and customize to your heart's content.
A command line tool on the other hand continues to support you throughout the
development and release. They are more helpful and supportive but enforce
guidelines on how your code should be structured and built. *Especially for
beginners, using a command line tool is likely to be helpful*.
## electron-forge
A "complete tool for building modern Electron applications". Electron Forge
unifies the existing (and well maintained) build tools for Electron development
into a simple, easy to use package so that anyone can jump right in to Electron
development.
Forge comes with [ready-to-use templates](https://electronforge.io/templates) for popular
frameworks like React, Vue, or Angular. It uses the same core modules used by the
greater Electron community (like [`electron-packager`](https://github.com/electron-userland/electron-packager))  
changes made by Electron maintainers (like Slack) benefit Forge's users, too.
You can find more information and documentation on [electronforge.io](https://electronforge.io/).
## electron-builder
A "complete solution to package and build a ready-for-distribution Electron app"
that focuses on an integrated experience. [`electron-builder`](https://github.com/electron-userland/electron-builder) adds one
single dependency focused on simplicity and manages all further requirements
internally.
`electron-builder` replaces features and modules used by the Electron
maintainers (such as the auto-updater) with custom ones. They are generally
tighter integrated but will have less in common with popular Electron apps
like Atom, Visual Studio Code, or Slack.
You can find more information and documentation in [the repository](https://github.com/electron-userland/electron-builder).
## electron-react-boilerplate
If you don't want any tools but simply a solid boilerplate to build from,
CT Lin's [`electron-react-boilerplate`](https://github.com/chentsulin/electron-react-boilerplate) might be worth
a look. It's quite popular in the community and uses `electron-builder`
internally.
## Other Tools and Boilerplates
The ["Awesome Electron" list](https://github.com/sindresorhus/awesome-electron#boilerplates) contains more tools and boilerplates
to choose from. If you find the length of the list intimidating, don't
forget that adding tools as you go along is a valid approach, too.

View File

@@ -10,344 +10,26 @@ environments with Electron APIs.
## Notifications
See [Notifications](notifications.md)
See the [Notifications documentation](notifications.md).
## Recent documents (Windows & macOS)
## Recent Documents
Windows and macOS provide easy access to a list of recent documents opened by
the application via JumpList or dock menu, respectively.
See [Recent Documents documentation](recent-documents.md).
__JumpList:__
## Progress Bar
![JumpList Recent Files](https://cloud.githubusercontent.com/assets/2289/23446924/11a27b98-fdfc-11e6-8485-cc3b1e86b80a.png)
See the [Progress Bar documentation](progress-bar.md).
__Application dock menu:__
## Unity Launcher
<img src="https://cloud.githubusercontent.com/assets/639601/5069610/2aa80758-6e97-11e4-8cfb-c1a414a10774.png" height="353" width="428" >
See the [Unity Launcher documentation][unity-launcher].
To add a file to recent documents, you can use the
[app.addRecentDocument][addrecentdocument] API:
## Represented File for macOS Window
```javascript
const {app} = require('electron')
app.addRecentDocument('/Users/USERNAME/Desktop/work.type')
```
And you can use [app.clearRecentDocuments][clearrecentdocuments] API to empty
the recent documents list:
```javascript
const {app} = require('electron')
app.clearRecentDocuments()
```
### Windows Notes
In order to be able to use this feature on Windows, your application has to be
registered as a handler of the file type of the document, otherwise the file
won't appear in JumpList even after you have added it. You can find everything
on registering your application in [Application Registration][app-registration].
When a user clicks a file from the JumpList, a new instance of your application
will be started with the path of the file added as a command line argument.
### macOS Notes
When a file is requested from the recent documents menu, the `open-file` event
of `app` module will be emitted for it.
## Custom Dock Menu (macOS)
macOS enables developers to specify a custom menu for the dock, which usually
contains some shortcuts for commonly used features of your application:
__Dock menu of Terminal.app:__
<img src="https://cloud.githubusercontent.com/assets/639601/5069962/6032658a-6e9c-11e4-9953-aa84006bdfff.png" height="354" width="341" >
To set your custom dock menu, you can use the `app.dock.setMenu` API, which is
only available on macOS:
```javascript
const {app, Menu} = require('electron')
const dockMenu = Menu.buildFromTemplate([
{label: 'New Window', click () { console.log('New Window') }},
{label: 'New Window with Settings',
submenu: [
{label: 'Basic'},
{label: 'Pro'}
]
},
{label: 'New Command...'}
])
app.dock.setMenu(dockMenu)
```
## User Tasks (Windows)
On Windows you can specify custom actions in the `Tasks` category of JumpList,
as quoted from MSDN:
> Applications define tasks based on both the program's features and the key
> things a user is expected to do with them. Tasks should be context-free, in
> that the application does not need to be running for them to work. They
> should also be the statistically most common actions that a normal user would
> perform in an application, such as compose an email message or open the
> calendar in a mail program, create a new document in a word processor, launch
> an application in a certain mode, or launch one of its subcommands. An
> application should not clutter the menu with advanced features that standard
> users won't need or one-time actions such as registration. Do not use tasks
> for promotional items such as upgrades or special offers.
>
> It is strongly recommended that the task list be static. It should remain the
> same regardless of the state or status of the application. While it is
> possible to vary the list dynamically, you should consider that this could
> confuse the user who does not expect that portion of the destination list to
> change.
__Tasks of Internet Explorer:__
![IE](http://i.msdn.microsoft.com/dynimg/IC420539.png)
Unlike the dock menu in macOS which is a real menu, user tasks in Windows work
like application shortcuts such that when user clicks a task, a program will be
executed with specified arguments.
To set user tasks for your application, you can use
[app.setUserTasks][setusertaskstasks] API:
```javascript
const {app} = require('electron')
app.setUserTasks([
{
program: process.execPath,
arguments: '--new-window',
iconPath: process.execPath,
iconIndex: 0,
title: 'New Window',
description: 'Create a new window'
}
])
```
To clean your tasks list, just call `app.setUserTasks` with an empty array:
```javascript
const {app} = require('electron')
app.setUserTasks([])
```
The user tasks will still show even after your application closes, so the icon
and program path specified for a task should exist until your application is
uninstalled.
## Thumbnail Toolbars
On Windows you can add a thumbnail toolbar with specified buttons in a taskbar
layout of an application window. It provides users a way to access to a
particular window's command without restoring or activating the window.
From MSDN, it's illustrated:
> This toolbar is simply the familiar standard toolbar common control. It has a
> maximum of seven buttons. Each button's ID, image, tooltip, and state are defined
> in a structure, which is then passed to the taskbar. The application can show,
> enable, disable, or hide buttons from the thumbnail toolbar as required by its
> current state.
>
> For example, Windows Media Player might offer standard media transport controls
> such as play, pause, mute, and stop.
__Thumbnail toolbar of Windows Media Player:__
![player](https://i-msdn.sec.s-msft.com/dynimg/IC420540.png)
You can use [BrowserWindow.setThumbarButtons][setthumbarbuttons] to set
thumbnail toolbar in your application:
```javascript
const {BrowserWindow} = require('electron')
const path = require('path')
let win = new BrowserWindow({
width: 800,
height: 600
})
win.setThumbarButtons([
{
tooltip: 'button1',
icon: path.join(__dirname, 'button1.png'),
click () { console.log('button1 clicked') }
},
{
tooltip: 'button2',
icon: path.join(__dirname, 'button2.png'),
flags: ['enabled', 'dismissonclick'],
click () { console.log('button2 clicked.') }
}
])
```
To clean thumbnail toolbar buttons, just call `BrowserWindow.setThumbarButtons`
with an empty array:
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.setThumbarButtons([])
```
## Unity Launcher Shortcuts (Linux)
In Unity, you can add custom entries to its launcher via modifying the
`.desktop` file, see [Adding Shortcuts to a Launcher][unity-launcher].
__Launcher shortcuts of Audacious:__
![audacious](https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles?action=AttachFile&do=get&target=shortcuts.png)
## Progress Bar in Taskbar (Windows, macOS, Unity)
On Windows a taskbar button can be used to display a progress bar. This enables
a window to provide progress information to the user without the user having to
switch to the window itself.
On macOS the progress bar will be displayed as a part of the dock icon.
The Unity DE also has a similar feature that allows you to specify the progress
bar in the launcher.
__Progress bar in taskbar button:__
![Taskbar Progress Bar](https://cloud.githubusercontent.com/assets/639601/5081682/16691fda-6f0e-11e4-9676-49b6418f1264.png)
To set the progress bar for a Window, you can use the
[BrowserWindow.setProgressBar][setprogressbar] API:
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.setProgressBar(0.5)
```
## Icon Overlays in Taskbar (Windows)
On Windows a taskbar button can use a small overlay to display application
status, as quoted from MSDN:
> Icon overlays serve as a contextual notification of status, and are intended
> to negate the need for a separate notification area status icon to communicate
> that information to the user. For instance, the new mail status in Microsoft
> Outlook, currently shown in the notification area, can now be indicated
> through an overlay on the taskbar button. Again, you must decide during your
> development cycle which method is best for your application. Overlay icons are
> intended to supply important, long-standing status or notifications such as
> network status, messenger status, or new mail. The user should not be
> presented with constantly changing overlays or animations.
__Overlay on taskbar button:__
![Overlay on taskbar button](https://i-msdn.sec.s-msft.com/dynimg/IC420441.png)
To set the overlay icon for a window, you can use the
[BrowserWindow.setOverlayIcon][setoverlayicon] API:
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.setOverlayIcon('path/to/overlay.png', 'Description for overlay')
```
## Flash Frame (Windows)
On Windows you can highlight the taskbar button to get the user's attention.
This is similar to bouncing the dock icon on macOS.
From the MSDN reference documentation:
> Typically, a window is flashed to inform the user that the window requires
> attention but that it does not currently have the keyboard focus.
To flash the BrowserWindow taskbar button, you can use the
[BrowserWindow.flashFrame][flashframe] API:
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.once('focus', () => win.flashFrame(false))
win.flashFrame(true)
```
Don't forget to call the `flashFrame` method with `false` to turn off the flash. In
the above example, it is called when the window comes into focus, but you might
use a timeout or some other event to disable it.
## Represented File of Window (macOS)
On macOS a window can set its represented file, so the file's icon can show in
the title bar and when users Command-Click or Control-Click on the title a path
popup will show.
You can also set the edited state of a window so that the file icon can indicate
whether the document in this window has been modified.
__Represented file popup menu:__
<img src="https://cloud.githubusercontent.com/assets/639601/5082061/670a949a-6f14-11e4-987a-9aaa04b23c1d.png" height="232" width="663" >
To set the represented file of window, you can use the
[BrowserWindow.setRepresentedFilename][setrepresentedfilename] and
[BrowserWindow.setDocumentEdited][setdocumentedited] APIs:
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.setRepresentedFilename('/etc/passwd')
win.setDocumentEdited(true)
```
See the [Represented File documentation](represented-file.md).
## Dragging files out of the window
For certain kinds of apps that manipulate on files, it is important to be able
to drag files from Electron to other apps. To implement this feature in your
app, you need to call `webContents.startDrag(item)` API on `ondragstart` event.
See the [Native File Drag & Drop documentation](native-file-drag-drop.md).
In web page:
```html
<a href="#" id="drag">item</a>
<script type="text/javascript" charset="utf-8">
document.getElementById('drag').ondragstart = (event) => {
event.preventDefault()
ipcRenderer.send('ondragstart', '/path/to/item')
}
</script>
```
In the main process:
```javascript
const {ipcMain} = require('electron')
ipcMain.on('ondragstart', (event, filePath) => {
event.sender.startDrag({
file: filePath,
icon: '/path/to/icon.png'
})
})
```
[addrecentdocument]: ../api/app.md#appaddrecentdocumentpath-os-x-windows
[clearrecentdocuments]: ../api/app.md#appclearrecentdocuments-os-x-windows
[setusertaskstasks]: ../api/app.md#appsetusertaskstasks-windows
[setprogressbar]: ../api/browser-window.md#winsetprogressbarprogress
[setoverlayicon]: ../api/browser-window.md#winsetoverlayiconoverlay-description-windows-7
[setrepresentedfilename]: ../api/browser-window.md#winsetrepresentedfilenamefilename-os-x
[setdocumentedited]: ../api/browser-window.md#winsetdocumenteditededited-os-x
[app-registration]: http://msdn.microsoft.com/en-us/library/windows/desktop/ee872121(v=vs.85).aspx
[unity-launcher]: https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles#Adding_shortcuts_to_a_launcher
[setthumbarbuttons]: ../api/browser-window.md#winsetthumbarbuttonsbuttons-windows-7
[tray-balloon]: ../api/tray.md#traydisplayballoonoptions-windows
[app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx
[notification-spec]: https://developer.gnome.org/notification-spec/
[flashframe]: ../api/browser-window.md#winflashframeflag

View File

@@ -0,0 +1,117 @@
# Developer Environment
Electron development is essentially Node.js development. To turn your operating
system into an environment capable of building desktop apps with Electron,
you will merely need Node.js, npm, a code editor of your choice, and a
rudimentary understanding of your operating system's command line client.
## Setting up macOS
> Electron supports Mac OS X 10.9 (and all versions named macOS) and up. Apple
does not allow running macOS in virtual machines unless the host computer is
already an Apple computer, so if you find yourself in need of a Mac, consider
using a cloud service that rents access to Macs (like [MacInCloud][macincloud]
or [xcloud](https://xcloud.me)).
First, install a recent version of Node.js. We recommend that you install
either the latest `LTS` or `Current` version available. Visit
[the Node.js download page][node-download] and select the `macOS Installer`.
While Homebrew is an offered option, but we recommend against it - many tools
will be incompatible with the way Homebrew installs Node.js.
Once downloaded, execute the installer and let the installation wizard guide
you through the installation.
Once installed, confirm that everything works as expected. Find the macOS
`Terminal` application in your `/Applications/Utilities` folder (or by
simply search for the word `Terminal` in Spotlight). Open up `Terminal`
or another command line client of your choice and confirm that both `node`
and `npm` are available:
```sh
# This command should print the version of Node.js
node -v
# This command should print the version of npm
npm -v
```
If both commands printed a version number, you are all set! Before you get
started, you might want to install a [code editor](#a-good-editor) suited
for JavaScript development.
## Setting up Windows
> Electron supports Windows 7 and later versions  attempting to develop Electron
applications on earlier versions of Windows will not work. Microsoft provides
free [virtual machine images with Windows 10][windows-vm] for developers.
First, install a recent version of Node.js. We recommend that you install
either the latest `LTS` or `Current` version available. Visit
[the Node.js download page][node-download] and select the `Windows Installer`.
Once downloaded, execute the installer and let the installation wizard guide
you through the installation.
On the screen that allows you to configure the installation, make sure to
select the `Node.js runtime`, `npm package manager`, and `Add to PATH`
options.
Once installed, confirm that everything works as expected. Find the Windows
PowerShell by simply opening the Start Menu and typing `PowerShell`. Open
up `PowerShell` or another command line client of your choice and confirm that
both `node` and `npm` are available:
```powershell
# This command should print the version of Node.js
node -v
# This command should print the version of npm
npm -v
```
If both commands printed a version number, you are all set! Before you get
started, you might want to install a [code editor](#a-good-editor) suited
for JavaScript development.
## Setting up Linux
> Generally speaking, Electron supports Ubuntu 12.04, Fedora 21, Debian 8
and later.
First, install a recent version of Node.js. Depending on your Linux
distribution, the installation steps might differ. Assuming that you normally
install software using a package manager like `apt` or `pacman`, use the
official [Node.js guidance on installing on Linux][node-package].
You're running Linux, so you likely already know how to operate a command line
client. Open up your favorite client and confirm that both `node` and `npm`
are available globally:
```sh
# This command should print the version of Node.js
node -v
# This command should print the version of npm
npm -v
```
If both commands printed a version number, you are all set! Before you get
started, you might want to install a [code editor](#a-good-editor) suited
for JavaScript development.
## A Good Editor
We might suggest two free popular editors built in Electron:
GitHub's [Atom][atom] and Microsoft's [Visual Studio Code][code]. Both of
them have excellent JavaScript support.
If you are one of the many developers with a strong preference, know that
virtually all code editors and IDEs these days support JavaScript.
[macincloud]: https://www.macincloud.com/
[xcloud]: https://xcloud.me
[node-download]: https://nodejs.org/en/download/
[node-package]: https://nodejs.org/en/download/package-manager/
[atom]: https://atom.io/
[code]: https://code.visualstudio.com/
[windows-vm]: https://developer.microsoft.com/en-us/windows/downloads/virtual-machines

View File

@@ -50,7 +50,7 @@ Following Devtools Extensions are tested and guaranteed to work in Electron:
* [jQuery Debugger](https://chrome.google.com/webstore/detail/jquery-debugger/dbhhnnnpaeobfddmlalhnehgclcmjimi)
* [AngularJS Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk)
* [Vue.js devtools](https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd)
* [Cerebral Debugger](http://www.cerebraljs.com/documentation/the_debugger)
* [Cerebral Debugger](https://cerebraljs.com/docs/introduction/debugger.html)
* [Redux DevTools Extension](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd)
* [MobX Developer Tools](https://chrome.google.com/webstore/detail/mobx-developer-tools/pfgnfdagidkfgccljigdamigbcnndkod)

View File

@@ -1,120 +1,150 @@
# Electron Versioning
## Overview of Semantic Versioning
> A detailed look at our versioning policy and implementation.
If you've been using Node and npm for a while, you are probably aware of [Semantic Versioning], or SemVer for short. It's a convention for specifying version numbers for software that helps communicate intentions to the users of your software.
Semantic versions are always made up of three numbers:
As of version 2.0.0, Electron follows [semver](#semver). The following command will install the most recent stable build of Electron:
```sh
major.minor.patch
npm install --save-dev electron
```
Semantic version numbers are bumped (incremented) using the following rules:
* **Major** is for changes that break backwards compatibility.
* **Minor** is for new features that don't break backwards compatibility.
* **Patch** is for bug fixes and other minor changes.
A simple mnemonic for remembering this scheme is as follows:
To update an existing project to use the latest stable version:
```sh
breaking.feature.fix
npm install --save-dev electron@latest
```
## Before Version 2
## Version 1.x
Before version 2 of Electron we didn't follow SemVer, instead the following was used:
Electron versions *< 2.0* did not conform to the [semver](http://semver.org) spec: major versions corresponded to end-user API changes, minor versions corresponded to Chromium major releases, and patch versions corresponded to new features and bug fixes. While convenient for developers merging features, it creates problems for developers of client-facing applications. The QA testing cycles of major apps like Slack, Stride, Teams, Skype, VS Code, Atom, and Desktop can be lengthy and stability is a highly desired outcome. There is a high risk in adopting new features while trying to absorb bug fixes.
- **Major**: Breaking changes to Electron's API
- **Minor**: Major Chrome, minor node or "significant" Electron changes
- **Patch**: New features and bug fixes
Here is an example of the 1.x strategy:
This system had a number of drawbacks, such as:
![](../images/versioning-sketch-0.png)
- New bugs could be introduced into a new patch version because patch versions added features
- It didn't follow SemVer so it could confuse consumers
- It wasn't clear what the differences between stable and beta builds were
- The lack of a formalized stabilization process and release schedule lead to sporadic releases and betas that could last several months
An app developed with `1.8.1` cannot take the `1.8.3` bug fix without either absorbing the `1.8.2` feature, or by backporting the fix and maintaining a new release line.
## Version 2 and Beyond
## Version 2.0 and Beyond
From version 2.0.0, Electron will attempt to adhere to SemVer and follow a
release schedule and stabilization process similar to that of Chromium.
There are several major changes from our 1.x strategy outlined below. Each change is intended to satisfy the needs and priorities of developers/maintainers and app developers.
### Version Change Rules
1. Strict use of semver
2. Introduction of semver-compliant `-beta` tags
3. Introduction of [conventional commit messages](https://conventionalcommits.org/)
4. Clearly defined stabilization branches
5. The `master` branch is versionless; only stabilization branches contain version information
Here are the general rules that apply when releasing new versions:
We will cover in detail how git branching works, how npm tagging works, what developers should expect to see, and how one can backport changes.
| Type of change | Version increase
|---|---
| Chromium version update | Major
| Node *major* version update | Major
| Electron breaking API change | Major
| Any other changes deemed "risky" | Major
| Node *minor* version update | Minor
| Electron non-breaking API change | Minor
| Electron bug fix | Patch
# semver
When you install an npm module with the `--save` or `--save-dev` flags, it
will be prefixed with a caret `^` in package.json:
From 2.0 onward, Electron will follow semver.
```json
{
"devDependencies": {
"electron": "^2.0.0"
}
}
Below is a table explicitly mapping types of changes to their corresponding category of semver (e.g. Major, Minor, Patch).
| Major Version Increments | Minor Version Increments | Patch Version Increments |
| ------------------------------- | ---------------------------------- | ----------------------------- |
| Electron breaking API changes | Electron non-breaking API changes | Electron bug fixes |
| Node.js major version updates | Node.js minor version updates | Node.js patch version updates |
| Chromium version updates | | fix-related chromium patches |
Note that most chromium updates will be considered breaking. Fixes that can be backported will likely be cherry-picked as patches.
# Stabilization Branches
Stabilization branches are branches that run parallel to master, taking in only cherry-picked commits that are related to security or stability. These branches are never merged back to master.
![](../images/versioning-sketch-1.png)
Stabilization branches are always either **major** or **minor** version lines, and named against the following template `$MAJOR-$MINOR-x` e.g. `2-0-x`.
We allow for multiple stabilization branches to exist simultaneously, and intend to support at least two in parallel at all times, backporting security fixes as necessary.
![](../images/versioning-sketch-2.png)
Older lines will not be supported by GitHub, but other groups can take ownership and backport stability and security fixes on their own. We discourage this, but recognize that it makes life easier for many app developers.
# Beta Releases and Bug Fixes
Developers want to know which releases are _safe_ to use. Even seemingly innocent features can introduce regressions in complex applications. At the same time, locking to a fixed version is dangerous because youre ignoring security patches and bug fixes that may have come out since your version. Our goal is to allow the following standard semver ranges in `package.json` :
* Use `~2.0.0` to admit only stability or security related fixes to your `2.0.0` release.
* Use `^2.0.0` to admit non-breaking _reasonably stable_ feature work as well as security and bug fixes.
Whats important about the second point is that apps using `^` should still be able to expect a reasonable level of stability. To accomplish this, semver allows for a _pre-release identifier_ to indicate a particular version is not yet _safe_ or _stable_.
Whatever you choose, you will periodically have to bump the version in your `package.json` as breaking changes are a fact of Chromium life.
The process is as follows:
1. All new major and minor releases lines begin with a `-beta.N` tag for `N >= 1`. At that point, the feature set is **locked**. That release line admits no further features, and focuses only on security and stability.
e.g. `2.0.0-beta.1`.
2. Bug fixes, regression fixes, and security patches can be admitted. Upon doing so, a new beta is released incrementing `N`.
e.g. `2.0.0-beta.2`
3. If a particular beta release is _generally regarded_ as stable, it will be re-released as a stable build, changing only the version information.
e.g. `2.0.0`.
4. If future bug fixes or security patches need to be made once a release is stable, they are applied and the _patch_ version is incremented accordingly
e.g. `2.0.1`.
For each major and minor bump, you should expect to see something like the following:
```text
2.0.0-beta.1
2.0.0-beta.2
2.0.0-beta.3
2.0.0
2.0.1
2.0.2
```
The [caret semver range](https://docs.npmjs.com/misc/semver#caret-ranges-123-025-004)
allows minor- and patch-level changes to be installed, i.e. non-breaking
features and bug fixes.
An example lifecycle in pictures:
Alternatively, a more conservative approach is to use the
[tilde semver range](https://docs.npmjs.com/misc/semver#tilde-ranges-123-12-1)
`~`, which will only allow patch-level upgrades, i.e. bug fixes.
* A new release branch is created that includes the latest set of features. It is published as `2.0.0-beta.1`.
![](../images/versioning-sketch-3.png)
* A bug fix comes into master that can be backported to the release branch. The patch is applied, and a new beta is published as `2.0.0-beta.2`.
![](../images/versioning-sketch-4.png)
* The beta is considered _generally stable_ and it is published again as a non-beta under `2.0.0`.
![](../images/versioning-sketch-5.png)
* Later, a zero-day exploit is revealed and a fix is applied to master. We backport the fix to the `2-0-x` line and release `2.0.1`.
![](../images/versioning-sketch-6.png)
A few examples of how various semver ranges will pick up new releases:
### The Release Schedule
![](../images/versioning-sketch-7.png)
**Note: The schedule outlined here is _aspirational_. We are not yet cutting
releases at a weekly cadence, but we hope to get there eventually.**
# Missing Features: Alphas, and Nightly
Our strategy has a few tradeoffs, which for now we feel are appropriate. Most importantly that new features in master may take a while before reaching a stable release line. If you want to try a new feature immediately, you will have to build Electron yourself.
<img style="width:100%;margin:20px 0;" src="https://cdn.rawgit.com/electron/electron/master/docs/images/tutorial-release-schedule.svg">
As a future consideration, we may introduce one or both of the following:
Here are some important points to call out:
* nightly builds off of master; these would allow folks to test new features quickly and give feedback
* alpha releases that have looser stability constraints to betas; for example it would be allowable to admit new features while a stability channel is in _alpha_
- A new release is performed approximately weekly.
- Minor versions are branched off of master for stabilization.
- The stabilization period is approximately weekly.
- Important bug fixes are cherry-picked to stabilization branches after landing
in master.
- Features are not cherry picked; a minor version should only get *more stable*
with its patch versions.
- There is little difference in the release schedule between a major and minor
release, other than the risk/effort it may take for third parties to adopt
- Chromium updates will be performed as fast as the team can manage. In an ideal
world this would happen every 6 weeks to align with
[Chromium's release schedule][Chromium release].
- Excluding exceptional circumstances, only the previous stable build will
get backported bug fixes.
# Feature Flags
Feature flags are a common practice in Chromium, and are well-established in the web-development ecosystem. In the context of Electron, a feature flag or **soft branch** must have the following properties:
### The Beta Process
* it is enabled/disabled either at runtime, or build-time; we do not support the concept of a request-scoped feature flag
* it completely segments new and old code paths; refactoring old code to support a new feature _violates_ the feature-flag contract
* feature flags are eventually removed after the soft-branch is merged
Electron relies on its consumers getting involved in stabilization. The short
target stabilization period and rapid release cadence was designed for shipping
security and bug fixes out fast and to encourage the automation of testing.
We reconcile flagged code with our versioning strategy as follows:
You can install the beta by specifying the `beta` dist tag when installing via
npm:
1. we do not consider iterating on feature-flagged code in a stability branch; even judicious use of feature flags is not without risk
2. you may break API contracts in feature-flagged code without bumping the major version. Flagged code does not adhere to semver
```sh
npm install electron@beta
```
# Semantic Commits
[Semantic Versioning]: http://semver.org
[pre-release identifier]: http://semver.org/#spec-item-9
[npm dist tag]: https://docs.npmjs.com/cli/dist-tag
[normal version]: http://semver.org/#spec-item-2
[Chromium release]: https://www.chromium.org/developers/calendar
We seek to increase clarity at all levels of the update and releases process. Starting with `2.0.0` we will require pull requests adhere to the [Conventional Commits](https://conventionalcommits.org/) spec, which can be summarized as follows:
* Commits that would result in a semver **major** bump must start with `BREAKING CHANGE:`.
* Commits that would result in a semver **minor** bump must start with `feat:`.
* Commits that would result in a semver **patch** bump must start with `fix:`.
* We allow squashing of commits, provided that the squashed message adheres the the above message format.
* It is acceptable for some commits in a pull request to not include a semantic prefix, as long as a later commit in the same pull request contains a meaningful encompassing semantic message.
# Versionless `master`
- The `master` branch will always contain `0.0.0-dev` in its `package.json`
- Release branches are never merged back to master
- Release branches _do_ contain the correct version in their `package.json`

235
docs/tutorial/first-app.md Normal file
View File

@@ -0,0 +1,235 @@
# Writing Your First Electron App
Electron enables you to create desktop applications with pure JavaScript by
providing a runtime with rich native (operating system) APIs. You could see it
as a variant of the Node.js runtime that is focused on desktop applications
instead of web servers.
This doesn't mean Electron is a JavaScript binding to graphical user interface
(GUI) libraries. Instead, Electron uses web pages as its GUI, so you could also
see it as a minimal Chromium browser, controlled by JavaScript.
**Note**: This example is also available as a repository you can
[download and run immediately](#trying-this-example).
As far as development is concerned, an Electron application is essentially a
Node.js application. The starting point is a `package.json` that is identical
to that of a Node.js module. A most basic Electron app would have the following
folder structure:
```text
your-app/
├── package.json
├── main.js
└── index.html
```
Create a new empty folder for your new Electron application. Open up your
command line client and run `npm init` from that very folder.
```sh
npm init
```
npm will guide you through creating a basic `package.json` file. The script
specified by the `main` field is the startup script of your app, which will
run the main process. An example of your `package.json` might look like this:
```json
{
"name": "your-app",
"version": "0.1.0",
"main": "main.js"
}
```
__Note__: If the `main` field is not present in `package.json`, Electron will
attempt to load an `index.js` (just like Node.js itself). If this was actually
a simple Node application, you would add a `start` script that instructs `node`
to execute the current package:
```json
{
"name": "your-app",
"version": "0.1.0",
"main": "main.js",
"scripts": {
"start": "node ."
}
}
```
Turning this Node application into an Electron application is quite simple - we
merely replace the `node` runtime with the `electron` runtime.
```json
{
"name": "your-app",
"version": "0.1.0",
"main": "main.js",
"scripts": {
"start": "electron ."
}
}
```
## Installing Electron
At this point, you'll need to install `electron` itself. The recommended way
of doing so is to install it as a development dependency in your app, which
allows you to work on multiple apps with different Electron versions. To do so,
run the following command from your app's directory:
```sh
npm install --save-dev electron
```
Other means for installing Electron exist. Please consult the
[installation guide](installation.md) to learn about use with proxies, mirrors,
and custom caches.
## Electron Development in a Nutshell
Electron apps are developed in JavaScript using the same principals and methods
found in Node.js development. All APIs and features found in Electron are
accessible through the `electron` module, which can be required like any other
Node.js module:
```javascript
const electron = require('electron')
```
The `electron` module exposes features in namespaces. As examples, the lifecycle
of the application is managed through `electron.app`, windows can be created
using the `electron.BrowserWindow` class. A simple `main.js` file might just wait
for the application to be ready and open a window:
```javascript
const {app, BrowserWindow} = require('electron')
function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
}
app.on('ready', createWindow)
```
The `main.js` should create windows and handle all the system events your
application might encounter. A more complete version of the above example
might open developer tools, handle the window being closed, or re-create
windows on macOS if the user clicks on the app's icon in the dock.
```javascript
const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
// Open the DevTools.
win.webContents.openDevTools()
// Emitted when the window is closed.
win.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
```
Finally the `index.html` is the web page you want to show:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using node <script>document.write(process.versions.node)</script>,
Chrome <script>document.write(process.versions.chrome)</script>,
and Electron <script>document.write(process.versions.electron)</script>.
</body>
</html>
```
## Running Your App
Once you've created your initial `main.js`, `index.html`, and `package.json`
files, you can try your app by running `npm start` from your application's
directory.
## Trying this Example
Clone and run the code in this tutorial by using the
[`electron/electron-quick-start`][quick-start] repository.
**Note**: Running this requires [Git](https://git-scm.com).
```sh
# Clone the repository
$ git clone https://github.com/electron/electron-quick-start
# Go into the repository
$ cd electron-quick-start
# Install dependencies
$ npm install
# Run the app
$ npm start
```
For a list of boilerplates and tools to kick-start your development process,
see the [Boilerplates and CLIs documentation][boilerplates].
[share-data]: ../faq.md#how-to-share-data-between-web-pages
[quick-start]: https://github.com/electron/electron-quick-start
[boilerplates]: ./boilerplates-and-clis.md

View File

@@ -1,8 +1,6 @@
# Installation
> Tips for installing Electron
To install prebuilt Electron binaries, use [`npm`](https://docs.npmjs.com/).
To install prebuilt Electron binaries, use [`npm`][npm].
The preferred method is to install Electron as a development dependency in your
app:
@@ -10,9 +8,8 @@ app:
npm install electron --save-dev
```
See the
[Electron versioning doc](https://electronjs.org/docs/tutorial/electron-versioning)
for info on how to manage Electron versions in your apps.
See the [Electron versioning doc][versioning] for info on how to
manage Electron versions in your apps.
## Global Installation
@@ -32,7 +29,7 @@ If you want to change the architecture that is downloaded (e.g., `ia32` on an
npm install --arch=ia32 electron
```
In addition to changing the architecture, you can also specify the platform
In addition to changing the architecture, you can also specify the platform
(e.g., `win32`, `linux`, etc.) using the `--platform` flag:
```shell
@@ -41,37 +38,104 @@ npm install --platform=win32 electron
## Proxies
If you need to use an HTTP proxy you can [set these environment variables](https://github.com/request/request/tree/f0c4ec061141051988d1216c24936ad2e7d5c45d#controlling-proxy-behaviour-using-environment-variables).
If you need to use an HTTP proxy you can [set these environment variables][proxy-env].
## Custom Mirrors and Caches
During installation, the `electron` module will call out to
[`electron-download`][electron-download] to download prebuilt binaries of
Electron for your platform. It will do so by contacting GitHub's
release download page (`https://github.com/electron/electron/releases/tag/v$VERSION`,
where `$VERSION` is the exact version of Electron).
If you are unable to access GitHub or you need to provide a custom build, you
can do so by either providing a mirror or an existing cache directory.
#### Mirror
You can use environment variables to override the base URL, the path at which to
look for Electron binaries, and the binary filename. The url used by `electron-download`
is composed as follows:
```txt
url = ELECTRON_MIRROR + ELECTRON_CUSTOM_DIR + '/' + ELECTRON_CUSTOM_FILENAME
```
For instance, to use the China mirror:
```txt
ELECTRON_MIRROR="https://npm.taobao.org/mirrors/electron/"
```
#### Cache
Alternatively, you can override the local cache. `electron-download` will cache
downloaded binaries in a local directory to not stress your network. You can use
that cache folder to provide custom builds of Electron or to avoid making contact
with the network at all.
* Linux: `$XDG_CACHE_HOME` or `~/.cache/electron/`
* MacOS: `~/Library/Caches/electron/`
* Windows: `$LOCALAPPDATA/electron/Cache` or `~/AppData/Local/electron/Cache/`
On environments that have been using older versions of Electron, you might find the
cache also in `~/.electron`.
You can also override the local cache location by providing a `ELECTRON_CACHE`
environment variable.
The cache contains the version's official zip file as well as a checksum, stored as
a text file. A typical cache might look like this:
```sh
├── electron-v1.7.9-darwin-x64.zip
├── electron-v1.8.1-darwin-x64.zip
├── electron-v1.8.2-beta.1-darwin-x64.zip
├── electron-v1.8.2-beta.2-darwin-x64.zip
├── electron-v1.8.2-beta.3-darwin-x64.zip
├── SHASUMS256.txt-1.7.9
├── SHASUMS256.txt-1.8.1
├── SHASUMS256.txt-1.8.2-beta.1
├── SHASUMS256.txt-1.8.2-beta.2
├── SHASUMS256.txt-1.8.2-beta.3
```
## Troubleshooting
When running `npm install electron`, some users occasionally encounter
When running `npm install electron`, some users occasionally encounter
installation errors.
In almost all cases, these errors are the result of network problems and not
actual issues with the `electron` npm package. Errors like `ELIFECYCLE`,
`EAI_AGAIN`, `ECONNRESET`, and `ETIMEDOUT` are all indications of such
network problems. The best resolution is to try switching networks, or
In almost all cases, these errors are the result of network problems and not
actual issues with the `electron` npm package. Errors like `ELIFECYCLE`,
`EAI_AGAIN`, `ECONNRESET`, and `ETIMEDOUT` are all indications of such
network problems. The best resolution is to try switching networks, or
just wait a bit and try installing again.
You can also attempt to download Electron directly from
[electron/electron/releases](https://github.com/electron/electron/releases)
You can also attempt to download Electron directly from
[electron/electron/releases][releases]
if installing via `npm` is failing.
If installation fails with an `EACCESS` error you may need to
[fix your npm permissions](https://docs.npmjs.com/getting-started/fixing-npm-permissions).
If installation fails with an `EACCESS` error you may need to
[fix your npm permissions][npm-permissions].
If the above error persists, the [unsafe-perm](https://docs.npmjs.com/misc/config#unsafe-perm) flag may need to be set to true:
If the above error persists, the [unsafe-perm][unsafe-perm] flag may need to be
set to true:
```sh
sudo npm install electron --unsafe-perm=true
```
On slower networks, it may be advisable to use the `--verbose` flag in order to show download progress:
On slower networks, it may be advisable to use the `--verbose` flag in order to
show download progress:
```sh
npm install --verbose electron
```
If you need to force a re-download of the asset and the SHASUM file set the
`force_no_cache` enviroment variable to `true`.
`force_no_cache` environment variable to `true`.
[npm]: https://docs.npmjs.com
[versioning]: ./electron-versioning.md
[releases]: https://github.com/electron/electron/releases
[proxy-env]: https://github.com/request/request/tree/f0c4ec061141051988d1216c24936ad2e7d5c45d#controlling-proxy-behaviour-using-environment-variables
[electron-download]: https://github.com/electron-userland/electron-download
[npm-permissions]: https://docs.npmjs.com/getting-started/fixing-npm-permissions
[unsafe-perm]: https://docs.npmjs.com/misc/config#unsafe-perm

View File

@@ -52,7 +52,7 @@ window.addEventListener('keyup', doSomething, true)
Note the third parameter `true` which means the listener will always receive key presses before other listeners so they can't have `stopPropagation()` called on them.
The [`before-input-event`](web-contents.md#event-before-input-event) event
The [`before-input-event`](../api/web-contents.md#event-before-input-event) event
is emitted before dispatching `keydown` and `keyup` events in the page. It can
be used to catch and handle custom shortcuts that are not visible in the menu.

View File

@@ -0,0 +1,41 @@
# Custom Linux Desktop Launcher Actions
On many Linux environments, you can add custom entries to its launcher
by modifying the `.desktop` file. For Canonical's Unity documentation,
see [Adding Shortcuts to a Launcher][unity-launcher]. For details on a
more generic implementation, see the [freedesktop.org Specification][spec].
__Launcher shortcuts of Audacious:__
![audacious][audacious-launcher]
Generally speaking, shortcuts are added by providing a `Name` and `Exec`
property for each entry in the shortcuts menu. Unity will execute the
`Exec` field once clicked by the user. The format is as follows:
```text
Actions=PlayPause;Next;Previous
[Desktop Action PlayPause]
Name=Play-Pause
Exec=audacious -t
OnlyShowIn=Unity;
[Desktop Action Next]
Name=Next
Exec=audacious -f
OnlyShowIn=Unity;
[Desktop Action Previous]
Name=Previous
Exec=audacious -r
OnlyShowIn=Unity;
```
Unity's preferred way of telling your application what to do is to use
parameters. You can find these in your app in the global variable
`process.argv`.
[unity-launcher]: https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles#Adding_shortcuts_to_a_launcher
[audacious-launcher]: https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles?action=AttachFile&do=get&target=shortcuts.png
[spec]: https://specifications.freedesktop.org/desktop-entry-spec/1.1/ar01s11.html

View File

@@ -231,7 +231,7 @@ more details.
## Known issues
### `shell.openItem(filePath)`
### `shell.openItem(filePath)`
This will fail when the app is signed for distribution in the Mac App Store.
Subscribe to [#9005](https://github.com/electron/electron/issues/9005) for updates.
@@ -248,29 +248,29 @@ submit a copy of U.S. Encryption Registration (ERN) approval.
Electron uses following cryptographic algorithms:
* AES - [NIST SP 800-38A](http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf), [NIST SP 800-38D](http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf), [RFC 3394](http://www.ietf.org/rfc/rfc3394.txt)
* HMAC - [FIPS 198-1](http://csrc.nist.gov/publications/fips/fips198-1/FIPS-198-1_final.pdf)
* AES - [NIST SP 800-38A](https://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf), [NIST SP 800-38D](https://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf), [RFC 3394](https://www.ietf.org/rfc/rfc3394.txt)
* HMAC - [FIPS 198-1](https://csrc.nist.gov/publications/fips/fips198-1/FIPS-198-1_final.pdf)
* ECDSA - ANS X9.622005
* ECDH - ANS X9.632001
* HKDF - [NIST SP 800-56C](http://csrc.nist.gov/publications/nistpubs/800-56C/SP-800-56C.pdf)
* HKDF - [NIST SP 800-56C](https://csrc.nist.gov/publications/nistpubs/800-56C/SP-800-56C.pdf)
* PBKDF2 - [RFC 2898](https://tools.ietf.org/html/rfc2898)
* RSA - [RFC 3447](http://www.ietf.org/rfc/rfc3447)
* SHA - [FIPS 180-4](http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf)
* SHA - [FIPS 180-4](https://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf)
* Blowfish - https://www.schneier.com/cryptography/blowfish/
* CAST - [RFC 2144](https://tools.ietf.org/html/rfc2144), [RFC 2612](https://tools.ietf.org/html/rfc2612)
* DES - [FIPS 46-3](http://csrc.nist.gov/publications/fips/fips46-3/fips46-3.pdf)
* DES - [FIPS 46-3](https://csrc.nist.gov/publications/fips/fips46-3/fips46-3.pdf)
* DH - [RFC 2631](https://tools.ietf.org/html/rfc2631)
* DSA - [ANSI X9.30](http://webstore.ansi.org/RecordDetail.aspx?sku=ANSI+X9.30-1%3A1997)
* DSA - [ANSI X9.30](https://webstore.ansi.org/RecordDetail.aspx?sku=ANSI+X9.30-1%3A1997)
* EC - [SEC 1](http://www.secg.org/sec1-v2.pdf)
* IDEA - "On the Design and Security of Block Ciphers" book by X. Lai
* MD2 - [RFC 1319](http://tools.ietf.org/html/rfc1319)
* MD2 - [RFC 1319](https://tools.ietf.org/html/rfc1319)
* MD4 - [RFC 6150](https://tools.ietf.org/html/rfc6150)
* MD5 - [RFC 1321](https://tools.ietf.org/html/rfc1321)
* MDC2 - [ISO/IEC 10118-2](https://www.openssl.org/docs/manmaster/crypto/mdc2.html)
* MDC2 - [ISO/IEC 10118-2](https://wiki.openssl.org/index.php/Manual:Mdc2(3))
* RC2 - [RFC 2268](https://tools.ietf.org/html/rfc2268)
* RC4 - [RFC 4345](https://tools.ietf.org/html/rfc4345)
* RC5 - http://people.csail.mit.edu/rivest/Rivest-rc5rev.pdf
* RIPEMD - [ISO/IEC 10118-3](http://webstore.ansi.org/RecordDetail.aspx?sku=ISO%2FIEC%2010118-3:2004)
* RIPEMD - [ISO/IEC 10118-3](https://webstore.ansi.org/RecordDetail.aspx?sku=ISO%2FIEC%2010118-3:2004)
On how to get the ERN approval, you can reference the article: [How to legally
submit an app to Apples App Store when it uses encryption (or how to obtain an

View File

@@ -0,0 +1,41 @@
# MacOS Dock
Electron has APIs to configure the app's icon in the macOS Dock. A macOS-only
API exists to create a [a custom dock menu](#custom-dock-menu-mac-os), but
Electron also uses the app's dock icon to implement cross-platform features
like [recent documents][recent-documents] and
[application progress][progress-bar].
The custom dock is commonly used to add shortcuts to tasks the user wouldn't
want to open the whole app window for.
__Dock menu of Terminal.app:__
![Dock Menu][dock-menu-image]
To set your custom dock menu, you can use the `app.dock.setMenu` API, which is
only available on macOS:
```javascript
const { app, Menu } = require('electron')
const dockMenu = Menu.buildFromTemplate([
{
label: 'New Window',
click () { console.log('New Window') }
}, {
label: 'New Window with Settings',
submenu: [
{ label: 'Basic' },
{ label: 'Pro' }
]
},
{ label: 'New Command...' }
])
app.dock.setMenu(dockMenu)
```
[dock-menu-image]: https://cloud.githubusercontent.com/assets/639601/5069962/6032658a-6e9c-11e4-9953-aa84006bdfff.png
[recent-documents]: ./recent-documents.md
[progress-bar]: ./progress-bar.md

View File

@@ -0,0 +1,37 @@
# Native File Drag & Drop
Certain kinds of applications that manipulate files might want to support
the operating system's native file drag & drop feature. Dragging files into
web content is common and supported by many websites. Electron additionally
supports dragging files and content out from web content into the operating
system's world.
To implement this feature in your app, you need to call `webContents.startDrag(item)`
API in response to the `ondragstart` event.
In your renderer process, handle the `ondragstart` event and forward the
information to your main process.
```html
<a href="#" id="drag">item</a>
<script type="text/javascript" charset="utf-8">
document.getElementById('drag').ondragstart = (event) => {
event.preventDefault()
ipcRenderer.send('ondragstart', '/path/to/item')
}
</script>
```
Then, in the main process, augment the event with a path to the file that is
being dragged and an icon.
```javascript
const { ipcMain } = require('electron')
ipcMain.on('ondragstart', (event, filePath) => {
event.sender.startDrag({
file: filePath,
icon: '/path/to/icon.png'
})
})
```

View File

@@ -14,7 +14,7 @@ performance loss.
**Note:** An offscreen window is always created as a [Frameless Window](../api/frameless-window.md).
## Two modes of rendering
## Rendering Modes
### GPU accelerated
@@ -35,17 +35,19 @@ To enable this mode GPU acceleration has to be disabled by calling the
## Usage
``` javascript
const {app, BrowserWindow} = require('electron')
const { app, BrowserWindow } = require('electron')
app.disableHardwareAcceleration()
let win
app.once('ready', () => {
win = new BrowserWindow({
webPreferences: {
offscreen: true
}
})
win.loadURL('http://github.com')
win.webContents.on('paint', (event, dirty, image) => {
// updateBitmap(dirty, image.getBitmap())

View File

@@ -1,6 +1,6 @@
# Planned Breaking API Changes
The following list includes the APIs that will be removed in Electron 2.0.
The following list includes the APIs that will be removed in Electron 3.0.
There is no timetable for when this release will occur but deprecation
warnings will be added at least 90 days beforehand.
@@ -25,16 +25,6 @@ let optionsB = {webPreferences: {enableBlinkFeatures: ''}}
let windowB = new BrowserWindow(optionsB)
```
```js
// Deprecated
let optionsA = {titleBarStyle: 'hidden-inset'}
let windowA = new BrowserWindow(optionsA)
// Replace with
let optionsB = {titleBarStyle: 'hiddenInset'}
let windowB = new BrowserWindow(optionsB)
```
## `clipboard`
```js
@@ -76,28 +66,9 @@ crashReporter.start({
})
```
## `menu`
```js
// Deprecated
menu.popup(browserWindow, 100, 200, 2)
// Replace with
menu.popup(browserWindow, {x: 100, y: 200, positioningItem: 2})
```
## `nativeImage`
```js
// Deprecated
nativeImage.toPng()
// Replace with
nativeImage.toPNG()
// Deprecated
nativeImage.toJpeg()
// Replace with
nativeImage.toJPEG()
// Deprecated
nativeImage.createFromBuffer(buffer, 1.0)
// Replace with
@@ -106,19 +77,15 @@ nativeImage.createFromBuffer(buffer, {
})
```
## `process`
## `screen`
```js
// Deprecated
process.versions['atom-shell']
screen.getMenuBarHeight()
// Replace with
process.versions.electron
screen.getPrimaryDisplay().workArea
```
* `process.versions.electron` and `process.version.chrome` will be made
read-only properties for consistency with the other `process.versions`
properties set by Node.
## `session`
```js
@@ -155,21 +122,9 @@ webContents.openDevTools({detach: true})
webContents.openDevTools({mode: 'detach'})
```
```js
// Deprecated
webContents.setZoomLevelLimits(1, 2)
// Replace with
webContents.setVisualZoomLevelLimits(1, 2)
```
## `webFrame`
```js
// Deprecated
webFrame.setZoomLevelLimits(1, 2)
// Replace with
webFrame.setVisualZoomLevelLimits(1, 2)
// Deprecated
webFrame.registerURLSchemeAsSecure('app')
// Replace with
@@ -181,15 +136,6 @@ webFrame.registerURLSchemeAsPrivileged('app', {secure: true})
protocol.registerStandardSchemes(['app'], {secure: true})
```
## `<webview>`
```js
// Deprecated
webview.setZoomLevelLimits(1, 2)
// Replace with
webview.setVisualZoomLevelLimits(1, 2)
```
## Node Headers URL
This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url`
@@ -199,26 +145,8 @@ Deprecated: https://atom.io/download/atom-shell
Replace with: https://atom.io/download/electron
## Duplicate ARM Assets
Each Electron release includes two identical ARM builds with slightly different
filenames, like `electron-v1.7.3-linux-arm.zip` and
`electron-v1.7.3-linux-armv7l.zip`. The asset with the `v7l` prefix was added
to clarify to users which ARM version it supports, and to disambiguate it from
future armv6l and arm64 assets that may be produced.
The file _without the prefix_ is still being published to avoid breaking any
setups that may be consuming it. Starting at 2.0, the un-prefixed file will
no longer be published.
For details, see
[6986](https://github.com/electron/electron/pull/6986)
and
[7189](https://github.com/electron/electron/pull/7189).
## `FIXME` comments
The `FIXME` string is used in code comments to denote things that should be
fixed for the 2.0 release. See
The `FIXME` string is used in code comments to denote things that should be
fixed for the 3.0 release. See
https://github.com/electron/electron/search?q=fixme

View File

@@ -0,0 +1,35 @@
# Progress Bar in Taskbar (Windows, macOS, Unity)
On Windows a taskbar button can be used to display a progress bar. This enables
a window to provide progress information to the user without the user having to
switch to the window itself.
On macOS the progress bar will be displayed as a part of the dock icon.
The Unity DE also has a similar feature that allows you to specify the progress
bar in the launcher.
__Progress bar in taskbar button:__
![Taskbar Progress Bar][taskbar-progress-image]
All three cases are covered by the same API - the `setProgressBar()` method
available on instances of `BrowserWindows`. Call it with a number between `0`
and `1` to indicate your progress. If you have a long-running task that's
currently at 63% towards completion, you'd call it with `setProgressBar(0.63)`.
Generally speaking, setting the parameter to a value below zero (like `-1`)
will remove the progress bar while setting it to a value higher than one
(like `2`) will switch the progress bar to intermediate mode.
See the [API documentation for more options and modes][setprogressbar].
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.setProgressBar(0.5)
```
[taskbar-progress-image]: https://cloud.githubusercontent.com/assets/639601/5081682/16691fda-6f0e-11e4-9676-49b6418f1264.png
[setprogressbar]: ../api/browser-window.md#winsetprogressbarprogress

View File

@@ -5,246 +5,18 @@ providing a runtime with rich native (operating system) APIs. You could see it
as a variant of the Node.js runtime that is focused on desktop applications
instead of web servers.
This doesn't mean Electron is a JavaScript binding to graphical user interface
(GUI) libraries. Instead, Electron uses web pages as its GUI, so you could also
see it as a minimal Chromium browser, controlled by JavaScript.
The old "Quick Start" document that used to live here has been split up into
two documents:
### Main Process
* To check out how a simple Electron app is built, see
[Writing Your First Electron App][first-app]
* To check out the process architecture, see
[Main and Renderer Processes][processes].
In Electron, the process that runs `package.json`'s `main` script is called
__the main process__. The script that runs in the main process can display a GUI
by creating web pages.
If you just came here to learn about Electron, check out the
[official guides][readme].
### Renderer Process
[first-app]: ./first-app.md
[processes]: ./application-architecture.md#main-and-renderer-processes
[readme]: ../README.md
Since Electron uses Chromium for displaying web pages, Chromium's
multi-process architecture is also used. Each web page in Electron runs in
its own process, which is called __the renderer process__.
In normal browsers, web pages usually run in a sandboxed environment and are not
allowed access to native resources. Electron users, however, have the power to
use Node.js APIs in web pages allowing lower level operating system
interactions.
### Differences Between Main Process and Renderer Process
The main process creates web pages by creating `BrowserWindow` instances. Each
`BrowserWindow` instance runs the web page in its own renderer process. When a
`BrowserWindow` instance is destroyed, the corresponding renderer process
is also terminated.
The main process manages all web pages and their corresponding renderer
processes. Each renderer process is isolated and only cares about the web page
running in it.
In web pages, calling native GUI related APIs is not allowed because managing
native GUI resources in web pages is very dangerous and it is easy to leak
resources. If you want to perform GUI operations in a web page, the renderer
process of the web page must communicate with the main process to request that
the main process perform those operations.
In Electron, we have several ways to communicate between the main process and
renderer processes. Like [`ipcRenderer`](../api/ipc-renderer.md) and
[`ipcMain`](../api/ipc-main.md) modules for sending messages, and the
[remote](../api/remote.md) module for RPC style communication. There is also
an FAQ entry on [how to share data between web pages][share-data].
## Write your First Electron App
Generally, an Electron app is structured like this:
```text
your-app/
├── package.json
├── main.js
└── index.html
```
The format of `package.json` is exactly the same as that of Node's modules, and
the script specified by the `main` field is the startup script of your app,
which will run the main process. An example of your `package.json` might look
like this:
```json
{
"name" : "your-app",
"version" : "0.1.0",
"main" : "main.js"
}
```
__Note__: If the `main` field is not present in `package.json`, Electron will
attempt to load an `index.js`.
The `main.js` should create windows and handle system events, a typical
example being:
```javascript
const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
// Open the DevTools.
win.webContents.openDevTools()
// Emitted when the window is closed.
win.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
```
Finally the `index.html` is the web page you want to show:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using node <script>document.write(process.versions.node)</script>,
Chrome <script>document.write(process.versions.chrome)</script>,
and Electron <script>document.write(process.versions.electron)</script>.
</body>
</html>
```
## Run your app
Once you've created your initial `main.js`, `index.html`, and `package.json` files,
you'll probably want to try running your app locally to test it and make sure it's
working as expected.
### `electron`
[`electron`](https://github.com/electron-userland/electron-prebuilt) is
an `npm` module that contains pre-compiled versions of Electron.
If you've installed it globally with `npm`, then you will only need to run the
following in your app's source directory:
```sh
electron .
```
If you've installed it locally, then run:
#### macOS / Linux
```sh
$ ./node_modules/.bin/electron .
```
#### Windows
```sh
$ .\node_modules\.bin\electron .
```
#### Node v8.2.0 and later
```sh
$ npx electron .
```
### Manually Downloaded Electron Binary
If you downloaded Electron manually, you can also use the included
binary to execute your app directly.
#### macOS
```sh
$ ./Electron.app/Contents/MacOS/Electron your-app/
```
#### Linux
```sh
$ ./electron/electron your-app/
```
#### Windows
```sh
$ .\electron\electron.exe your-app\
```
`Electron.app` here is part of the Electron's release package, you can download
it from [here](https://github.com/electron/electron/releases).
### Run as a distribution
After you're done writing your app, you can create a distribution by
following the [Application Distribution](./application-distribution.md) guide
and then executing the packaged app.
### Try this Example
Clone and run the code in this tutorial by using the [`electron/electron-quick-start`](https://github.com/electron/electron-quick-start)
repository.
**Note**: Running this requires [Git](https://git-scm.com) and [Node.js](https://nodejs.org/en/download/) (which includes [npm](https://npmjs.org)) on your system.
```sh
# Clone the repository
$ git clone https://github.com/electron/electron-quick-start
# Go into the repository
$ cd electron-quick-start
# Install dependencies
$ npm install
# Run the app
$ npm start
```
For more example apps, see the
[list of boilerplates](https://electronjs.org/community#boilerplates)
created by the awesome electron community.
[share-data]: ../faq.md#how-to-share-data-between-web-pages

View File

@@ -0,0 +1,48 @@
# Recent Documents (Windows & macOS)
Windows and macOS provide easy access to a list of recent documents opened by
the application via JumpList or dock menu, respectively.
__JumpList:__
![JumpList Recent Files][jumplist-image]
__Application dock menu:__
![macOS Dock Menu][dock-menu-image]
To add a file to recent documents, you can use the
[app.addRecentDocument][addrecentdocument] API:
```javascript
const { app } = require('electron')
app.addRecentDocument('/Users/USERNAME/Desktop/work.type')
```
And you can use [app.clearRecentDocuments][clearrecentdocuments] API to empty
the recent documents list:
```javascript
const { app } = require('electron')
app.clearRecentDocuments()
```
## Windows Notes
In order to be able to use this feature on Windows, your application has to be
registered as a handler of the file type of the document, otherwise the file
won't appear in JumpList even after you have added it. You can find everything
on registering your application in [Application Registration][app-registration].
When a user clicks a file from the JumpList, a new instance of your application
will be started with the path of the file added as a command line argument.
## macOS Notes
When a file is requested from the recent documents menu, the `open-file` event
of `app` module will be emitted for it.
[jumplist-image]: https://cloud.githubusercontent.com/assets/2289/23446924/11a27b98-fdfc-11e6-8485-cc3b1e86b80a.png
[dock-menu-image]: https://cloud.githubusercontent.com/assets/639601/5069610/2aa80758-6e97-11e4-8cfb-c1a414a10774.png
[addrecentdocument]: ../api/app.md#appaddrecentdocumentpath-macos-windows
[clearrecentdocuments]: ../api/app.md#appclearrecentdocuments-macos-windows

View File

@@ -0,0 +1,28 @@
# Represented File for macOS BrowserWindows
On macOS a window can set its represented file, so the file's icon can show in
the title bar and when users Command-Click or Control-Click on the title a path
popup will show.
You can also set the edited state of a window so that the file icon can indicate
whether the document in this window has been modified.
__Represented file popup menu:__
![Represented File][represented-image]
To set the represented file of window, you can use the
[BrowserWindow.setRepresentedFilename][setrepresentedfilename] and
[BrowserWindow.setDocumentEdited][setdocumentedited] APIs:
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.setRepresentedFilename('/etc/passwd')
win.setDocumentEdited(true)
```
[represented-image]: https://cloud.githubusercontent.com/assets/639601/5082061/670a949a-6f14-11e4-987a-9aaa04b23c1d.png
[setrepresentedfilename]: ../api/browser-window.md#winsetrepresentedfilenamefilename-macos
[setdocumentedited]: ../api/browser-window.md#winsetdocumenteditededited-macos

View File

@@ -1,17 +1,17 @@
# Security, Native Capabilities, and Your Responsibility
As web developers, we usually enjoy the strong security net of the browser - the
risks associated with the code we write are relatively small. Our websites are
granted limited powers in a sandbox, and we trust that our users enjoy a browser
built by a large team of engineers that is able to quickly respond to newly
discovered security threats.
As web developers, we usually enjoy the strong security net of the browser -
the risks associated with the code we write are relatively small. Our websites
are granted limited powers in a sandbox, and we trust that our users enjoy a
browser built by a large team of engineers that is able to quickly respond to
newly discovered security threats.
When working with Electron, it is important to understand that Electron is not
a web browser. It allows you to build feature-rich desktop applications with
familiar web technologies, but your code wields much greater power. JavaScript
can access the filesystem, user shell, and more. This allows you to build
high quality native applications, but the inherent security risks scale with the
additional powers granted to your code.
high quality native applications, but the inherent security risks scale with
the additional powers granted to your code.
With that in mind, be aware that displaying arbitrary content from untrusted
sources poses a severe security risk that Electron is not intended to handle.
@@ -34,8 +34,8 @@ contributions available today, Electron will often not be on the very latest
version of Chromium, lagging behind by either days or weeks.
We feel that our current system of updating the Chromium component strikes an
appropriate balance between the resources we have available and the needs of the
majority of applications built on top of the framework. We definitely are
appropriate balance between the resources we have available and the needs of
the majority of applications built on top of the framework. We definitely are
interested in hearing more about specific use cases from the people that build
things on top of Electron. Pull requests and contributions supporting this
effort are always very welcome.
@@ -44,41 +44,500 @@ effort are always very welcome.
A security issue exists whenever you receive code from a remote destination and
execute it locally. As an example, consider a remote website being displayed
inside a browser window. If an attacker somehow manages to change said content
(either by attacking the source directly, or by sitting between your app and
the actual destination), they will be able to execute native code on the user's
machine.
inside a [`BrowserWindow`][browser-window]. If an attacker somehow manages to
change said content (either by attacking the source directly, or by sitting
between your app and the actual destination), they will be able to execute
native code on the user's machine.
> :warning: Under no circumstances should you load and execute remote code with
Node integration enabled. Instead, use only local files (packaged together with
your application) to execute Node code. To display remote content, use the
`webview` tag and make sure to disable the `nodeIntegration`.
Node.js integration enabled. Instead, use only local files (packaged together
with your application) to execute Node.js code. To display remote content, use
the [`webview`][web-view] tag and make sure to disable the `nodeIntegration`.
#### Checklist
## Electron Security Warnings
This is not bulletproof, but at the least, you should attempt the following:
From Electron 2.0 on, developers will see warnings and recommendations printed
to the developer console. They only show up when the binary's name is Electron,
indicating that a developer is currently looking at the console.
* Only display secure (https) content
* Disable the Node integration in all renderers that display remote content
(setting `nodeIntegration` to `false` in `webPreferences`)
* Enable context isolation in all renderers that display remote content
(setting `contextIsolation` to `true` in `webPreferences`)
* Use `ses.setPermissionRequestHandler()` in all sessions that load remote content
* Do not disable `webSecurity`. Disabling it will disable the same-origin policy.
* Define a [`Content-Security-Policy`](http://www.html5rocks.com/en/tutorials/security/content-security-policy/)
, and use restrictive rules (i.e. `script-src 'self'`)
* [Override and disable `eval`](https://github.com/nylas/N1/blob/0abc5d5defcdb057120d726b271933425b75b415/static/index.js#L6-L8)
, which allows strings to be executed as code.
* Do not set `allowRunningInsecureContent` to true.
* Do not enable `experimentalFeatures` or `experimentalCanvasFeatures` unless
you know what you're doing.
* Do not use `blinkFeatures` unless you know what you're doing.
* WebViews: Do not add the `nodeintegration` attribute.
* WebViews: Do not use `disablewebsecurity`
* WebViews: Do not use `allowpopups`
* WebViews: Do not use `insertCSS` or `executeJavaScript` with remote CSS/JS.
* WebViews: Verify the options and params of all `<webview>` tags before they
get attached using the `will-attach-webview` event:
You can force-enable or force-disable these warnings by setting
`ELECTRON_ENABLE_SECURITY_WARNINGS` or `ELECTRON_DISABLE_SECURITY_WARNINGS` on
either `process.env` or the `window` object.
## Checklist: Security Recommendations
This is not bulletproof, but at the least, you should follow these steps to
improve the security of your application.
1. [Only load secure content](#only-load-secure-content)
2. [Disable the Node.js integration in all renderers that display remote content](#disable-node.js-integration-for-remote-content)
3. [Enable context isolation in all renderers that display remote content](#enable-context-isolation-for-remote-content)
4. [Use `ses.setPermissionRequestHandler()` in all sessions that load remote content](#handle-session-permission-requests-from-remote-content)
5. [Do not disable `webSecurity`](#do-not-disable-websecurity)
6. [Define a `Content-Security-Policy`](#define-a-content-security-policy) and use restrictive rules (i.e. `script-src 'self'`)
7. [Override and disable `eval`](#override-and-disable-eval), which allows strings to be executed as code.
8. [Do not set `allowRunningInsecureContent` to `true`](#do-not-set-allowRunningInsecureContent-to-true)
9. [Do not enable experimental features](#do-not-enable-experimental-features)
10. [Do not use `blinkFeatures`](#do-not-use-blinkfeatures)
11. [WebViews: Do not use `allowpopups`](#do-not-use-allowpopups)
12. [WebViews: Verify the options and params of all `<webview>` tags](#verify-webview-options-before-creation)
## 1) Only Load Secure Content
Any resources not included with your application should be loaded using a
secure protocol like `HTTPS`. In other words, do not use insecure protocols
like `HTTP`. Similarly, we recommend the use of `WSS` over `WS`, `FTPS` over
`FTP`, and so on.
### Why?
`HTTPS` has three main benefits:
1) It authenticates the remote server, ensuring your app connects to the correct
host instead of an impersonator.
2) It ensures data integrity, asserting that the data was not modified while in
transit between your application and the host.
3) It encrypts the traffic between your user and the destination host, making it
more difficult to eavesdrop on the information sent between your app and
the host.
### How?
```js
// Bad
browserWindow.loadURL('http://my-website.com')
// Good
browserWindow.loadURL('https://my-website.com')
```
```html
<!-- Bad -->
<script crossorigin src="http://cdn.com/react.js"></script>
<link rel="stylesheet" href="http://cdn.com/style.css">
<!-- Good -->
<script crossorigin src="https://cdn.com/react.js"></script>
<link rel="stylesheet" href="https://cdn.com/style.css">
```
## 2) Disable Node.js Integration for Remote Content
It is paramount that you disable Node.js integration in any renderer
([`BrowserWindow`][browser-window], [`BrowserView`][browser-view], or
[`WebView`][web-view]) that loads remote content. The goal is to limit the
powers you grant to remote content, thus making it dramatically more difficult
for an attacker to harm your users should they gain the ability to execute
JavaScript on your website.
After this, you can grant additional permissions for specific hosts. For example,
if you are opening a BrowserWindow pointed at `https://my-website.com/", you can
give that website exactly the abilities it needs, but no more.
### Why?
A cross-site-scripting (XSS) attack is more dangerous if an attacker can jump
out of the renderer process and execute code on the user's computer.
Cross-site-scripting attacks are fairly common - and while an issue, their
power is usually limited to messing with the website that they are executed on.
Disabling Node.js integration helps prevent an XSS from being escalated into a
so-called "Remote Code Execution" (RCE) attack.
### How?
```js
// Bad
const mainWindow = new BrowserWindow()
mainWindow.loadURL('https://my-website.com')
```
```js
// Good
const mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: false,
preload: './preload.js'
}
})
mainWindow.loadURL('https://my-website.com')
```
```html
<!-- Bad -->
<webview nodeIntegration src="page.html"></webview>
<!-- Good -->
<webview src="page.html"></webview>
```
When disabling Node.js integration, you can still expose APIs to your website that
do consume Node.js modules or features. Preload scripts continue to have access
to `require` and other Node.js features, allowing developers to expose a custom
API to remotely loaded content.
In the following example preload script, the later loaded website will have
access to a `window.readConfig()` method, but no Node.js features.
```js
const { readFileSync } = require('fs')
window.readConfig = function () {
const data = readFileSync('./config.json')
return data
}
```
## 3) Enable Context Isolation for Remote Content
Context isolation is an Electron feature that allows developers to run code
in preload scripts and in Electron APIs in a dedicated JavaScript context. In
practice, that means that global objects like `Array.prototype.push` or
`JSON.parse` cannot be modified by scripts running in the renderer process.
Electron uses the same technology as Chromium's [Content Scripts](https://developer.chrome.com/extensions/content_scripts#execution-environment)
to enable this behavior.
### Why?
Context isolation allows each the scripts on running in the renderer to make
changes to its JavaScript environment without worrying about conflicting with
the scripts in the Electron API or the preload script.
While still an experimental Electron feature, context isolation adds an
additional layer of security. It creates a new JavaScript world for Electron
APIs and preload scripts.
At the same time, preload scripts still have access to the `document` and
`window` objects. In other words, you're getting a decent return on a likely
very small investment.
### How?
```js
// Main process
const mainWindow = new BrowserWindow({
webPreferences: {
contextIsolation: true,
preload: 'preload.js'
}
})
```
```js
// Preload script
// Set a variable in the page before it loads
webFrame.executeJavaScript('window.foo = "foo";')
// The loaded page will not be able to access this, it is only available
// in this context
window.bar = 'bar'
document.addEventListener('DOMContentLoaded', () => {
// Will log out 'undefined' since window.foo is only available in the main
// context
console.log(window.foo)
// Will log out 'bar' since window.bar is available in this context
console.log(window.bar)
})
```
## 4) Handle Session Permission Requests From Remote Content
You may have seen permission requests while using Chrome: They pop up whenever
the website attempts to use a feature that the user has to manually approve (
like notifications).
The API is based on the [Chromium permissions API](https://developer.chrome.com/extensions/permissions)
and implements the same types of permissions.
### Why?
By default, Electron will automatically approve all permission requests unless
the developer has manually configured a custom handler. While a solid default,
security-conscious developers might want to assume the very opposite.
### How?
```js
const { session } = require('electron')
session
.fromPartition('some-partition')
.setPermissionRequestHandler((webContents, permission, callback) => {
const url = webContents.getURL()
if (permission === 'notifications') {
// Approves the permissions request
callback(true)
}
if (!url.startsWith('https://my-website.com')) {
// Denies the permissions request
return callback(false)
}
})
```
## 5) Do Not Disable WebSecurity
_Recommendation is Electron's default_
You may have already guessed that disabling the `webSecurity` property on a
renderer process ([`BrowserWindow`][browser-window],
[`BrowserView`][browser-view], or [`WebView`][web-view]) disables crucial
security features.
Do not disable `webSecurity` in production applications.
### Why?
Disabling `webSecurity` will disable the same-origin policy and set
`allowRunningInsecureContent` property to `true`. In other words, it allows
the execution of insecure code from different domains.
### How?
```js
// Bad
const mainWindow = new BrowserWindow({
webPreferences: {
webSecurity: false
}
})
```
```js
// Good
const mainWindow = new BrowserWindow()
```
```html
<!-- Bad -->
<webview disablewebsecurity src="page.html"></webview>
<!-- Good -->
<webview src="page.html"></webview>
```
## 6) Define a Content Security Policy
A Content Security Policy (CSP) is an additional layer of protection against
cross-site-scripting attacks and data injection attacks. We recommend that they
be enabled by any website you load inside Electron.
### Why?
CSP allows the server serving content to restrict and control the resources
Electron can load for that given web page. `https://your-page.com` should
be allowed to load scripts from the origins you defined while scripts from
`https://evil.attacker.com` should not be allowed to run. Defining a CSP is an
easy way to improve your applications security.
### How?
Electron respects [the `Content-Security-Policy` HTTP header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy)
and the respective `<meta>` tag.
The following CSP will allow Electron to execute scripts from the current
website and from `apis.mydomain.com`.
```txt
// Bad
Content-Security-Policy: '*'
// Good
Content-Security-Policy: script-src 'self' https://apis.mydomain.com
```
## 7) Override and Disable `eval`
`eval()` is a core JavaScript method that allows the execution of JavaScript
from a string. Disabling it disables your app's ability to evaluate JavaScript
that is not known in advance.
### Why?
The `eval()` method has precisely one mission: To evaluate a series of
characters as JavaScript and execute it. It is a required method whenever you
need to evaluate code that is not known ahead of time. While legitimate use
cases exist, just like any other code generators, `eval()` is difficult to
harden.
Generally speaking, it is easier to completely disable `eval()` than to make
it bulletproof. Thus, if you do not need it, it is a good idea to disable it.
### How?
```js
// ESLint will warn about any use of eval(), even this one
// eslint-disable-next-line
window.eval = global.eval = function () {
throw new Error(`Sorry, this app does not support window.eval().`)
}
```
## 8) Do Not Set `allowRunningInsecureContent` to `true`
_Recommendation is Electron's default_
By default, Electron will now allow websites loaded over `HTTPS` to load and
execute scripts, CSS, or plugins from insecure sources (`HTTP`). Setting the
property `allowRunningInsecureContent` to `true` disables that protection.
Loading the initial HTML of a website over `HTTPS` and attempting to load
subsequent resources via `HTTP` is also known as "mixed content".
### Why?
Simply put, loading content over `HTTPS` assures the authenticity and integrity
of the loaded resources while encrypting the traffic itself. See the section on
[only displaying secure content](#only-display-secure-content) for more details.
### How?
```js
// Bad
const mainWindow = new BrowserWindow({
webPreferences: {
allowRunningInsecureContent: true
}
})
```
```js
// Good
const mainWindow = new BrowserWindow({})
```
## 9) Do Not Enable Experimental Features
_Recommendation is Electron's default_
Advanced users of Electron can enable experimental Chromium features using the
`experimentalFeatures` and `experimentalCanvasFeatures` properties.
### Why?
Experimental features are, as the name suggests, experimental and have not been
enabled for all Chromium users. Furthermore, their impact on Electron as a whole
has likely not been tested.
Legitimate use cases exist, but unless you know what you are doing, you should
not enable this property.
### How?
```js
// Bad
const mainWindow = new BrowserWindow({
webPreferences: {
experimentalFeatures: true
}
})
```
```js
// Good
const mainWindow = new BrowserWindow({})
```
## 10) Do Not Use `blinkFeatures`
_Recommendation is Electron's default_
Blink is the name of the rendering engine behind Chromium. As with
`experimentalFeatures`, the `blinkFeatures` property allows developers to
enable features that have been disabled by default.
### Why?
Generally speaking, there are likely good reasons if a feature was not enabled
by default. Legitimate use cases for enabling specific features exist. As a
developer, you should know exactly why you need to enable a feature, what the
ramifications are, and how it impacts the security of your application. Under
no circumstances should you enable features speculatively.
### How?
```js
// Bad
const mainWindow = new BrowserWindow({
webPreferences: {
blinkFeatures: ['ExecCommandInJavaScript']
}
})
```
```js
// Good
const mainWindow = new BrowserWindow()
```
## 11) Do Not Use `allowpopups`
_Recommendation is Electron's default_
If you are using [`WebViews`][web-view], you might need the pages and scripts
loaded in your `<webview>` tag to open new windows. The `allowpopups` attribute
enables them to create new [`BrowserWindows`][browser-window] using the
`window.open()` method. `WebViews` are otherwise not allowed to create new
windows.
### Why?
If you do not need popups, you are better off not allowing the creation of
new [`BrowserWindows`][browser-window] by default. This follows the principle
of minimally required access: Don't let a website create new popups unless
you know it needs that feature.
### How?
```html
<!-- Bad -->
<webview allowpopups src="page.html"></webview>
<!-- Good -->
<webview src="page.html"></webview>
```
## 12) Verify WebView Options Before Creation
A WebView created in a renderer process that does not have Node.js integration
enabled will not be able to enable integration itself. However, a WebView will
always create an independent renderer process with its own `webPreferences`.
It is a good idea to control the creation of new [`WebViews`][web-view] from
the main process and to verify that their webPreferences do not disable
security features.
### Why?
Since WebViews live in the DOM, they can be created by a script running on your
website even if Node.js integration is otherwise disabled.
Electron enables developers to disable various security features that control
a renderer process. In most cases, developers do not need to disable any of
those features - and you should therefore not allow different configurations
for newly created [`<WebView>`][web-view] tags.
### How?
Before a [`<WebView>`][web-view] tag is attached, Electron will fire the
`will-attach-webview` event on the hosting `webContents`. Use the event to
prevent the creation of WebViews with possibly insecure options.
```js
app.on('web-contents-created', (event, contents) => {
@@ -87,7 +546,7 @@ app.on('web-contents-created', (event, contents) => {
delete webPreferences.preload
delete webPreferences.preloadURL
// Disable node integration
// Disable Node.js integration
webPreferences.nodeIntegration = false
// Verify URL being loaded
@@ -100,3 +559,7 @@ app.on('web-contents-created', (event, contents) => {
Again, this list merely minimizes the risk, it does not remove it. If your goal
is to display a website, a browser will be a more secure option.
[browser-window]: ../api/browser-window.md
[browser-view]: ../api/browser-view.md
[web-view]: ../api/web-view.md

184
docs/tutorial/snapcraft.md Normal file
View File

@@ -0,0 +1,184 @@
# Snapcraft Guide (Ubuntu Software Center & More)
This guide provides information on how to package your Electron application
for any Snapcraft environment, including the Ubuntu Software Center.
## Background and Requirements
Together with the broader Linux community, Canonical aims to fix many of the
common software installation problems with the [`snapcraft`](https://snapcraft.io/)
project. Snaps are containerized software packages that include required
dependencies, auto-update, and work on all major Linux distributions without
system modification.
There are three ways to create a `.snap` file:
1) Using [`electron-forge`][electron-forge] or
[`electron-builder`][electron-builder], both tools that come with `snap`
support out of the box. This is the easiest option.
2) Using `electron-installer-snap`, which takes `electron-packager`'s output.
3) Using an already created `.deb` package.
In all cases, you will need to have the `snapcraft` tool installed. We
recommend building on Ubuntu 16.04 (or the current LTS).
```sh
snap install snapcraft --classic
```
While it _is possible_ to install `snapcraft` on macOS using Homebrew, it
is not able to build `snap` packages and is focused on managing packages
in the store.
## Using `electron-installer-snap`
The module works like [`electron-winstaller`][electron-winstaller] and similar
modules in that its scope is limited to building snap packages. You can install
it with:
```sh
npm install --save-dev electron-installer-snap
```
### Step 1: Package Your Electron Application
Package the application using [electron-packager][electron-packager] (or a
similar tool). Make sure to remove `node_modules` that you don't need in your
final application, since any module you don't actually need will just increase
your application's size.
The output should look roughly like this:
```text
.
└── dist
└── app-linux-x64
├── LICENSE
├── LICENSES.chromium.html
├── content_shell.pak
├── app
├── icudtl.dat
├── libgcrypt.so.11
├── libnode.so
├── locales
├── natives_blob.bin
├── resources
├── snapshot_blob.bin
└── version
```
### Step 2: Running `electron-installer-snap`
From a terminal that has `snapcraft` in its `PATH`, run `electron-installer-snap`
with the only required parameter `--src`, which is the location of your packaged
Electron application created in the first step.
```sh
npx electron-installer-snap --src=out/myappname-linux-x64
```
If you have an existing build pipeline, you can use `electron-installer-snap`
programmatically. For more information, see the [Snapcraft API docs][snapcraft-syntax].
```js
const snap = require('electron-installer-snap')
snap(options)
.then(snapPath => console.log(`Created snap at ${snapPath}!`))
```
## Using an Existing Debian Package
Snapcraft is capable of taking an existing `.deb` file and turning it into
a `.snap` file. The creation of a snap is configured using a `snapcraft.yaml`
file that describes the sources, dependencies, description, and other core
building blocks.
### Step 1: Create a Debian Package
If you do not already have a `.deb` package, using `electron-installer-snap`
might be an easier path to create snap packages. However, multiple solutions
for creating Debian packages exist, including [`electron-forge`][electron-forge],
[`electron-builder`][electron-builder] or
[`electron-installer-debian`][electron-installer-debian].
### Step 2: Create a snapcraft.yaml
For more information on the available configuration options, see the
[documentation on the snapcraft syntax][snapcraft-syntax].
Let's look at an example:
```yaml
name: myApp
version: '2.0.0'
summary: A little description for the app.
description: |
You know what? This app is amazing! It does all the things
for you. Some say it keeps you young, maybe even happy.
grade: stable
confinement: classic
parts:
slack:
plugin: dump
source: my-deb.deb
source-type: deb
after:
- desktop-gtk3
stage-packages:
- libasound2
- libgconf2-4
- libnotify4
- libnspr4
- libnss3
- libpcre3
- libpulse0
- libxss1
- libxtst6
electron-launch:
plugin: dump
source: files/
prepare: |
chmod +x bin/electron-launch
apps:
myApp:
command: bin/electron-launch $SNAP/usr/lib/myApp/myApp
desktop: usr/share/applications/myApp.desktop
# Correct the TMPDIR path for Chromium Framework/Electron to ensure
# libappindicator has readable resources.
environment:
TMPDIR: $XDG_RUNTIME_DIR
```
As you can see, the `snapcraft.yaml` instructs the system to launch a file
called `electron-launch`. In this example, it simply passes information on
to the app's binary:
```sh
#!/bin/sh
exec "$@" --executed-from="$(pwd)" --pid=$$ > /dev/null 2>&1 &
```
Alternatively, if you're building your `snap` with `strict` confinement, you
can use the `desktop-launch` command:
```yaml
apps:
myApp:
# Correct the TMPDIR path for Chromium Framework/Electron to ensure
# libappindicator has readable resources.
command: env TMPDIR=$XDG_RUNTIME_DIR PATH=/usr/local/bin:${PATH} ${SNAP}/bin/desktop-launch $SNAP/myApp/desktop
desktop: usr/share/applications/desktop.desktop
```
[snapcraft.io]: https://snapcraft.io/
[snapcraft-store]: https://snapcraft.io/store/
[snapcraft-syntax]: https://docs.snapcraft.io/build-snaps/syntax
[electron-packager]: https://github.com/electron-userland/electron-packager
[electron-forge]: https://github.com/electron-userland/electron-forge
[electron-builder]: https://github.com/electron-userland/electron-builder
[electron-installer-debian]: https://github.com/unindented/electron-installer-debian
[electron-winstaller]: https://github.com/electron/windows-installer

View File

@@ -18,9 +18,13 @@ Please note, the `ARM` version of Windows is not supported for now.
### Linux
The prebuilt `ia32` (`i686`) and `x64` (`amd64`) binaries of Electron are built on
Ubuntu 12.04, the `arm` binary is built against ARM v7 with hard-float ABI and
Ubuntu 12.04, the `armv7l` binary is built against ARM v7 with hard-float ABI and
NEON for Debian Wheezy.
[Until the release of Electron 2.0][arm-breaking-change], Electron will also
continue to release the `armv7l` binary with a simple `arm` suffix. Both binaries
are identical.
Whether the prebuilt binary can run on a distribution depends on whether the
distribution includes the libraries that Electron is linked to on the building
platform, so only Ubuntu 12.04 is guaranteed to work, but following platforms
@@ -29,3 +33,5 @@ are also verified to be able to run the prebuilt binaries of Electron:
* Ubuntu 12.04 and later
* Fedora 21
* Debian 8
[arm-breaking-change]: https://github.com/electron/electron/blob/master/docs/tutorial/planned-breaking-changes.md#duplicate-arm-assets

View File

@@ -1,52 +1,54 @@
# Updating Applications
There are several ways to update an Electron application. The easiest and
officially supported one is taking advantage of the built-in
[Squirrel](https://github.com/Squirrel) framework and
There are several ways to update an Electron application. The easiest and
officially supported one is taking advantage of the built-in
[Squirrel](https://github.com/Squirrel) framework and
Electron's [autoUpdater](../api/auto-updater.md) module.
## Deploying an update server
## Deploying an Update Server
To get started, you first need to deploy a server that the
To get started, you first need to deploy a server that the
[autoUpdater](../api/auto-updater.md) module will download new updates from.
Depending on your needs, you can choose from one of these:
- [Hazel](https://github.com/zeit/hazel) Simple update server for open-source
apps. Pulls from
[GitHub Releases](https://help.github.com/articles/creating-releases/)
and can be deployed for free on [Now](https://zeit.co/now).
- [Nuts](https://github.com/GitbookIO/nuts) Also uses
[GitHub Releases](https://help.github.com/articles/creating-releases/),
but caches app updates on disk and supports private repositories.
- [electron-release-server](https://github.com/ArekSredzki/electron-release-server)
Provides a dashboard for handling releases
- [Nucleus](https://github.com/atlassian/nucleus) - A complete update server for Electron apps maintained by Atlassian. Supports multiple applications and channels; uses a static file store to minify server cost.
- [Hazel][hazel] Update server for private or open-source apps which can be
deployed for free on [Now][now]. It pulls from [GitHub Releases][gh-releases]
and leverages the power of GitHub's CDN.
- [Nuts][nuts] Also uses [GitHub Releases][gh-releases], but caches app
updates on disk and supports private repositories.
- [electron-release-server][electron-release-server] Provides a dashboard for
handling releases and does not require releases to originate on GitHub.
- [Nucleus][nucleus] A complete update server for Electron apps maintained by
Atlassian. Supports multiple applications and channels; uses a static file store
to minify server cost.
If your app is packaged with [electron-builder][electron-builder-lib] you can use the
[electron-updater] module, which does not require a server and allows for updates
from S3, GitHub or any other static file host.
If your app is packaged with [`electron-builder`][electron-builder-lib] you can use the
[electron-updater] module, which does not require a server and allows for updates
from S3, GitHub or any other static file host. This sidesteps Electron's built-in
update mechanism, meaning that the rest of this documentation will not apply to
`electron-builder`'s updater.
## Implementing updates in your app
## Implementing Updates in Your App
Once you've deployed your update server, continue with importing the required
modules in your code. The following code might vary for different server
software, but it works like described when using
Once you've deployed your update server, continue with importing the required
modules in your code. The following code might vary for different server
software, but it works like described when using
[Hazel](https://github.com/zeit/hazel).
**Important:** Please ensure that the code below will only be executed in
your packaged app, and not in development. You can use
[electron-is-dev](https://github.com/sindresorhus/electron-is-dev) to check for
**Important:** Please ensure that the code below will only be executed in
your packaged app, and not in development. You can use
[electron-is-dev](https://github.com/sindresorhus/electron-is-dev) to check for
the environment.
```js
const {app, autoUpdater, dialog} = require('electron')
```javascript
const { app, autoUpdater, dialog } = require('electron')
```
Next, construct the URL of the update server and tell
Next, construct the URL of the update server and tell
[autoUpdater](../api/auto-updater.md) about it:
```js
```javascript
const server = 'https://your-deployment-url.com'
const feed = `${server}/update/${process.platform}/${app.getVersion()}`
@@ -55,25 +57,25 @@ autoUpdater.setFeedURL(feed)
As the final step, check for updates. The example below will check every minute:
```js
```javascript
setInterval(() => {
autoUpdater.checkForUpdates()
}, 60000)
```
Once your application is [packaged](../tutorial/application-distribution.md),
it will receive an update for each new
[GitHub Release](https://help.github.com/articles/creating-releases/) that you
Once your application is [packaged](../tutorial/application-distribution.md),
it will receive an update for each new
[GitHub Release](https://help.github.com/articles/creating-releases/) that you
publish.
## Applying updates
## Applying Updates
Now that you've configured the basic update mechanism for your application, you
Now that you've configured the basic update mechanism for your application, you
need to ensure that the user will get notified when there's an update. This
can be achieved using the autoUpdater API
can be achieved using the autoUpdater API
[events](../api/auto-updater.md#events):
```js
```javascript
autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName) => {
const dialogOpts = {
type: 'info',
@@ -89,11 +91,11 @@ autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName) => {
})
```
Also make sure that errors are
Also make sure that errors are
[being handled](../api/auto-updater.md#event-error). Here's an example
for logging them to `stderr`:
```js
```javascript
autoUpdater.on('error', message => {
console.error('There was a problem updating the application')
console.error(message)
@@ -102,3 +104,9 @@ autoUpdater.on('error', message => {
[electron-builder-lib]: https://github.com/electron-userland/electron-builder
[electron-updater]: https://www.electron.build/auto-update
[now]: https://zeit.co/now
[hazel]: https://github.com/zeit/hazel
[nuts]: https://github.com/GitbookIO/nuts
[gh-releases]: https://help.github.com/articles/creating-releases/
[electron-release-server]: https://github.com/ArekSredzki/electron-release-server
[nucleus]: https://github.com/atlassian/nucleus

View File

@@ -63,7 +63,7 @@ the plugins yourself, its path can be received by calling
Add `plugins` attribute to `<webview>` tag.
```html
<webview src="http://www.adobe.com/software/flash/about/" plugins></webview>
<webview src="https://www.adobe.com/software/flash/about/" plugins></webview>
```
## Troubleshooting

View File

@@ -169,4 +169,4 @@ your app's folder. This eliminates the need to copy-paste your app into
Electron's resource directory.
[chrome-driver]: https://sites.google.com/a/chromium.org/chromedriver/
[spectron]: https://electron.atom.io/spectron
[spectron]: https://electronjs.org/spectron

View File

@@ -151,7 +151,7 @@ You will receive two files: `DesktopAppConverter.zip` and `BaseImage-14316.wim`.
Once installation succeeded, you can move on to compiling your Electron app.
[windows-sdk]: https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk
[app-converter]: https://www.microsoft.com/en-us/download/details.aspx?id=51691
[app-converter]: https://docs.microsoft.com/en-us/windows/uwp/porting/desktop-to-uwp-run-desktop-app-converter
[add-appxpackage]: https://technet.microsoft.com/en-us/library/hh856048.aspx
[electron-packager]: https://github.com/electron-userland/electron-packager
[electron-windows-store]: https://github.com/catalystcode/electron-windows-store

View File

@@ -0,0 +1,185 @@
# Windows Taskbar
Electron has APIs to configure the app's icon in the Windows taskbar. Supported
are the [creation of a `JumpList`](#jumplist),
[custom thumbnails and toolbars](#thumbnail-toolbars),
[icon overlays](#icon-overlays-in-taskbar-windows), and the so-called
["Flash Frame" effect](#flash-frame), but
Electron also uses the app's dock icon to implement cross-platform features
like [recent documents][recent-documents] and
[application progress][progress-bar].
## JumpList
Windows allows apps to define a custom context menu that shows up when users
right-click the app's icon in the task bar. That context menu is called
`JumpList`. You specify custom actions in the `Tasks` category of JumpList,
as quoted from MSDN:
> Applications define tasks based on both the program's features and the key
> things a user is expected to do with them. Tasks should be context-free, in
> that the application does not need to be running for them to work. They
> should also be the statistically most common actions that a normal user would
> perform in an application, such as compose an email message or open the
> calendar in a mail program, create a new document in a word processor, launch
> an application in a certain mode, or launch one of its subcommands. An
> application should not clutter the menu with advanced features that standard
> users won't need or one-time actions such as registration. Do not use tasks
> for promotional items such as upgrades or special offers.
>
> It is strongly recommended that the task list be static. It should remain the
> same regardless of the state or status of the application. While it is
> possible to vary the list dynamically, you should consider that this could
> confuse the user who does not expect that portion of the destination list to
> change.
__Tasks of Internet Explorer:__
![IE](http://i.msdn.microsoft.com/dynimg/IC420539.png)
Unlike the dock menu in macOS which is a real menu, user tasks in Windows work
like application shortcuts such that when user clicks a task, a program will be
executed with specified arguments.
To set user tasks for your application, you can use
[app.setUserTasks][setusertaskstasks] API:
```javascript
const { app } = require('electron')
app.setUserTasks([
{
program: process.execPath,
arguments: '--new-window',
iconPath: process.execPath,
iconIndex: 0,
title: 'New Window',
description: 'Create a new window'
}
])
```
To clean your tasks list, just call `app.setUserTasks` with an empty array:
```javascript
const { app } = require('electron')
app.setUserTasks([])
```
The user tasks will still show even after your application closes, so the icon
and program path specified for a task should exist until your application is
uninstalled.
## Thumbnail Toolbars
On Windows you can add a thumbnail toolbar with specified buttons in a taskbar
layout of an application window. It provides users a way to access to a
particular window's command without restoring or activating the window.
From MSDN, it's illustrated:
> This toolbar is simply the familiar standard toolbar common control. It has a
> maximum of seven buttons. Each button's ID, image, tooltip, and state are defined
> in a structure, which is then passed to the taskbar. The application can show,
> enable, disable, or hide buttons from the thumbnail toolbar as required by its
> current state.
>
> For example, Windows Media Player might offer standard media transport controls
> such as play, pause, mute, and stop.
__Thumbnail toolbar of Windows Media Player:__
![player](https://i-msdn.sec.s-msft.com/dynimg/IC420540.png)
You can use [BrowserWindow.setThumbarButtons][setthumbarbuttons] to set
thumbnail toolbar in your application:
```javascript
const { BrowserWindow } = require('electron')
const path = require('path')
const win = new BrowserWindow()
win.setThumbarButtons([
{
tooltip: 'button1',
icon: path.join(__dirname, 'button1.png'),
click () { console.log('button1 clicked') }
}, {
tooltip: 'button2',
icon: path.join(__dirname, 'button2.png'),
flags: ['enabled', 'dismissonclick'],
click () { console.log('button2 clicked.') }
}
])
```
To clean thumbnail toolbar buttons, just call `BrowserWindow.setThumbarButtons`
with an empty array:
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.setThumbarButtons([])
```
## Icon Overlays in Taskbar
On Windows a taskbar button can use a small overlay to display application
status, as quoted from MSDN:
> Icon overlays serve as a contextual notification of status, and are intended
> to negate the need for a separate notification area status icon to communicate
> that information to the user. For instance, the new mail status in Microsoft
> Outlook, currently shown in the notification area, can now be indicated
> through an overlay on the taskbar button. Again, you must decide during your
> development cycle which method is best for your application. Overlay icons are
> intended to supply important, long-standing status or notifications such as
> network status, messenger status, or new mail. The user should not be
> presented with constantly changing overlays or animations.
__Overlay on taskbar button:__
![Overlay on taskbar button](https://i-msdn.sec.s-msft.com/dynimg/IC420441.png)
To set the overlay icon for a window, you can use the
[BrowserWindow.setOverlayIcon][setoverlayicon] API:
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.setOverlayIcon('path/to/overlay.png', 'Description for overlay')
```
## Flash Frame
On Windows you can highlight the taskbar button to get the user's attention.
This is similar to bouncing the dock icon on macOS.
From the MSDN reference documentation:
> Typically, a window is flashed to inform the user that the window requires
> attention but that it does not currently have the keyboard focus.
To flash the BrowserWindow taskbar button, you can use the
[BrowserWindow.flashFrame][flashframe] API:
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.once('focus', () => win.flashFrame(false))
win.flashFrame(true)
```
Don't forget to call the `flashFrame` method with `false` to turn off the flash. In
the above example, it is called when the window comes into focus, but you might
use a timeout or some other event to disable it.
[setthumbarbuttons]: ../api/browser-window.md#winsetthumbarbuttonsbuttons-windows
[setusertaskstasks]: ../api/app.md#appsetusertaskstasks-windows
[setoverlayicon]: ../api/browser-window.md#winsetoverlayiconoverlay-description-windows
[flashframe]: ../api/browser-window.md#winflashframeflag
[recent-documents]: ./recent-documents.md
[progress-bar]: ./progress-bar.md