This commit is contained in:
Samuel Attard 2018-09-14 02:10:51 +10:00
Родитель 9e85bdb02c
Коммит 558fff69e7
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: E89DDE5742D58C4E
198 изменённых файлов: 4455 добавлений и 2940 удалений

Просмотреть файл

@ -1,4 +1,4 @@
const {app, BrowserWindow} = require('electron') const { app, BrowserWindow } = require('electron')
const path = require('path') const path = require('path')
let mainWindow = null let mainWindow = null

Просмотреть файл

@ -1,4 +1,4 @@
const {app, dialog, shell, Menu} = require('electron') const { app, dialog, shell, Menu } = require('electron')
const fs = require('fs') const fs = require('fs')
const Module = require('module') const Module = require('module')

Просмотреть файл

@ -1,4 +1,4 @@
const {remote, shell} = require('electron') const { remote, shell } = require('electron')
const fs = require('fs') const fs = require('fs')
const path = require('path') const path = require('path')
const URL = require('url') const URL = require('url')
@ -7,7 +7,7 @@ const electronPath = path.relative(process.cwd(), remote.process.execPath)
Array.from(document.querySelectorAll('a[href]')).forEach(link => { Array.from(document.querySelectorAll('a[href]')).forEach(link => {
// safely add `?utm_source=default_app // safely add `?utm_source=default_app
let url = URL.parse(link.getAttribute('href'), true) let url = URL.parse(link.getAttribute('href'), true)
url.query = Object.assign(url.query, {utm_source: 'default_app'}) url.query = Object.assign(url.query, { utm_source: 'default_app' })
url = URL.format(url) url = URL.format(url)
link.addEventListener('click', (e) => { link.addEventListener('click', (e) => {

Просмотреть файл

@ -16,7 +16,7 @@ using the [`register`](global-shortcut.md#globalshortcutregisteraccelerator-call
method, i.e. method, i.e.
```javascript ```javascript
const {app, globalShortcut} = require('electron') const { app, globalShortcut } = require('electron')
app.on('ready', () => { app.on('ready', () => {
// Register a 'CommandOrControl+Y' shortcut listener. // Register a 'CommandOrControl+Y' shortcut listener.

Просмотреть файл

@ -8,7 +8,7 @@ The following example shows how to quit the application when the last window is
closed: closed:
```javascript ```javascript
const {app} = require('electron') const { app } = require('electron')
app.on('window-all-closed', () => { app.on('window-all-closed', () => {
app.quit() app.quit()
}) })
@ -268,7 +268,7 @@ certificate you should prevent the default behavior with
`event.preventDefault()` and call `callback(true)`. `event.preventDefault()` and call `callback(true)`.
```javascript ```javascript
const {app} = require('electron') const { app } = require('electron')
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => { app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
if (url === 'https://github.com') { if (url === 'https://github.com') {
@ -300,7 +300,7 @@ and `callback` can be called with an entry filtered from the list. Using
certificate from the store. certificate from the store.
```javascript ```javascript
const {app} = require('electron') const { app } = require('electron')
app.on('select-client-certificate', (event, webContents, url, list, callback) => { app.on('select-client-certificate', (event, webContents, url, list, callback) => {
event.preventDefault() event.preventDefault()
@ -335,7 +335,7 @@ should prevent the default behavior with `event.preventDefault()` and call
`callback(username, password)` with the credentials. `callback(username, password)` with the credentials.
```javascript ```javascript
const {app} = require('electron') const { app } = require('electron')
app.on('login', (event, webContents, request, authInfo, callback) => { app.on('login', (event, webContents, request, authInfo, callback) => {
event.preventDefault() event.preventDefault()
@ -375,7 +375,7 @@ Returns:
Emitted when Electron has created a new `session`. Emitted when Electron has created a new `session`.
```javascript ```javascript
const {app} = require('electron') const { app } = require('electron')
app.on('session-created', (event, session) => { app.on('session-created', (event, session) => {
console.log(session) console.log(session)
@ -448,9 +448,9 @@ An example of restarting current instance immediately and adding a new command
line argument to the new instance: line argument to the new instance:
```javascript ```javascript
const {app} = require('electron') const { app } = require('electron')
app.relaunch({args: process.argv.slice(1).concat(['--relaunch'])}) app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) })
app.exit(0) app.exit(0)
``` ```
@ -712,7 +712,7 @@ items can be obtained using `app.getJumpListSettings()`.
Here's a very simple example of creating a custom Jump List: Here's a very simple example of creating a custom Jump List:
```javascript ```javascript
const {app} = require('electron') const { app } = require('electron')
app.setJumpList([ app.setJumpList([
{ {
@ -798,7 +798,7 @@ An example of activating the window of primary instance when a second instance
starts: starts:
```javascript ```javascript
const {app} = require('electron') const { app } = require('electron')
let myWindow = null let myWindow = null
const gotTheLock = app.requestSingleInstanceLock() const gotTheLock = app.requestSingleInstanceLock()

Просмотреть файл

@ -49,17 +49,17 @@ app.getAppMetrics()
// Deprecated // Deprecated
const metrics = app.getAppMetrics() const metrics = app.getAppMetrics()
const {memory} = metrics[0] // Deprecated property const { memory } = metrics[0] // Deprecated property
``` ```
## `BrowserWindow` ## `BrowserWindow`
```js ```js
// Deprecated // Deprecated
let optionsA = {webPreferences: {blinkFeatures: ''}} let optionsA = { webPreferences: { blinkFeatures: '' } }
let windowA = new BrowserWindow(optionsA) let windowA = new BrowserWindow(optionsA)
// Replace with // Replace with
let optionsB = {webPreferences: {enableBlinkFeatures: ''}} let optionsB = { webPreferences: { enableBlinkFeatures: '' } }
let windowB = new BrowserWindow(optionsB) let windowB = new BrowserWindow(optionsB)
// Deprecated // Deprecated
@ -175,9 +175,9 @@ tray.setHighlightMode('off')
```js ```js
// Deprecated // Deprecated
webContents.openDevTools({detach: true}) webContents.openDevTools({ detach: true })
// Replace with // Replace with
webContents.openDevTools({mode: 'detach'}) webContents.openDevTools({ mode: 'detach' })
// Removed // Removed
webContents.setSize(options) webContents.setSize(options)
@ -190,12 +190,12 @@ webContents.setSize(options)
// Deprecated // Deprecated
webFrame.registerURLSchemeAsSecure('app') webFrame.registerURLSchemeAsSecure('app')
// Replace with // Replace with
protocol.registerStandardSchemes(['app'], {secure: true}) protocol.registerStandardSchemes(['app'], { secure: true })
// Deprecated // Deprecated
webFrame.registerURLSchemeAsPrivileged('app', {secure: true}) webFrame.registerURLSchemeAsPrivileged('app', { secure: true })
// Replace with // Replace with
protocol.registerStandardSchemes(['app'], {secure: true}) protocol.registerStandardSchemes(['app'], { secure: true })
``` ```
## `<webview>` ## `<webview>`
@ -232,10 +232,10 @@ The following list includes the breaking API changes made in Electron 2.0.
```js ```js
// Deprecated // Deprecated
let optionsA = {titleBarStyle: 'hidden-inset'} let optionsA = { titleBarStyle: 'hidden-inset' }
let windowA = new BrowserWindow(optionsA) let windowA = new BrowserWindow(optionsA)
// Replace with // Replace with
let optionsB = {titleBarStyle: 'hiddenInset'} let optionsB = { titleBarStyle: 'hiddenInset' }
let windowB = new BrowserWindow(optionsB) let windowB = new BrowserWindow(optionsB)
``` ```
@ -245,7 +245,7 @@ let windowB = new BrowserWindow(optionsB)
// Removed // Removed
menu.popup(browserWindow, 100, 200, 2) menu.popup(browserWindow, 100, 200, 2)
// Replaced with // Replaced with
menu.popup(browserWindow, {x: 100, y: 200, positioningItem: 2}) menu.popup(browserWindow, { x: 100, y: 200, positioningItem: 2 })
``` ```
## `nativeImage` ## `nativeImage`

Просмотреть файл

@ -16,9 +16,9 @@ relative to its owning window. It is meant to be an alternative to the
```javascript ```javascript
// In the main process. // In the main process.
const {BrowserView, BrowserWindow} = require('electron') const { BrowserView, BrowserWindow } = require('electron')
let win = new BrowserWindow({width: 800, height: 600}) let win = new BrowserWindow({ width: 800, height: 600 })
win.on('closed', () => { win.on('closed', () => {
win = null win = null
}) })

Просмотреть файл

@ -6,12 +6,12 @@ Process: [Main](../glossary.md#main-process)
```javascript ```javascript
// In the main process. // In the main process.
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
// Or use `remote` from the renderer process. // Or use `remote` from the renderer process.
// const {BrowserWindow} = require('electron').remote // const { BrowserWindow } = require('electron').remote
let win = new BrowserWindow({width: 800, height: 600}) let win = new BrowserWindow({ width: 800, height: 600 })
win.on('closed', () => { win.on('closed', () => {
win = null win = null
}) })
@ -40,8 +40,8 @@ process has rendered the page for the first time if the window has not been show
the window after this event will have no visual flash: the window after this event will have no visual flash:
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow({show: false}) let win = new BrowserWindow({ show: false })
win.once('ready-to-show', () => { win.once('ready-to-show', () => {
win.show() win.show()
}) })
@ -58,9 +58,9 @@ the app feel slow. In this case, it is recommended to show the window
immediately, and use a `backgroundColor` close to your app's background: immediately, and use a `backgroundColor` close to your app's background:
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow({backgroundColor: '#2e2c29'}) let win = new BrowserWindow({ backgroundColor: '#2e2c29' })
win.loadURL('https://github.com') win.loadURL('https://github.com')
``` ```
@ -72,10 +72,10 @@ to set `backgroundColor` to make app feel more native.
By using `parent` option, you can create child windows: By using `parent` option, you can create child windows:
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let top = new BrowserWindow() let top = new BrowserWindow()
let child = new BrowserWindow({parent: top}) let child = new BrowserWindow({ parent: top })
child.show() child.show()
top.show() top.show()
``` ```
@ -88,9 +88,9 @@ A modal window is a child window that disables parent window, to create a modal
window, you have to set both `parent` and `modal` options: window, you have to set both `parent` and `modal` options:
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let child = new BrowserWindow({parent: top, modal: true, show: false}) let child = new BrowserWindow({ parent: top, modal: true, show: false })
child.loadURL('https://github.com') child.loadURL('https://github.com')
child.once('ready-to-show', () => { child.once('ready-to-show', () => {
child.show() child.show()
@ -558,7 +558,7 @@ Commands are lowercased, underscores are replaced with hyphens, and the
e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`. e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`.
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow() let win = new BrowserWindow()
win.on('app-command', (e, cmd) => { win.on('app-command', (e, cmd) => {
// Navigate the window back when the user hits their mouse back button // Navigate the window back when the user hits their mouse back button
@ -692,7 +692,7 @@ an Object containing `name` and `version` properties.
To check if a DevTools extension is installed you can run the following: To check if a DevTools extension is installed you can run the following:
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let installed = BrowserWindow.getDevToolsExtensions().hasOwnProperty('devtron') let installed = BrowserWindow.getDevToolsExtensions().hasOwnProperty('devtron')
console.log(installed) console.log(installed)
@ -706,9 +706,9 @@ is emitted.
Objects created with `new BrowserWindow` have the following properties: Objects created with `new BrowserWindow` have the following properties:
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
// In this example `win` is our instance // In this example `win` is our instance
let win = new BrowserWindow({width: 800, height: 600}) let win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com') win.loadURL('https://github.com')
``` ```
@ -1085,7 +1085,7 @@ attached just below the window frame, but you may want to display them beneath
a HTML-rendered toolbar. For example: a HTML-rendered toolbar. For example:
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow() let win = new BrowserWindow()
let toolbarRect = document.getElementById('toolbar').getBoundingClientRect() let toolbarRect = document.getElementById('toolbar').getBoundingClientRect()
@ -1354,7 +1354,7 @@ The `flags` is an array that can include following `String`s:
Sets the region of the window to show as the thumbnail image displayed when Sets the region of the window to show as the thumbnail image displayed when
hovering over the window in the taskbar. You can reset the thumbnail to be hovering over the window in the taskbar. You can reset the thumbnail to be
the entire window by specifying an empty region: the entire window by specifying an empty region:
`{x: 0, y: 0, width: 0, height: 0}`. `{ x: 0, y: 0, width: 0, height: 0 }`.
#### `win.setThumbnailToolTip(toolTip)` _Windows_ #### `win.setThumbnailToolTip(toolTip)` _Windows_

Просмотреть файл

@ -7,7 +7,7 @@ your app's main script before the [ready][ready] event of the [app][app] module
is emitted: is emitted:
```javascript ```javascript
const {app} = require('electron') const { app } = require('electron')
app.commandLine.appendSwitch('remote-debugging-port', '8315') app.commandLine.appendSwitch('remote-debugging-port', '8315')
app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1') app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1')
@ -72,7 +72,7 @@ list of hosts. This flag has an effect only if used in tandem with
For example: For example:
```javascript ```javascript
const {app} = require('electron') const { app } = require('electron')
app.commandLine.appendSwitch('proxy-bypass-list', '<local>;*.google.com;*foo.com;1.2.3.4:5678') app.commandLine.appendSwitch('proxy-bypass-list', '<local>;*.google.com;*foo.com;1.2.3.4:5678')
``` ```

Просмотреть файл

@ -7,7 +7,7 @@ Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer
The following example shows how to write a string to the clipboard: The following example shows how to write a string to the clipboard:
```javascript ```javascript
const {clipboard} = require('electron') const { clipboard } = require('electron')
clipboard.writeText('Example String') clipboard.writeText('Example String')
``` ```
@ -15,7 +15,7 @@ On X Window systems, there is also a selection clipboard. To manipulate it
you need to pass `selection` to each method: you need to pass `selection` to each method:
```javascript ```javascript
const {clipboard} = require('electron') const { clipboard } = require('electron')
clipboard.writeText('Example String', 'selection') clipboard.writeText('Example String', 'selection')
console.log(clipboard.readText('selection')) console.log(clipboard.readText('selection'))
``` ```
@ -141,7 +141,7 @@ Returns `String[]` - An array of supported formats for the clipboard `type`.
Returns `Boolean` - Whether the clipboard supports the specified `format`. Returns `Boolean` - Whether the clipboard supports the specified `format`.
```javascript ```javascript
const {clipboard} = require('electron') const { clipboard } = require('electron')
console.log(clipboard.has('<p>selection</p>')) console.log(clipboard.has('<p>selection</p>'))
``` ```
@ -176,7 +176,7 @@ Writes the `buffer` into the clipboard as `format`.
* `type` String (optional) * `type` String (optional)
```javascript ```javascript
const {clipboard} = require('electron') const { clipboard } = require('electron')
clipboard.write({text: 'test', html: '<b>test</b>'}) clipboard.write({ text: 'test', html: '<b>test</b>' })
``` ```
Writes `data` to the clipboard. Writes `data` to the clipboard.

Просмотреть файл

@ -14,7 +14,7 @@ module is emitted.
```javascript ```javascript
const {app, contentTracing} = require('electron') const { app, contentTracing } = require('electron')
app.on('ready', () => { app.on('ready', () => {
const options = { const options = {

Просмотреть файл

@ -10,7 +10,7 @@ a `Session`.
For example: For example:
```javascript ```javascript
const {session} = require('electron') const { session } = require('electron')
// Query all cookies. // Query all cookies.
session.defaultSession.cookies.get({}, (error, cookies) => { session.defaultSession.cookies.get({}, (error, cookies) => {
@ -18,13 +18,13 @@ session.defaultSession.cookies.get({}, (error, cookies) => {
}) })
// Query all cookies associated with a specific url. // Query all cookies associated with a specific url.
session.defaultSession.cookies.get({url: 'http://www.github.com'}, (error, cookies) => { session.defaultSession.cookies.get({ url: 'http://www.github.com' }, (error, cookies) => {
console.log(error, cookies) console.log(error, cookies)
}) })
// Set a cookie with the given cookie data; // Set a cookie with the given cookie data;
// may overwrite equivalent cookies if they exist. // may overwrite equivalent cookies if they exist.
const cookie = {url: 'http://www.github.com', name: 'dummy_name', value: 'dummy'} const cookie = { url: 'http://www.github.com', name: 'dummy_name', value: 'dummy' }
session.defaultSession.cookies.set(cookie, (error) => { session.defaultSession.cookies.set(cookie, (error) => {
if (error) console.error(error) if (error) console.error(error)
}) })

Просмотреть файл

@ -8,7 +8,7 @@ The following is an example of automatically submitting a crash report to a
remote server: remote server:
```javascript ```javascript
const {crashReporter} = require('electron') const { crashReporter } = require('electron')
crashReporter.start({ crashReporter.start({
productName: 'YourName', productName: 'YourName',
@ -71,18 +71,18 @@ first call `start` you can call `addExtraParameter` on macOS or call `start`
again with the new/updated `extra` parameters on Linux and Windows. again with the new/updated `extra` parameters on Linux and Windows.
```js ```js
const args = [ const args = [
`--reporter-url=${submitURL}`, `--reporter-url=${submitURL}`,
`--application-name=${productName}`, `--application-name=${productName}`,
`--crashes-directory=${crashesDirectory}` `--crashes-directory=${crashesDirectory}`
] ]
const env = { const env = {
ELECTRON_INTERNAL_CRASH_SERVICE: 1 ELECTRON_INTERNAL_CRASH_SERVICE: 1
} }
spawn(process.execPath, args, { spawn(process.execPath, args, {
env: env, env: env,
detached: true detached: true
}) })
``` ```
**Note:** On macOS, Electron uses a new `crashpad` client for crash collection and reporting. **Note:** On macOS, Electron uses a new `crashpad` client for crash collection and reporting.

Просмотреть файл

@ -8,7 +8,7 @@ Chrome Developer Tools has a [special binding][rdp] available at JavaScript
runtime that allows interacting with pages and instrumenting them. runtime that allows interacting with pages and instrumenting them.
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow() let win = new BrowserWindow()
try { try {

Просмотреть файл

@ -10,9 +10,9 @@ title is `Electron`:
```javascript ```javascript
// In the renderer process. // In the renderer process.
const {desktopCapturer} = require('electron') const { desktopCapturer } = require('electron')
desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => { desktopCapturer.getSources({ types: ['window', 'screen'] }, (error, sources) => {
if (error) throw error if (error) throw error
for (let i = 0; i < sources.length; ++i) { for (let i = 0; i < sources.length; ++i) {
if (sources[i].name === 'Electron') { if (sources[i].name === 'Electron') {
@ -28,9 +28,8 @@ desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
maxHeight: 720 maxHeight: 720
} }
} }
}) }).then((stream) => handleStream(stream))
.then((stream) => handleStream(stream)) .catch((e) => handleError(e))
.catch((e) => handleError(e))
return return
} }
} }

Просмотреть файл

@ -7,15 +7,15 @@ Process: [Main](../glossary.md#main-process)
An example of showing a dialog to select multiple files and directories: An example of showing a dialog to select multiple files and directories:
```javascript ```javascript
const {dialog} = require('electron') const { dialog } = require('electron')
console.log(dialog.showOpenDialog({properties: ['openFile', 'openDirectory', 'multiSelections']})) console.log(dialog.showOpenDialog({ properties: ['openFile', 'openDirectory', 'multiSelections'] }))
``` ```
The Dialog is opened from Electron's main thread. If you want to use the dialog The Dialog is opened from Electron's main thread. If you want to use the dialog
object from a renderer process, remember to access it using the remote: object from a renderer process, remember to access it using the remote:
```javascript ```javascript
const {dialog} = require('electron').remote const { dialog } = require('electron').remote
console.log(dialog) console.log(dialog)
``` ```
@ -66,10 +66,10 @@ selected when you want to limit the user to a specific type. For example:
```javascript ```javascript
{ {
filters: [ filters: [
{name: 'Images', extensions: ['jpg', 'png', 'gif']}, { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
{name: 'Movies', extensions: ['mkv', 'avi', 'mp4']}, { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
{name: 'Custom File Type', extensions: ['as']}, { name: 'Custom File Type', extensions: ['as'] },
{name: 'All Files', extensions: ['*']} { name: 'All Files', extensions: ['*'] }
] ]
} }
``` ```

Просмотреть файл

@ -10,7 +10,7 @@ control the download item.
```javascript ```javascript
// In the main process. // In the main process.
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow() let win = new BrowserWindow()
win.webContents.session.on('will-download', (event, item, webContents) => { win.webContents.session.on('will-download', (event, item, webContents) => {
// Set the save path, making Electron not to prompt a save dialog. // Set the save path, making Electron not to prompt a save dialog.

Просмотреть файл

@ -14,8 +14,8 @@ To create a frameless window, you need to set `frame` to `false` in
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow({width: 800, height: 600, frame: false}) let win = new BrowserWindow({ width: 800, height: 600, frame: false })
win.show() win.show()
``` ```
@ -33,8 +33,8 @@ You can do so by specifying the `titleBarStyle` option:
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. 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.
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow({titleBarStyle: 'hidden'}) let win = new BrowserWindow({ titleBarStyle: 'hidden' })
win.show() win.show()
``` ```
@ -43,8 +43,8 @@ win.show()
Results in a hidden title bar with an alternative look where the traffic light buttons are slightly more inset from the window edge. Results in a hidden title bar with an alternative look where the traffic light buttons are slightly more inset from the window edge.
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow({titleBarStyle: 'hiddenInset'}) let win = new BrowserWindow({ titleBarStyle: 'hiddenInset' })
win.show() win.show()
``` ```
@ -56,8 +56,8 @@ with mouse events that occur with the standard window toolbar buttons. This
option is only applicable for frameless windows. option is only applicable for frameless windows.
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow({titleBarStyle: 'customButtonsOnHover', frame: false}) let win = new BrowserWindow({ titleBarStyle: 'customButtonsOnHover', frame: false })
win.show() win.show()
``` ```
@ -67,8 +67,8 @@ By setting the `transparent` option to `true`, you can also make the frameless
window transparent: window transparent:
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow({transparent: true, frame: false}) let win = new BrowserWindow({ transparent: true, frame: false })
win.show() win.show()
``` ```
@ -98,7 +98,7 @@ events, you can call the [win.setIgnoreMouseEvents(ignore)][ignore-mouse-events]
API: API:
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow() let win = new BrowserWindow()
win.setIgnoreMouseEvents(true) win.setIgnoreMouseEvents(true)
``` ```
@ -114,7 +114,7 @@ allowing events such as `mouseleave` to be emitted:
let win = require('electron').remote.getCurrentWindow() let win = require('electron').remote.getCurrentWindow()
let el = document.getElementById('clickThroughElement') let el = document.getElementById('clickThroughElement')
el.addEventListener('mouseenter', () => { el.addEventListener('mouseenter', () => {
win.setIgnoreMouseEvents(true, {forward: true}) win.setIgnoreMouseEvents(true, { forward: true })
}) })
el.addEventListener('mouseleave', () => { el.addEventListener('mouseleave', () => {
win.setIgnoreMouseEvents(false) win.setIgnoreMouseEvents(false)

Просмотреть файл

@ -13,7 +13,7 @@ not have the keyboard focus. You should not use this module until the `ready`
event of the app module is emitted. event of the app module is emitted.
```javascript ```javascript
const {app, globalShortcut} = require('electron') const { app, globalShortcut } = require('electron')
app.on('ready', () => { app.on('ready', () => {
// Register a 'CommandOrControl+X' shortcut listener. // Register a 'CommandOrControl+X' shortcut listener.

Просмотреть файл

@ -25,7 +25,7 @@ processes:
```javascript ```javascript
// In main process. // In main process.
const {ipcMain} = require('electron') const { ipcMain } = require('electron')
ipcMain.on('asynchronous-message', (event, arg) => { ipcMain.on('asynchronous-message', (event, arg) => {
console.log(arg) // prints "ping" console.log(arg) // prints "ping"
event.sender.send('asynchronous-reply', 'pong') event.sender.send('asynchronous-reply', 'pong')
@ -39,7 +39,7 @@ ipcMain.on('synchronous-message', (event, arg) => {
```javascript ```javascript
// In renderer process (web page). // In renderer process (web page).
const {ipcRenderer} = require('electron') const { ipcRenderer } = require('electron')
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // prints "pong" console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // prints "pong"
ipcRenderer.on('asynchronous-reply', (event, arg) => { ipcRenderer.on('asynchronous-reply', (event, arg) => {

Просмотреть файл

@ -149,42 +149,42 @@ An example of creating the application menu in the main process with the
simple template API: simple template API:
```javascript ```javascript
const {app, Menu} = require('electron') const { app, Menu } = require('electron')
const template = [ const template = [
{ {
label: 'Edit', label: 'Edit',
submenu: [ submenu: [
{role: 'undo'}, { role: 'undo' },
{role: 'redo'}, { role: 'redo' },
{type: 'separator'}, { type: 'separator' },
{role: 'cut'}, { role: 'cut' },
{role: 'copy'}, { role: 'copy' },
{role: 'paste'}, { role: 'paste' },
{role: 'pasteandmatchstyle'}, { role: 'pasteandmatchstyle' },
{role: 'delete'}, { role: 'delete' },
{role: 'selectall'} { role: 'selectall' }
] ]
}, },
{ {
label: 'View', label: 'View',
submenu: [ submenu: [
{role: 'reload'}, { role: 'reload' },
{role: 'forcereload'}, { role: 'forcereload' },
{role: 'toggledevtools'}, { role: 'toggledevtools' },
{type: 'separator'}, { type: 'separator' },
{role: 'resetzoom'}, { role: 'resetzoom' },
{role: 'zoomin'}, { role: 'zoomin' },
{role: 'zoomout'}, { role: 'zoomout' },
{type: 'separator'}, { type: 'separator' },
{role: 'togglefullscreen'} { role: 'togglefullscreen' }
] ]
}, },
{ {
role: 'window', role: 'window',
submenu: [ submenu: [
{role: 'minimize'}, { role: 'minimize' },
{role: 'close'} { role: 'close' }
] ]
}, },
{ {
@ -202,37 +202,37 @@ if (process.platform === 'darwin') {
template.unshift({ template.unshift({
label: app.getName(), label: app.getName(),
submenu: [ submenu: [
{role: 'about'}, { role: 'about' },
{type: 'separator'}, { type: 'separator' },
{role: 'services', submenu: []}, { role: 'services', submenu: [] },
{type: 'separator'}, { type: 'separator' },
{role: 'hide'}, { role: 'hide' },
{role: 'hideothers'}, { role: 'hideothers' },
{role: 'unhide'}, { role: 'unhide' },
{type: 'separator'}, { type: 'separator' },
{role: 'quit'} { role: 'quit' }
] ]
}) })
// Edit menu // Edit menu
template[1].submenu.push( template[1].submenu.push(
{type: 'separator'}, { type: 'separator' },
{ {
label: 'Speech', label: 'Speech',
submenu: [ submenu: [
{role: 'startspeaking'}, { role: 'startspeaking' },
{role: 'stopspeaking'} { role: 'stopspeaking' }
] ]
} }
) )
// Window menu // Window menu
template[3].submenu = [ template[3].submenu = [
{role: 'close'}, { role: 'close' },
{role: 'minimize'}, { role: 'minimize' },
{role: 'zoom'}, { role: 'zoom' },
{type: 'separator'}, { type: 'separator' },
{role: 'front'} { role: 'front' }
] ]
} }
@ -249,17 +249,17 @@ the user right clicks the page:
```html ```html
<!-- index.html --> <!-- index.html -->
<script> <script>
const {remote} = require('electron') const { remote } = require('electron')
const {Menu, MenuItem} = remote const { Menu, MenuItem } = remote
const menu = new Menu() const menu = new Menu()
menu.append(new MenuItem({label: 'MenuItem1', click() { console.log('item 1 clicked') }})) menu.append(new MenuItem({ label: 'MenuItem1', click() { console.log('item 1 clicked') } })))
menu.append(new MenuItem({type: 'separator'})) menu.append(new MenuItem({ type: 'separator' }))
menu.append(new MenuItem({label: 'MenuItem2', type: 'checkbox', checked: true})) menu.append(new MenuItem({ label: 'MenuItem2', type: 'checkbox', checked: true }))
window.addEventListener('contextmenu', (e) => { window.addEventListener('contextmenu', (e) => {
e.preventDefault() e.preventDefault()
menu.popup({window: remote.getCurrentWindow()}) menu.popup({ window: remote.getCurrentWindow() })
}, false) }, false)
</script> </script>
``` ```

Просмотреть файл

@ -11,17 +11,17 @@ For example, when creating a tray or setting a window's icon, you can pass an
image file path as a `String`: image file path as a `String`:
```javascript ```javascript
const {BrowserWindow, Tray} = require('electron') const { BrowserWindow, Tray } = require('electron')
const appIcon = new Tray('/Users/somebody/images/icon.png') const appIcon = new Tray('/Users/somebody/images/icon.png')
let win = new BrowserWindow({icon: '/Users/somebody/images/window.png'}) let win = new BrowserWindow({ icon: '/Users/somebody/images/window.png' })
console.log(appIcon, win) console.log(appIcon, win)
``` ```
Or read the image from the clipboard which returns a `NativeImage`: Or read the image from the clipboard which returns a `NativeImage`:
```javascript ```javascript
const {clipboard, Tray} = require('electron') const { clipboard, Tray } = require('electron')
const image = clipboard.readImage() const image = clipboard.readImage()
const appIcon = new Tray(image) const appIcon = new Tray(image)
console.log(appIcon) console.log(appIcon)
@ -73,7 +73,7 @@ images/
```javascript ```javascript
const {Tray} = require('electron') const { Tray } = require('electron')
let appIcon = new Tray('/Users/somebody/images/icon.png') let appIcon = new Tray('/Users/somebody/images/icon.png')
console.log(appIcon) console.log(appIcon)
``` ```

Просмотреть файл

@ -5,7 +5,7 @@
Process: [Main](../glossary.md#main-process) Process: [Main](../glossary.md#main-process)
```javascript ```javascript
const {netLog} = require('electron') const { netLog } = require('electron')
console.log('Start recording net-logs') console.log('Start recording net-logs')
netLog.startLogging('/path/to/net-log') netLog.startLogging('/path/to/net-log')
// After some network events // After some network events

Просмотреть файл

@ -30,9 +30,9 @@ For instance, the following example quickly shows how the `net` API might be
used: used:
```javascript ```javascript
const {app} = require('electron') const { app } = require('electron')
app.on('ready', () => { app.on('ready', () => {
const {net} = require('electron') const { net } = require('electron')
const request = net.request('https://github.com') const request = net.request('https://github.com')
request.on('response', (response) => { request.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`) console.log(`STATUS: ${response.statusCode}`)

Просмотреть файл

@ -11,7 +11,7 @@ For example:
```javascript ```javascript
const electron = require('electron') const electron = require('electron')
const {app} = electron const { app } = electron
app.on('ready', () => { app.on('ready', () => {
electron.powerMonitor.on('suspend', () => { electron.powerMonitor.on('suspend', () => {

Просмотреть файл

@ -7,7 +7,7 @@ Process: [Main](../glossary.md#main-process)
For example: For example:
```javascript ```javascript
const {powerSaveBlocker} = require('electron') const { powerSaveBlocker } = require('electron')
const id = powerSaveBlocker.start('prevent-display-sleep') const id = powerSaveBlocker.start('prevent-display-sleep')
console.log(powerSaveBlocker.isStarted(id)) console.log(powerSaveBlocker.isStarted(id))

Просмотреть файл

@ -8,13 +8,13 @@ An example of implementing a protocol that has the same effect as the
`file://` protocol: `file://` protocol:
```javascript ```javascript
const {app, protocol} = require('electron') const { app, protocol } = require('electron')
const path = require('path') const path = require('path')
app.on('ready', () => { app.on('ready', () => {
protocol.registerFileProtocol('atom', (request, callback) => { protocol.registerFileProtocol('atom', (request, callback) => {
const url = request.url.substr(7) const url = request.url.substr(7)
callback({path: path.normalize(`${__dirname}/${url}`)}) callback({ path: path.normalize(`${__dirname}/${url}`) })
}, (error) => { }, (error) => {
if (error) console.error('Failed to register protocol') if (error) console.error('Failed to register protocol')
}) })
@ -62,7 +62,7 @@ are disabled for non standard schemes. So in general if you want to register a
custom protocol to replace the `http` protocol, you have to register it as a standard scheme: custom protocol to replace the `http` protocol, you have to register it as a standard scheme:
```javascript ```javascript
const {app, protocol} = require('electron') const { app, protocol } = require('electron')
protocol.registerStandardSchemes(['atom']) protocol.registerStandardSchemes(['atom'])
app.on('ready', () => { app.on('ready', () => {
@ -99,7 +99,7 @@ going to be created with `scheme`. `completion` will be called with
To handle the `request`, the `callback` should be called with either the file's To handle the `request`, the `callback` should be called with either the file's
path or an object that has a `path` property, e.g. `callback(filePath)` or path or an object that has a `path` property, e.g. `callback(filePath)` or
`callback({path: filePath})`. `callback({ path: filePath })`.
When `callback` is called with nothing, a number, or an object that has an When `callback` is called with nothing, a number, or an object that has an
`error` property, the `request` will fail with the `error` number you `error` property, the `request` will fail with the `error` number you
@ -134,10 +134,10 @@ should be called with either a `Buffer` object or an object that has the `data`,
Example: Example:
```javascript ```javascript
const {protocol} = require('electron') const { protocol } = require('electron')
protocol.registerBufferProtocol('atom', (request, callback) => { protocol.registerBufferProtocol('atom', (request, callback) => {
callback({mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>')}) callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') })
}, (error) => { }, (error) => {
if (error) console.error('Failed to register protocol') if (error) console.error('Failed to register protocol')
}) })
@ -218,8 +218,8 @@ has the `data`, `statusCode`, and `headers` properties.
Example: Example:
```javascript ```javascript
const {protocol} = require('electron') const { protocol } = require('electron')
const {PassThrough} = require('stream') const { PassThrough } = require('stream')
function createStream (text) { function createStream (text) {
const rv = new PassThrough() // PassThrough is also a Readable stream const rv = new PassThrough() // PassThrough is also a Readable stream
@ -245,7 +245,7 @@ It is possible to pass any object that implements the readable stream API (emits
`data`/`end`/`error` events). For example, here's how a file could be returned: `data`/`end`/`error` events). For example, here's how a file could be returned:
```javascript ```javascript
const {protocol} = require('electron') const { protocol } = require('electron')
const fs = require('fs') const fs = require('fs')
protocol.registerStreamProtocol('atom', (request, callback) => { protocol.registerStreamProtocol('atom', (request, callback) => {

Просмотреть файл

@ -16,8 +16,8 @@ similar to Java's [RMI][rmi]. An example of creating a browser window from a
renderer process: renderer process:
```javascript ```javascript
const {BrowserWindow} = require('electron').remote const { BrowserWindow } = require('electron').remote
let win = new BrowserWindow({width: 800, height: 600}) let win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com') win.loadURL('https://github.com')
``` ```
@ -158,7 +158,7 @@ project/
```js ```js
// main process: main/index.js // main process: main/index.js
const {app} = require('electron') const { app } = require('electron')
app.on('ready', () => { /* ... */ }) app.on('ready', () => { /* ... */ })
``` ```

Просмотреть файл

@ -115,7 +115,7 @@ and preload.js:
// private scope that can access a subset of Electron renderer APIs. We must be // private scope that can access a subset of Electron renderer APIs. We must be
// careful to not leak any objects into the global scope! // careful to not leak any objects into the global scope!
const fs = require('fs') const fs = require('fs')
const {ipcRenderer} = require('electron') const { ipcRenderer } = require('electron')
// read a configuration file using the `fs` module // read a configuration file using the `fs` module
const buf = fs.readFileSync('allowed-popup-urls.json') const buf = fs.readFileSync('allowed-popup-urls.json')

Просмотреть файл

@ -10,19 +10,19 @@ module is emitted.
`screen` is an [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter). `screen` is an [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter).
**Note:** In the renderer / DevTools, `window.screen` is a reserved DOM **Note:** In the renderer / DevTools, `window.screen` is a reserved DOM
property, so writing `let {screen} = require('electron')` will not work. property, so writing `let { screen } = require('electron')` will not work.
An example of creating a window that fills the whole screen: An example of creating a window that fills the whole screen:
```javascript ```javascript
const electron = require('electron') const electron = require('electron')
const {app, BrowserWindow} = electron const { app, BrowserWindow } = electron
let win let win
app.on('ready', () => { app.on('ready', () => {
const {width, height} = electron.screen.getPrimaryDisplay().workAreaSize const { width, height } = electron.screen.getPrimaryDisplay().workAreaSize
win = new BrowserWindow({width, height}) win = new BrowserWindow({ width, height })
win.loadURL('https://github.com') win.loadURL('https://github.com')
}) })
``` ```
@ -31,7 +31,7 @@ Another example of creating a window in the external display:
```javascript ```javascript
const electron = require('electron') const electron = require('electron')
const {app, BrowserWindow} = require('electron') const { app, BrowserWindow } = require('electron')
let win let win

Просмотреть файл

@ -10,9 +10,9 @@ You can also access the `session` of existing pages by using the `session`
property of [`WebContents`](web-contents.md), or from the `session` module. property of [`WebContents`](web-contents.md), or from the `session` module.
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow({width: 800, height: 600}) let win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('http://github.com') win.loadURL('http://github.com')
const ses = win.webContents.session const ses = win.webContents.session
@ -59,7 +59,7 @@ Process: [Main](../glossary.md#main-process)
You can create a `Session` object in the `session` module: You can create a `Session` object in the `session` module:
```javascript ```javascript
const {session} = require('electron') const { session } = require('electron')
const ses = session.fromPartition('persist:name') const ses = session.fromPartition('persist:name')
console.log(ses.getUserAgent()) console.log(ses.getUserAgent())
``` ```
@ -80,7 +80,7 @@ Calling `event.preventDefault()` will cancel the download and `item` will not be
available from next tick of the process. available from next tick of the process.
```javascript ```javascript
const {session} = require('electron') const { session } = require('electron')
session.defaultSession.on('will-download', (event, item, webContents) => { session.defaultSession.on('will-download', (event, item, webContents) => {
event.preventDefault() event.preventDefault()
require('request')(item.getURL(), (data) => { require('request')(item.getURL(), (data) => {
@ -239,7 +239,7 @@ window.webContents.session.enableNetworkEmulation({
}) })
// To emulate a network outage. // To emulate a network outage.
window.webContents.session.enableNetworkEmulation({offline: true}) window.webContents.session.enableNetworkEmulation({ offline: true })
``` ```
#### `ses.disableNetworkEmulation()` #### `ses.disableNetworkEmulation()`
@ -272,11 +272,11 @@ Calling `setCertificateVerifyProc(null)` will revert back to default certificate
verify proc. verify proc.
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow() let win = new BrowserWindow()
win.webContents.session.setCertificateVerifyProc((request, callback) => { win.webContents.session.setCertificateVerifyProc((request, callback) => {
const {hostname} = request const { hostname } = request
if (hostname === 'github.com') { if (hostname === 'github.com') {
callback(0) callback(0)
} else { } else {
@ -303,7 +303,7 @@ Calling `callback(true)` will allow the permission and `callback(false)` will re
To clear the handler, call `setPermissionRequestHandler(null)`. To clear the handler, call `setPermissionRequestHandler(null)`.
```javascript ```javascript
const {session} = require('electron') const { session } = require('electron')
session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => { session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => {
if (webContents.getURL() === 'some-host' && permission === 'notifications') { if (webContents.getURL() === 'some-host' && permission === 'notifications') {
return callback(false) // denied. return callback(false) // denied.
@ -329,7 +329,7 @@ Returning `true` will allow the permission and `false` will reject it.
To clear the handler, call `setPermissionCheckHandler(null)`. To clear the handler, call `setPermissionCheckHandler(null)`.
```javascript ```javascript
const {session} = require('electron') const { session } = require('electron')
session.fromPartition('some-partition').setPermissionCheckHandler((webContents, permission) => { session.fromPartition('some-partition').setPermissionCheckHandler((webContents, permission) => {
if (webContents.getURL() === 'some-host' && permission === 'notifications') { if (webContents.getURL() === 'some-host' && permission === 'notifications') {
return false // denied return false // denied
@ -354,7 +354,7 @@ Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate
authentication. authentication.
```javascript ```javascript
const {session} = require('electron') const { session } = require('electron')
// consider any url ending with `example.com`, `foobar.com`, `baz` // consider any url ending with `example.com`, `foobar.com`, `baz`
// for integrated authentication. // for integrated authentication.
session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz') session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz')
@ -441,14 +441,14 @@ A [WebRequest](web-request.md) object for this session.
A [Protocol](protocol.md) object for this session. A [Protocol](protocol.md) object for this session.
```javascript ```javascript
const {app, session} = require('electron') const { app, session } = require('electron')
const path = require('path') const path = require('path')
app.on('ready', function () { app.on('ready', function () {
const protocol = session.fromPartition('some-partition').protocol const protocol = session.fromPartition('some-partition').protocol
protocol.registerFileProtocol('atom', function (request, callback) { protocol.registerFileProtocol('atom', function (request, callback) {
var url = request.url.substr(7) var url = request.url.substr(7)
callback({path: path.normalize(`${__dirname}/${url}`)}) callback({ path: path.normalize(`${__dirname}/${url}`) })
}, function (error) { }, function (error) {
if (error) console.error('Failed to register protocol') if (error) console.error('Failed to register protocol')
}) })

Просмотреть файл

@ -9,7 +9,7 @@ The `shell` module provides functions related to desktop integration.
An example of opening a URL in the user's default browser: An example of opening a URL in the user's default browser:
```javascript ```javascript
const {shell} = require('electron') const { shell } = require('electron')
shell.openExternal('https://github.com') shell.openExternal('https://github.com')
``` ```

Просмотреть файл

@ -19,11 +19,11 @@ scripts to be able to use those modules.
The main process script is like a normal Node.js script: The main process script is like a normal Node.js script:
```javascript ```javascript
const {app, BrowserWindow} = require('electron') const { app, BrowserWindow } = require('electron')
let win = null let win = null
app.on('ready', () => { app.on('ready', () => {
win = new BrowserWindow({width: 800, height: 600}) win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com') win.loadURL('https://github.com')
}) })
``` ```
@ -36,7 +36,7 @@ extra ability to use node modules:
<html> <html>
<body> <body>
<script> <script>
const {app} = require('electron').remote const { app } = require('electron').remote
console.log(app.getVersion()) console.log(app.getVersion())
</script> </script>
</body> </body>
@ -52,7 +52,7 @@ As of 0.37, you can use
built-in modules. built-in modules.
```javascript ```javascript
const {app, BrowserWindow} = require('electron') const { app, BrowserWindow } = require('electron')
let win let win
@ -67,7 +67,7 @@ destructuring to access the individual modules from `electron`.
```javascript ```javascript
const electron = require('electron') const electron = require('electron')
const {app, BrowserWindow} = electron const { app, BrowserWindow } = electron
let win let win

Просмотреть файл

@ -5,7 +5,7 @@
Process: [Main](../glossary.md#main-process) Process: [Main](../glossary.md#main-process)
```javascript ```javascript
const {systemPreferences} = require('electron') const { systemPreferences } = require('electron')
console.log(systemPreferences.isDarkMode()) console.log(systemPreferences.isDarkMode())
``` ```
@ -185,8 +185,8 @@ An example of using it to determine if you should create a transparent window or
not (transparent windows won't work correctly when DWM composition is disabled): not (transparent windows won't work correctly when DWM composition is disabled):
```javascript ```javascript
const {BrowserWindow, systemPreferences} = require('electron') const { BrowserWindow, systemPreferences } = require('electron')
let browserOptions = {width: 1000, height: 800} let browserOptions = { width: 1000, height: 800 }
// Make the window transparent only if the platform supports it. // Make the window transparent only if the platform supports it.
if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) { if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) {

Просмотреть файл

@ -36,9 +36,9 @@ Below is an example of a simple slot machine touch bar game with a button
and some labels. and some labels.
```javascript ```javascript
const {app, BrowserWindow, TouchBar} = require('electron') const { app, BrowserWindow, TouchBar } = require('electron')
const {TouchBarLabel, TouchBarButton, TouchBarSpacer} = TouchBar const { TouchBarLabel, TouchBarButton, TouchBarSpacer } = TouchBar
let spinning = false let spinning = false
@ -114,13 +114,13 @@ const finishSpin = () => {
const touchBar = new TouchBar([ const touchBar = new TouchBar([
spin, spin,
new TouchBarSpacer({size: 'large'}), new TouchBarSpacer({ size: 'large' }),
reel1, reel1,
new TouchBarSpacer({size: 'small'}), new TouchBarSpacer({ size: 'small' }),
reel2, reel2,
new TouchBarSpacer({size: 'small'}), new TouchBarSpacer({ size: 'small' }),
reel3, reel3,
new TouchBarSpacer({size: 'large'}), new TouchBarSpacer({ size: 'large' }),
result result
]) ])

Просмотреть файл

@ -7,16 +7,16 @@ Process: [Main](../glossary.md#main-process)
`Tray` is an [EventEmitter][event-emitter]. `Tray` is an [EventEmitter][event-emitter].
```javascript ```javascript
const {app, Menu, Tray} = require('electron') const { app, Menu, Tray } = require('electron')
let tray = null let tray = null
app.on('ready', () => { app.on('ready', () => {
tray = new Tray('/path/to/my/icon') tray = new Tray('/path/to/my/icon')
const contextMenu = Menu.buildFromTemplate([ const contextMenu = Menu.buildFromTemplate([
{label: 'Item1', type: 'radio'}, { label: 'Item1', type: 'radio' },
{label: 'Item2', type: 'radio'}, { label: 'Item2', type: 'radio' },
{label: 'Item3', type: 'radio', checked: true}, { label: 'Item3', type: 'radio', checked: true },
{label: 'Item4', type: 'radio'} { label: 'Item4', type: 'radio' }
]) ])
tray.setToolTip('This is my application.') tray.setToolTip('This is my application.')
tray.setContextMenu(contextMenu) tray.setContextMenu(contextMenu)
@ -35,14 +35,14 @@ __Platform limitations:__
you have to call `setContextMenu` again. For example: you have to call `setContextMenu` again. For example:
```javascript ```javascript
const {app, Menu, Tray} = require('electron') const { app, Menu, Tray } = require('electron')
let appIcon = null let appIcon = null
app.on('ready', () => { app.on('ready', () => {
appIcon = new Tray('/path/to/my/icon') appIcon = new Tray('/path/to/my/icon')
const contextMenu = Menu.buildFromTemplate([ const contextMenu = Menu.buildFromTemplate([
{label: 'Item1', type: 'radio'}, { label: 'Item1', type: 'radio' },
{label: 'Item2', type: 'radio'} { label: 'Item2', type: 'radio' }
]) ])
// Make a change to the context menu // Make a change to the context menu
@ -225,9 +225,9 @@ by toggling between `'never'` and `'always'` modes when the window visibility
changes. changes.
```javascript ```javascript
const {BrowserWindow, Tray} = require('electron') const { BrowserWindow, Tray } = require('electron')
const win = new BrowserWindow({width: 800, height: 600}) const win = new BrowserWindow({ width: 800, height: 600 })
const tray = new Tray('/path/to/my/icon') const tray = new Tray('/path/to/my/icon')
tray.on('click', () => { tray.on('click', () => {

Просмотреть файл

@ -11,9 +11,9 @@ the [`BrowserWindow`](browser-window.md) object. An example of accessing the
`webContents` object: `webContents` object:
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow({width: 800, height: 1500}) let win = new BrowserWindow({ width: 800, height: 1500 })
win.loadURL('http://github.com') win.loadURL('http://github.com')
let contents = win.webContents let contents = win.webContents
@ -25,7 +25,7 @@ console.log(contents)
These methods can be accessed from the `webContents` module: These methods can be accessed from the `webContents` module:
```javascript ```javascript
const {webContents} = require('electron') const { webContents } = require('electron')
console.log(webContents) console.log(webContents)
``` ```
@ -140,7 +140,7 @@ instance, failing to do so may result in unexpected behavior. For example:
```javascript ```javascript
myBrowserWindow.webContents.on('new-window', (event, url) => { myBrowserWindow.webContents.on('new-window', (event, url) => {
event.preventDefault() event.preventDefault()
const win = new BrowserWindow({show: false}) const win = new BrowserWindow({ show: false })
win.once('ready-to-show', () => win.show()) win.once('ready-to-show', () => win.show())
win.loadURL(url) win.loadURL(url)
event.newGuest = win event.newGuest = win
@ -240,8 +240,8 @@ Calling `event.preventDefault()` will ignore the `beforeunload` event handler
and allow the page to be unloaded. and allow the page to be unloaded.
```javascript ```javascript
const {BrowserWindow, dialog} = require('electron') const { BrowserWindow, dialog } = require('electron')
const win = new BrowserWindow({width: 800, height: 600}) const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('will-prevent-unload', (event) => { win.webContents.on('will-prevent-unload', (event) => {
const choice = dialog.showMessageBox(win, { const choice = dialog.showMessageBox(win, {
type: 'question', type: 'question',
@ -312,9 +312,9 @@ To only prevent the menu shortcuts, use
[`setIgnoreMenuShortcuts`](#contentssetignoremenushortcutsignore-experimental): [`setIgnoreMenuShortcuts`](#contentssetignoremenushortcutsignore-experimental):
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow({width: 800, height: 600}) let win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('before-input-event', (event, input) => { win.webContents.on('before-input-event', (event, input) => {
// For example, only enable application menu keyboard shortcuts when // For example, only enable application menu keyboard shortcuts when
@ -535,13 +535,13 @@ first available device will be selected. `callback` should be called with
cancel the request. cancel the request.
```javascript ```javascript
const {app, BrowserWindow} = require('electron') const { app, BrowserWindow } = require('electron')
let win = null let win = null
app.commandLine.appendSwitch('enable-experimental-web-platform-features') app.commandLine.appendSwitch('enable-experimental-web-platform-features')
app.on('ready', () => { app.on('ready', () => {
win = new BrowserWindow({width: 800, height: 600}) win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { win.webContents.on('select-bluetooth-device', (event, deviceList, callback) => {
event.preventDefault() event.preventDefault()
let result = deviceList.find((device) => { let result = deviceList.find((device) => {
@ -568,9 +568,9 @@ Emitted when a new frame is generated. Only the dirty area is passed in the
buffer. buffer.
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow({webPreferences: {offscreen: true}}) let win = new BrowserWindow({ webPreferences: { offscreen: true } })
win.webContents.on('paint', (event, dirty, image) => { win.webContents.on('paint', (event, dirty, image) => {
// updateBitmap(dirty, image.getBitmap()) // updateBitmap(dirty, image.getBitmap())
}) })
@ -642,8 +642,8 @@ e.g. the `http://` or `file://`. If the load should bypass http cache then
use the `pragma` header to achieve it. use the `pragma` header to achieve it.
```javascript ```javascript
const {webContents} = require('electron') const { webContents } = require('electron')
const options = {extraHeaders: 'pragma: no-cache\n'} const options = { extraHeaders: 'pragma: no-cache\n' }
webContents.loadURL('https://github.com', options) webContents.loadURL('https://github.com', options)
``` ```
@ -685,8 +685,8 @@ Initiates a download of the resource at `url` without navigating. The
Returns `String` - The URL of the current web page. Returns `String` - The URL of the current web page.
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow({width: 800, height: 600}) let win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('http://github.com') win.loadURL('http://github.com')
let currentURL = win.webContents.getURL() let currentURL = win.webContents.getURL()
@ -979,7 +979,7 @@ can be obtained by subscribing to [`found-in-page`](web-contents.md#event-found-
Stops any `findInPage` request for the `webContents` with the provided `action`. Stops any `findInPage` request for the `webContents` with the provided `action`.
```javascript ```javascript
const {webContents} = require('electron') const { webContents } = require('electron')
webContents.on('found-in-page', (event, result) => { webContents.on('found-in-page', (event, result) => {
if (result.finalUpdate) webContents.stopFindInPage('clearSelection') if (result.finalUpdate) webContents.stopFindInPage('clearSelection')
}) })
@ -1037,7 +1037,7 @@ the system's default printer if `deviceName` is empty and the default settings
for printing. for printing.
Calling `window.print()` in web page is equivalent to calling Calling `window.print()` in web page is equivalent to calling
`webContents.print({silent: false, printBackground: false, deviceName: ''})`. `webContents.print({ silent: false, printBackground: false, deviceName: '' })`.
Use `page-break-before: always; ` CSS style to force to print to a new page. Use `page-break-before: always; ` CSS style to force to print to a new page.
@ -1080,10 +1080,10 @@ Use `page-break-before: always; ` CSS style to force to print to a new page.
An example of `webContents.printToPDF`: An example of `webContents.printToPDF`:
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
const fs = require('fs') const fs = require('fs')
let win = new BrowserWindow({width: 800, height: 600}) let win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('http://github.com') win.loadURL('http://github.com')
win.webContents.on('did-finish-load', () => { win.webContents.on('did-finish-load', () => {
@ -1106,7 +1106,7 @@ Adds the specified path to DevTools workspace. Must be used after DevTools
creation: creation:
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow() let win = new BrowserWindow()
win.webContents.on('devtools-opened', () => { win.webContents.on('devtools-opened', () => {
win.webContents.addWorkSpace(__dirname) win.webContents.addWorkSpace(__dirname)
@ -1167,7 +1167,7 @@ An example of showing devtools in a `<webview>` tag:
An example of showing devtools in a `BrowserWindow`: An example of showing devtools in a `BrowserWindow`:
```js ```js
const {app, BrowserWindow} = require('electron') const { app, BrowserWindow } = require('electron')
let win = null let win = null
let devtools = null let devtools = null
@ -1177,7 +1177,7 @@ app.once('ready', () => {
devtools = new BrowserWindow() devtools = new BrowserWindow()
win.loadURL('https://github.com') win.loadURL('https://github.com')
win.webContents.setDevToolsWebContents(devtools.webContents) win.webContents.setDevToolsWebContents(devtools.webContents)
win.webContents.openDevTools({mode: 'detach'}) win.webContents.openDevTools({ mode: 'detach' })
}) })
``` ```
@ -1236,11 +1236,11 @@ An example of sending messages from the main process to the renderer process:
```javascript ```javascript
// In the main process. // In the main process.
const {app, BrowserWindow} = require('electron') const { app, BrowserWindow } = require('electron')
let win = null let win = null
app.on('ready', () => { app.on('ready', () => {
win = new BrowserWindow({width: 800, height: 600}) win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL(`file://${__dirname}/index.html`) win.loadURL(`file://${__dirname}/index.html`)
win.webContents.on('did-finish-load', () => { win.webContents.on('did-finish-load', () => {
win.webContents.send('ping', 'whoooooooh!') win.webContents.send('ping', 'whoooooooh!')
@ -1270,7 +1270,7 @@ app.on('ready', () => {
* `mobile` - Mobile screen type. * `mobile` - Mobile screen type.
* `screenSize` [Size](structures/size.md) - Set the emulated screen size (screenPosition == mobile). * `screenSize` [Size](structures/size.md) - Set the emulated screen size (screenPosition == mobile).
* `viewPosition` [Point](structures/point.md) - Position the view on the screen * `viewPosition` [Point](structures/point.md) - Position the view on the screen
(screenPosition == mobile) (default: `{x: 0, y: 0}`). (screenPosition == mobile) (default: `{ x: 0, y: 0 }`).
* `deviceScaleFactor` Integer - Set the device scale factor (if zero defaults to * `deviceScaleFactor` Integer - Set the device scale factor (if zero defaults to
original device scale factor) (default: `0`). original device scale factor) (default: `0`).
* `viewSize` [Size](structures/size.md) - Set the emulated view size (empty means no override) * `viewSize` [Size](structures/size.md) - Set the emulated view size (empty means no override)
@ -1373,7 +1373,7 @@ the cursor when dragging.
Returns `Boolean` - true if the process of saving page has been initiated successfully. Returns `Boolean` - true if the process of saving page has been initiated successfully.
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow() let win = new BrowserWindow()
win.loadURL('https://github.com') win.loadURL('https://github.com')

Просмотреть файл

@ -11,7 +11,7 @@ be retrieved by certain properties and methods (e.g. `webFrame.firstChild`).
An example of zooming current page to 200%. An example of zooming current page to 200%.
```javascript ```javascript
const {webFrame} = require('electron') const { webFrame } = require('electron')
webFrame.setZoomFactor(2) webFrame.setZoomFactor(2)
``` ```
@ -73,7 +73,7 @@ whether the word passed is correctly spelled.
An example of using [node-spellchecker][spellchecker] as provider: An example of using [node-spellchecker][spellchecker] as provider:
```javascript ```javascript
const {webFrame} = require('electron') const { webFrame } = require('electron')
webFrame.setSpellCheckProvider('en-US', true, { webFrame.setSpellCheckProvider('en-US', true, {
spellCheck (text) { spellCheck (text) {
return !(require('spellchecker').isMisspelled(text)) return !(require('spellchecker').isMisspelled(text))
@ -105,7 +105,7 @@ Specify an option with the value of `false` to omit it from the registration.
An example of registering a privileged scheme, without bypassing Content Security Policy: An example of registering a privileged scheme, without bypassing Content Security Policy:
```javascript ```javascript
const {webFrame} = require('electron') const { webFrame } = require('electron')
webFrame.registerURLSchemeAsPrivileged('foo', { bypassCSP: false }) webFrame.registerURLSchemeAsPrivileged('foo', { bypassCSP: false })
``` ```
@ -177,7 +177,7 @@ Returns an object describing usage information of Blink's internal memory
caches. caches.
```javascript ```javascript
const {webFrame} = require('electron') const { webFrame } = require('electron')
console.log(webFrame.getResourceUsage()) console.log(webFrame.getResourceUsage())
``` ```

Просмотреть файл

@ -23,7 +23,7 @@ called with a `response` object when `listener` has done its work.
An example of adding `User-Agent` header for requests: An example of adding `User-Agent` header for requests:
```javascript ```javascript
const {session} = require('electron') const { session } = require('electron')
// Modify the user agent for all requests to the following urls. // Modify the user agent for all requests to the following urls.
const filter = { const filter = {
@ -32,7 +32,7 @@ const filter = {
session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => { session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
details.requestHeaders['User-Agent'] = 'MyAgent' details.requestHeaders['User-Agent'] = 'MyAgent'
callback({cancel: false, requestHeaders: details.requestHeaders}) callback({ cancel: false, requestHeaders: details.requestHeaders })
}) })
``` ```

Просмотреть файл

@ -752,7 +752,7 @@ Fired when the guest page attempts to open a new browser window.
The following example code opens the new url in system's default browser. The following example code opens the new url in system's default browser.
```javascript ```javascript
const {shell} = require('electron') const { shell } = require('electron')
const webview = document.querySelector('webview') const webview = document.querySelector('webview')
webview.addEventListener('new-window', (e) => { webview.addEventListener('new-window', (e) => {
@ -844,7 +844,7 @@ webview.send('ping')
```javascript ```javascript
// In guest page. // In guest page.
const {ipcRenderer} = require('electron') const { ipcRenderer } = require('electron')
ipcRenderer.on('ping', () => { ipcRenderer.on('ping', () => {
ipcRenderer.sendToHost('pong') ipcRenderer.sendToHost('pong')
}) })

Просмотреть файл

@ -144,7 +144,7 @@ codecs.
<video style="display:none" src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4" autoplay></video> <video style="display:none" src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4" autoplay></video>
<script> <script>
const video = document.querySelector('video') const video = document.querySelector('video')
video.addEventListener('error', ({target}) => { video.addEventListener('error', ({ target }) => {
if (target.error.code === target.error.MEDIA_ERR_SRC_NOT_SUPPORTED) { if (target.error.code === target.error.MEDIA_ERR_SRC_NOT_SUPPORTED) {
document.querySelector('#outcome').textContent = 'Not using proprietary codecs, video emitted source not supported error event.' document.querySelector('#outcome').textContent = 'Not using proprietary codecs, video emitted source not supported error event.'
} else { } else {

Просмотреть файл

@ -78,7 +78,7 @@ If you want a quick fix, you can make the variables global by changing your
code from this: code from this:
```javascript ```javascript
const {app, Tray} = require('electron') const { app, Tray } = require('electron')
app.on('ready', () => { app.on('ready', () => {
const tray = new Tray('/path/to/icon.png') const tray = new Tray('/path/to/icon.png')
tray.setTitle('hello world') tray.setTitle('hello world')
@ -88,7 +88,7 @@ app.on('ready', () => {
to this: to this:
```javascript ```javascript
const {app, Tray} = require('electron') const { app, Tray } = require('electron')
let tray = null let tray = null
app.on('ready', () => { app.on('ready', () => {
tray = new Tray('/path/to/icon.png') tray = new Tray('/path/to/icon.png')
@ -106,7 +106,7 @@ To solve this, you can turn off node integration in Electron:
```javascript ```javascript
// In the main process. // In the main process.
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow({ let win = new BrowserWindow({
webPreferences: { webPreferences: {
nodeIntegration: false nodeIntegration: false

Просмотреть файл

@ -11,7 +11,7 @@ var electronPath = require('electron')
// spawn the process // spawn the process
var env = { /* ... */ } var env = { /* ... */ }
var stdio = ['inherit', 'inherit', 'inherit', 'ipc'] var stdio = ['inherit', 'inherit', 'inherit', 'ipc']
var appProcess = childProcess.spawn(electronPath, ['./app'], {stdio, env}) var appProcess = childProcess.spawn(electronPath, ['./app'], { stdio, env })
// listen for IPC messages from the app // listen for IPC messages from the app
appProcess.on('message', (msg) => { appProcess.on('message', (msg) => {
@ -19,7 +19,7 @@ appProcess.on('message', (msg) => {
}) })
// send an IPC message to the app // send an IPC message to the app
appProcess.send({my: 'message'}) appProcess.send({ my: 'message' })
``` ```
From within the Electron app, you can listen for messages and send replies using the nodejs [process](https://nodejs.org/api/process.html) API: From within the Electron app, you can listen for messages and send replies using the nodejs [process](https://nodejs.org/api/process.html) API:
@ -31,7 +31,7 @@ process.on('message', (msg) => {
}) })
// send an IPC message to the test suite // send an IPC message to the test suite
process.send({my: 'message'}) process.send({ my: 'message' })
``` ```
We can now communicate from the test suite to the Electron app using the `appProcess` object. We can now communicate from the test suite to the Electron app using the `appProcess` object.
@ -40,12 +40,12 @@ For convenience, you may want to wrap `appProcess` in a driver object that provi
```js ```js
class TestDriver { class TestDriver {
constructor ({path, args, env}) { constructor ({ path, args, env }) {
this.rpcCalls = [] this.rpcCalls = []
// start child process // start child process
env.APP_TEST_DRIVER = 1 // let the app know it should listen for messages env.APP_TEST_DRIVER = 1 // let the app know it should listen for messages
this.process = childProcess.spawn(path, args, {stdio: ['inherit', 'inherit', 'inherit', 'ipc'], env}) this.process = childProcess.spawn(path, args, { stdio: ['inherit', 'inherit', 'inherit', 'ipc'], env })
// handle rpc responses // handle rpc responses
this.process.on('message', (message) => { this.process.on('message', (message) => {
@ -71,8 +71,8 @@ class TestDriver {
async rpc (cmd, ...args) { async rpc (cmd, ...args) {
// send rpc request // send rpc request
var msgId = this.rpcCalls.length var msgId = this.rpcCalls.length
this.process.send({msgId, cmd, args}) this.process.send({ msgId, cmd, args })
return new Promise((resolve, reject) => this.rpcCalls.push({resolve, reject})) return new Promise((resolve, reject) => this.rpcCalls.push({ resolve, reject }))
} }
stop () { stop () {
@ -88,19 +88,19 @@ if (process.env.APP_TEST_DRIVER) {
process.on('message', onMessage) process.on('message', onMessage)
} }
async function onMessage ({msgId, cmd, args}) { async function onMessage ({ msgId, cmd, args }) {
var method = METHODS[cmd] var method = METHODS[cmd]
if (!method) method = () => new Error('Invalid method: ' + cmd) if (!method) method = () => new Error('Invalid method: ' + cmd)
try { try {
var resolve = await method(...args) var resolve = await method(...args)
process.send({msgId, resolve}) process.send({ msgId, resolve })
} catch (err) { } catch (err) {
var reject = { var reject = {
message: err.message, message: err.message,
stack: err.stack, stack: err.stack,
name: err.name name: err.name
} }
process.send({msgId, reject}) process.send({ msgId, reject })
} }
} }

Просмотреть файл

@ -105,11 +105,11 @@ using the `electron.BrowserWindow` class. A simple `main.js` file might wait
for the application to be ready and open a window: for the application to be ready and open a window:
```javascript ```javascript
const {app, BrowserWindow} = require('electron') const { app, BrowserWindow } = require('electron')
function createWindow () { function createWindow () {
// Create the browser window. // Create the browser window.
win = new BrowserWindow({width: 800, height: 600}) win = new BrowserWindow({ width: 800, height: 600 })
// and load the index.html of the app. // and load the index.html of the app.
win.loadFile('index.html') win.loadFile('index.html')
@ -124,7 +124,7 @@ 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. windows on macOS if the user clicks on the app's icon in the dock.
```javascript ```javascript
const {app, BrowserWindow} = require('electron') const { app, BrowserWindow } = require('electron')
// Keep a global reference of the window object, if you don't, the window will // 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. // be closed automatically when the JavaScript object is garbage collected.
@ -132,7 +132,7 @@ let win
function createWindow () { function createWindow () {
// Create the browser window. // Create the browser window.
win = new BrowserWindow({width: 800, height: 600}) win = new BrowserWindow({ width: 800, height: 600 })
// and load the index.html of the app. // and load the index.html of the app.
win.loadFile('index.html') win.loadFile('index.html')

Просмотреть файл

@ -9,7 +9,7 @@ be triggered only when the app is focused. To do so, specify an
[`accelerator`] property when creating a [MenuItem]. [`accelerator`] property when creating a [MenuItem].
```js ```js
const {Menu, MenuItem} = require('electron') const { Menu, MenuItem } = require('electron')
const menu = new Menu() const menu = new Menu()
menu.append(new MenuItem({ menu.append(new MenuItem({
@ -33,7 +33,7 @@ You can use the [globalShortcut] module to detect keyboard events even when
the application does not have keyboard focus. the application does not have keyboard focus.
```js ```js
const {app, globalShortcut} = require('electron') const { app, globalShortcut } = require('electron')
app.on('ready', () => { app.on('ready', () => {
globalShortcut.register('CommandOrControl+X', () => { globalShortcut.register('CommandOrControl+X', () => {

Просмотреть файл

@ -11,7 +11,7 @@ Example:
_main.js_ _main.js_
```javascript ```javascript
const {app, BrowserWindow} = require('electron') const { app, BrowserWindow } = require('electron')
let onlineStatusWindow let onlineStatusWindow
@ -50,7 +50,7 @@ to the main process and handled as needed, as shown in the following example.
_main.js_ _main.js_
```javascript ```javascript
const {app, BrowserWindow, ipcMain} = require('electron') const { app, BrowserWindow, ipcMain } = require('electron')
let onlineStatusWindow let onlineStatusWindow
app.on('ready', () => { app.on('ready', () => {
@ -70,7 +70,7 @@ _online-status.html_
<html> <html>
<body> <body>
<script> <script>
const {ipcRenderer} = require('electron') const { ipcRenderer } = require('electron')
const updateOnlineStatus = () => { const updateOnlineStatus = () => {
ipcRenderer.send('online-status-changed', navigator.onLine ? 'online' : 'offline') ipcRenderer.send('online-status-changed', navigator.onLine ? 'online' : 'offline')
} }

Просмотреть файл

@ -361,10 +361,10 @@ which can be set using Electron's
handler: handler:
```javascript ```javascript
const {session} = require('electron') const { session } = require('electron')
session.defaultSession.webRequest.onHeadersReceived((details, callback) => { session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
callback({responseHeaders: `default-src 'none'`}) callback({ responseHeaders: `default-src 'none'` })
}) })
``` ```

Просмотреть файл

@ -34,7 +34,7 @@ passed before the `ready` event of `app` module gets emitted.
Example code: Example code:
```javascript ```javascript
const {app, BrowserWindow} = require('electron') const { app, BrowserWindow } = require('electron')
// You have to pass the directory that contains widevine library here, it is // You have to pass the directory that contains widevine library here, it is
// * `libwidevinecdm.dylib` on macOS, // * `libwidevinecdm.dylib` on macOS,

Просмотреть файл

@ -20,7 +20,7 @@ before the app ready event. Also, turn on `plugins` option of `BrowserWindow`.
For example: For example:
```javascript ```javascript
const {app, BrowserWindow} = require('electron') const { app, BrowserWindow } = require('electron')
const path = require('path') const path = require('path')
// Specify flash path, supposing it is placed in the same directory with main.js. // Specify flash path, supposing it is placed in the same directory with main.js.

Просмотреть файл

@ -32,13 +32,13 @@ app.start().then(function () {
return app.browserWindow.isVisible() return app.browserWindow.isVisible()
}).then(function (isVisible) { }).then(function (isVisible) {
// Verify the window is visible // Verify the window is visible
assert.equal(isVisible, true) assert.strictEqual(isVisible, true)
}).then(function () { }).then(function () {
// Get the window's title // Get the window's title
return app.client.getTitle() return app.client.getTitle()
}).then(function (title) { }).then(function (title) {
// Verify the window's title // Verify the window's title
assert.equal(title, 'My App') assert.strictEqual(title, 'My App')
}).catch(function (error) { }).catch(function (error) {
// Log any failures // Log any failures
console.error('Test failed', error.message) console.error('Test failed', error.message)
@ -135,12 +135,12 @@ $ npm install webdriverio
const webdriverio = require('webdriverio') const webdriverio = require('webdriverio')
const options = { const options = {
host: 'localhost', // Use localhost as chrome driver server host: 'localhost', // Use localhost as chrome driver server
port: 9515, // "9515" is the port opened by chrome driver. port: 9515, // "9515" is the port opened by chrome driver.
desiredCapabilities: { desiredCapabilities: {
browserName: 'chrome', browserName: 'chrome',
chromeOptions: { chromeOptions: {
binary: '/Path-to-Your-App/electron', // Path to your Electron binary. binary: '/Path-to-Your-App/electron', // Path to your Electron binary.
args: [/* cli arguments */] // Optional, perhaps 'app=' + /path/to/your/app/ args: [/* cli arguments */] // Optional, perhaps 'app=' + /path/to/your/app/
} }
} }
} }

Просмотреть файл

@ -148,7 +148,7 @@ To set the overlay icon for a window, you can use the
[BrowserWindow.setOverlayIcon][setoverlayicon] API: [BrowserWindow.setOverlayIcon][setoverlayicon] API:
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow() let win = new BrowserWindow()
win.setOverlayIcon('path/to/overlay.png', 'Description for overlay') win.setOverlayIcon('path/to/overlay.png', 'Description for overlay')
``` ```
@ -167,7 +167,7 @@ To flash the BrowserWindow taskbar button, you can use the
[BrowserWindow.flashFrame][flashframe] API: [BrowserWindow.flashFrame][flashframe] API:
```javascript ```javascript
const {BrowserWindow} = require('electron') const { BrowserWindow } = require('electron')
let win = new BrowserWindow() let win = new BrowserWindow()
win.once('focus', () => win.flashFrame(false)) win.once('focus', () => win.flashFrame(false))
win.flashFrame(true) win.flashFrame(true)

Просмотреть файл

@ -2,14 +2,14 @@
const bindings = process.atomBinding('app') const bindings = process.atomBinding('app')
const path = require('path') const path = require('path')
const {app, App} = bindings const { app, App } = bindings
// Only one app object permitted. // Only one app object permitted.
module.exports = app module.exports = app
const electron = require('electron') const electron = require('electron')
const {deprecate, Menu} = electron const { deprecate, Menu } = electron
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
let dockMenu = null let dockMenu = null
@ -113,5 +113,5 @@ for (let name of events) {
} }
// Wrappers for native classes. // Wrappers for native classes.
const {DownloadItem} = process.atomBinding('download_item') const { DownloadItem } = process.atomBinding('download_item')
Object.setPrototypeOf(DownloadItem.prototype, EventEmitter.prototype) Object.setPrototypeOf(DownloadItem.prototype, EventEmitter.prototype)

Просмотреть файл

@ -1,5 +1,5 @@
const EventEmitter = require('events').EventEmitter const EventEmitter = require('events').EventEmitter
const {autoUpdater, AutoUpdater} = process.atomBinding('auto_updater') const { autoUpdater, AutoUpdater } = process.atomBinding('auto_updater')
// AutoUpdater is an EventEmitter. // AutoUpdater is an EventEmitter.
Object.setPrototypeOf(AutoUpdater.prototype, EventEmitter.prototype) Object.setPrototypeOf(AutoUpdater.prototype, EventEmitter.prototype)

Просмотреть файл

@ -1,7 +1,7 @@
'use strict' 'use strict'
const {app} = require('electron') const { app } = require('electron')
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
const squirrelUpdate = require('./squirrel-update-win') const squirrelUpdate = require('./squirrel-update-win')
class AutoUpdater extends EventEmitter { class AutoUpdater extends EventEmitter {
@ -54,7 +54,7 @@ class AutoUpdater extends EventEmitter {
if (error != null) { if (error != null) {
return this.emitError(error) return this.emitError(error)
} }
const {releaseNotes, version} = update const { releaseNotes, version } = update
// Date is not available on Windows, so fake it. // Date is not available on Windows, so fake it.
const date = new Date() const date = new Date()
this.emit('update-downloaded', {}, releaseNotes, version, date, this.updateURL, () => { this.emit('update-downloaded', {}, releaseNotes, version, date, this.updateURL, () => {

Просмотреть файл

@ -2,8 +2,8 @@
const electron = require('electron') const electron = require('electron')
const {LayoutManager} = electron const { LayoutManager } = electron
const {BoxLayout} = process.atomBinding('box_layout') const { BoxLayout } = process.atomBinding('box_layout')
Object.setPrototypeOf(BoxLayout.prototype, LayoutManager.prototype) Object.setPrototypeOf(BoxLayout.prototype, LayoutManager.prototype)

Просмотреть файл

@ -1,7 +1,7 @@
'use strict' 'use strict'
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
const {BrowserView} = process.atomBinding('browser_view') const { BrowserView } = process.atomBinding('browser_view')
Object.setPrototypeOf(BrowserView.prototype, EventEmitter.prototype) Object.setPrototypeOf(BrowserView.prototype, EventEmitter.prototype)

Просмотреть файл

@ -1,8 +1,8 @@
'use strict' 'use strict'
const electron = require('electron') const electron = require('electron')
const {ipcMain, WebContentsView, TopLevelWindow} = electron const { ipcMain, WebContentsView, TopLevelWindow } = electron
const {BrowserWindow} = process.atomBinding('window') const { BrowserWindow } = process.atomBinding('window')
const v8Util = process.atomBinding('v8_util') const v8Util = process.atomBinding('v8_util')
Object.setPrototypeOf(BrowserWindow.prototype, TopLevelWindow.prototype) Object.setPrototypeOf(BrowserWindow.prototype, TopLevelWindow.prototype)
@ -12,35 +12,35 @@ BrowserWindow.prototype._init = function () {
TopLevelWindow.prototype._init.call(this) TopLevelWindow.prototype._init.call(this)
// Avoid recursive require. // Avoid recursive require.
const {app} = electron const { app } = electron
// Create WebContentsView. // Create WebContentsView.
this.setContentView(new WebContentsView(this.webContents)) this.setContentView(new WebContentsView(this.webContents))
// Make new windows requested by links behave like "window.open" // Make new windows requested by links behave like "window.open"
this.webContents.on('-new-window', (event, url, frameName, disposition, this.webContents.on('-new-window', (event, url, frameName, disposition,
additionalFeatures, postData, additionalFeatures, postData,
referrer) => { referrer) => {
const options = { const options = {
show: true, show: true,
width: 800, width: 800,
height: 600 height: 600
} }
ipcMain.emit('ELECTRON_GUEST_WINDOW_MANAGER_INTERNAL_WINDOW_OPEN', ipcMain.emit('ELECTRON_GUEST_WINDOW_MANAGER_INTERNAL_WINDOW_OPEN',
event, url, referrer, frameName, disposition, event, url, referrer, frameName, disposition,
options, additionalFeatures, postData) options, additionalFeatures, postData)
}) })
this.webContents.on('-web-contents-created', (event, webContents, url, this.webContents.on('-web-contents-created', (event, webContents, url,
frameName) => { frameName) => {
v8Util.setHiddenValue(webContents, 'url-framename', {url, frameName}) v8Util.setHiddenValue(webContents, 'url-framename', { url, frameName })
}) })
// Create a new browser window for the native implementation of // Create a new browser window for the native implementation of
// "window.open", used in sandbox and nativeWindowOpen mode // "window.open", used in sandbox and nativeWindowOpen mode
this.webContents.on('-add-new-contents', (event, webContents, disposition, this.webContents.on('-add-new-contents', (event, webContents, disposition,
userGesture, left, top, width, userGesture, left, top, width,
height) => { height) => {
let urlFrameName = v8Util.getHiddenValue(webContents, 'url-framename') let urlFrameName = v8Util.getHiddenValue(webContents, 'url-framename')
if ((disposition !== 'foreground-tab' && disposition !== 'new-window' && if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
disposition !== 'background-tab') || !urlFrameName) { disposition !== 'background-tab') || !urlFrameName) {
@ -48,7 +48,7 @@ BrowserWindow.prototype._init = function () {
return return
} }
let {url, frameName} = urlFrameName let { url, frameName } = urlFrameName
v8Util.deleteHiddenValue(webContents, 'url-framename') v8Util.deleteHiddenValue(webContents, 'url-framename')
const options = { const options = {
show: true, show: true,
@ -60,7 +60,7 @@ BrowserWindow.prototype._init = function () {
} }
const referrer = { url: '', policy: 'default' } const referrer = { url: '', policy: 'default' }
ipcMain.emit('ELECTRON_GUEST_WINDOW_MANAGER_INTERNAL_WINDOW_OPEN', ipcMain.emit('ELECTRON_GUEST_WINDOW_MANAGER_INTERNAL_WINDOW_OPEN',
event, url, referrer, frameName, disposition, options) event, url, referrer, frameName, disposition, options)
}) })
// window.resizeTo(...) // window.resizeTo(...)
@ -167,7 +167,7 @@ BrowserWindow.fromBrowserView = (browserView) => {
BrowserWindow.fromDevToolsWebContents = (webContents) => { BrowserWindow.fromDevToolsWebContents = (webContents) => {
for (const window of BrowserWindow.getAllWindows()) { for (const window of BrowserWindow.getAllWindows()) {
const {devToolsWebContents} = window const { devToolsWebContents } = window
if (devToolsWebContents != null && devToolsWebContents.equal(webContents)) { if (devToolsWebContents != null && devToolsWebContents.equal(webContents)) {
return window return window
} }

Просмотреть файл

@ -2,8 +2,8 @@
const electron = require('electron') const electron = require('electron')
const {View} = electron const { View } = electron
const {Button} = process.atomBinding('button') const { Button } = process.atomBinding('button')
Object.setPrototypeOf(Button.prototype, View.prototype) Object.setPrototypeOf(Button.prototype, View.prototype)

Просмотреть файл

@ -1,6 +1,6 @@
'use strict' 'use strict'
const {app, BrowserWindow} = require('electron') const { app, BrowserWindow } = require('electron')
const binding = process.atomBinding('dialog') const binding = process.atomBinding('dialog')
const v8Util = process.atomBinding('v8_util') const v8Util = process.atomBinding('v8_util')
@ -83,7 +83,7 @@ module.exports = {
} }
} }
let {buttonLabel, defaultPath, filters, properties, title, message, securityScopedBookmarks = false} = options let { buttonLabel, defaultPath, filters, properties, title, message, securityScopedBookmarks = false } = options
if (properties == null) { if (properties == null) {
properties = ['openFile'] properties = ['openFile']
@ -129,7 +129,7 @@ module.exports = {
const wrappedCallback = typeof callback === 'function' ? function (success, result, bookmarkData) { const wrappedCallback = typeof callback === 'function' ? function (success, result, bookmarkData) {
return success ? callback(result, bookmarkData) : callback() return success ? callback(result, bookmarkData) : callback()
} : null } : null
const settings = {title, buttonLabel, defaultPath, filters, message, securityScopedBookmarks, window} const settings = { title, buttonLabel, defaultPath, filters, message, securityScopedBookmarks, window }
settings.properties = dialogProperties settings.properties = dialogProperties
return binding.showOpenDialog(settings, wrappedCallback) return binding.showOpenDialog(settings, wrappedCallback)
}, },
@ -145,7 +145,7 @@ module.exports = {
} }
} }
let {buttonLabel, defaultPath, filters, title, message, securityScopedBookmarks = false, nameFieldLabel, showsTagField} = options let { buttonLabel, defaultPath, filters, title, message, securityScopedBookmarks = false, nameFieldLabel, showsTagField } = options
if (title == null) { if (title == null) {
title = '' title = ''
@ -188,7 +188,7 @@ module.exports = {
const wrappedCallback = typeof callback === 'function' ? function (success, result, bookmarkData) { const wrappedCallback = typeof callback === 'function' ? function (success, result, bookmarkData) {
return success ? callback(result, bookmarkData) : callback() return success ? callback(result, bookmarkData) : callback()
} : null } : null
const settings = {title, buttonLabel, defaultPath, filters, message, securityScopedBookmarks, nameFieldLabel, showsTagField, window} const settings = { title, buttonLabel, defaultPath, filters, message, securityScopedBookmarks, nameFieldLabel, showsTagField, window }
return binding.showSaveDialog(settings, wrappedCallback) return binding.showSaveDialog(settings, wrappedCallback)
}, },
@ -275,8 +275,8 @@ module.exports = {
const flags = options.noLink ? messageBoxOptions.noLink : 0 const flags = options.noLink ? messageBoxOptions.noLink : 0
return binding.showMessageBox(messageBoxType, buttons, defaultId, cancelId, return binding.showMessageBox(messageBoxType, buttons, defaultId, cancelId,
flags, title, message, detail, checkboxLabel, flags, title, message, detail, checkboxLabel,
checkboxChecked, icon, window, callback) checkboxChecked, icon, window, callback)
}, },
showErrorBox: function (...args) { showErrorBox: function (...args) {
@ -290,7 +290,7 @@ module.exports = {
throw new TypeError('options must be an object') throw new TypeError('options must be an object')
} }
let {certificate, message} = options let { certificate, message } = options
if (certificate == null || typeof certificate !== 'object') { if (certificate == null || typeof certificate !== 'object') {
throw new TypeError('certificate must be an object') throw new TypeError('certificate must be an object')
} }

Просмотреть файл

@ -1,8 +1,8 @@
'use strict' 'use strict'
if (process.platform === 'darwin') { if (process.platform === 'darwin') {
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
const {inAppPurchase, InAppPurchase} = process.atomBinding('in_app_purchase') const { inAppPurchase, InAppPurchase } = process.atomBinding('in_app_purchase')
// inAppPurchase is an EventEmitter. // inAppPurchase is an EventEmitter.
Object.setPrototypeOf(InAppPurchase.prototype, EventEmitter.prototype) Object.setPrototypeOf(InAppPurchase.prototype, EventEmitter.prototype)

Просмотреть файл

@ -2,8 +2,8 @@
const electron = require('electron') const electron = require('electron')
const {Button} = electron const { Button } = electron
const {LabelButton} = process.atomBinding('label_button') const { LabelButton } = process.atomBinding('label_button')
Object.setPrototypeOf(LabelButton.prototype, Button.prototype) Object.setPrototypeOf(LabelButton.prototype, Button.prototype)

Просмотреть файл

@ -1,6 +1,6 @@
'use strict' 'use strict'
const {LayoutManager} = process.atomBinding('layout_manager') const { LayoutManager } = process.atomBinding('layout_manager')
LayoutManager.prototype._init = function () { LayoutManager.prototype._init = function () {
} }

Просмотреть файл

@ -1,4 +1,4 @@
const {app} = require('electron') const { app } = require('electron')
const roles = { const roles = {
about: { about: {
@ -244,7 +244,7 @@ exports.getDefaultAccelerator = (role) => {
exports.getDefaultSubmenu = (role) => { exports.getDefaultSubmenu = (role) => {
if (!roles.hasOwnProperty(role)) return if (!roles.hasOwnProperty(role)) return
let {submenu} = roles[role] let { submenu } = roles[role]
// remove null items from within the submenu // remove null items from within the submenu
if (Array.isArray(submenu)) { if (Array.isArray(submenu)) {
@ -257,7 +257,7 @@ exports.getDefaultSubmenu = (role) => {
exports.execute = (role, focusedWindow, focusedWebContents) => { exports.execute = (role, focusedWindow, focusedWebContents) => {
if (!canExecuteRole(role)) return false if (!canExecuteRole(role)) return false
const {appMethod, webContentsMethod, windowMethod} = roles[role] const { appMethod, webContentsMethod, windowMethod } = roles[role]
if (appMethod) { if (appMethod) {
app[appMethod]() app[appMethod]()

Просмотреть файл

@ -5,7 +5,7 @@ const roles = require('./menu-item-roles')
let nextCommandId = 0 let nextCommandId = 0
const MenuItem = function (options) { const MenuItem = function (options) {
const {Menu} = require('electron') const { Menu } = require('electron')
// Preserve extra fields specified by user // Preserve extra fields specified by user
for (let key in options) { for (let key in options) {

Просмотреть файл

@ -165,4 +165,4 @@ function sortMenuItems (menuItems) {
return joined return joined
} }
module.exports = {sortMenuItems} module.exports = { sortMenuItems }

Просмотреть файл

@ -1,12 +1,12 @@
'use strict' 'use strict'
const {TopLevelWindow, MenuItem, webContents} = require('electron') const { TopLevelWindow, MenuItem, webContents } = require('electron')
const {sortMenuItems} = require('./menu-utils') const { sortMenuItems } = require('./menu-utils')
const EventEmitter = require('events').EventEmitter const EventEmitter = require('events').EventEmitter
const v8Util = process.atomBinding('v8_util') const v8Util = process.atomBinding('v8_util')
const bindings = process.atomBinding('menu') const bindings = process.atomBinding('menu')
const {Menu} = bindings const { Menu } = bindings
let applicationMenu = null let applicationMenu = null
let groupIdIndex = 0 let groupIdIndex = 0
@ -51,7 +51,7 @@ Menu.prototype.popup = function (options = {}) {
if (options == null || typeof options !== 'object') { if (options == null || typeof options !== 'object') {
throw new TypeError('Options must be an object') throw new TypeError('Options must be an object')
} }
let {window, x, y, positioningItem, callback} = options let { window, x, y, positioningItem, callback } = options
// no callback passed // no callback passed
if (!callback || typeof callback !== 'function') callback = () => {} if (!callback || typeof callback !== 'function') callback = () => {}
@ -175,7 +175,7 @@ Menu.buildFromTemplate = function (template) {
// validate the template against having the wrong attribute // validate the template against having the wrong attribute
function areValidTemplateItems (template) { function areValidTemplateItems (template) {
return template.every(item => return template.every(item =>
item != null && typeof item === 'object' && (item.hasOwnProperty('label') || item.hasOwnProperty('role') || item.type === 'separator')) item != null && typeof item === 'object' && (item.hasOwnProperty('label') || item.hasOwnProperty('role') || item.type === 'separator'))
} }
function sortTemplate (template) { function sortTemplate (template) {

Просмотреть файл

@ -2,42 +2,42 @@ const features = process.atomBinding('features')
// Browser side modules, please sort alphabetically. // Browser side modules, please sort alphabetically.
module.exports = [ module.exports = [
{name: 'app', file: 'app'}, { name: 'app', file: 'app' },
{name: 'autoUpdater', file: 'auto-updater'}, { name: 'autoUpdater', file: 'auto-updater' },
{name: 'BrowserView', file: 'browser-view'}, { name: 'BrowserView', file: 'browser-view' },
{name: 'BrowserWindow', file: 'browser-window'}, { name: 'BrowserWindow', file: 'browser-window' },
{name: 'contentTracing', file: 'content-tracing'}, { name: 'contentTracing', file: 'content-tracing' },
{name: 'dialog', file: 'dialog'}, { name: 'dialog', file: 'dialog' },
{name: 'globalShortcut', file: 'global-shortcut'}, { name: 'globalShortcut', file: 'global-shortcut' },
{name: 'ipcMain', file: 'ipc-main'}, { name: 'ipcMain', file: 'ipc-main' },
{name: 'inAppPurchase', file: 'in-app-purchase'}, { name: 'inAppPurchase', file: 'in-app-purchase' },
{name: 'Menu', file: 'menu'}, { name: 'Menu', file: 'menu' },
{name: 'MenuItem', file: 'menu-item'}, { name: 'MenuItem', file: 'menu-item' },
{name: 'net', file: 'net'}, { name: 'net', file: 'net' },
{name: 'netLog', file: 'net-log'}, { name: 'netLog', file: 'net-log' },
{name: 'Notification', file: 'notification'}, { name: 'Notification', file: 'notification' },
{name: 'powerMonitor', file: 'power-monitor'}, { name: 'powerMonitor', file: 'power-monitor' },
{name: 'powerSaveBlocker', file: 'power-save-blocker'}, { name: 'powerSaveBlocker', file: 'power-save-blocker' },
{name: 'protocol', file: 'protocol'}, { name: 'protocol', file: 'protocol' },
{name: 'screen', file: 'screen'}, { name: 'screen', file: 'screen' },
{name: 'session', file: 'session'}, { name: 'session', file: 'session' },
{name: 'systemPreferences', file: 'system-preferences'}, { name: 'systemPreferences', file: 'system-preferences' },
{name: 'TopLevelWindow', file: 'top-level-window'}, { name: 'TopLevelWindow', file: 'top-level-window' },
{name: 'TouchBar', file: 'touch-bar'}, { name: 'TouchBar', file: 'touch-bar' },
{name: 'Tray', file: 'tray'}, { name: 'Tray', file: 'tray' },
{name: 'View', file: 'view'}, { name: 'View', file: 'view' },
{name: 'webContents', file: 'web-contents'}, { name: 'webContents', file: 'web-contents' },
{name: 'WebContentsView', file: 'web-contents-view'}, { name: 'WebContentsView', file: 'web-contents-view' },
// The internal modules, invisible unless you know their names. // The internal modules, invisible unless you know their names.
{name: 'NavigationController', file: 'navigation-controller', private: true} { name: 'NavigationController', file: 'navigation-controller', private: true }
] ]
if (features.isViewApiEnabled()) { if (features.isViewApiEnabled()) {
module.exports.push( module.exports.push(
{name: 'BoxLayout', file: 'box-layout'}, { name: 'BoxLayout', file: 'box-layout' },
{name: 'Button', file: 'button'}, { name: 'Button', file: 'button' },
{name: 'LabelButton', file: 'label-button'}, { name: 'LabelButton', file: 'label-button' },
{name: 'LayoutManager', file: 'layout-manager'}, { name: 'LayoutManager', file: 'layout-manager' },
{name: 'TextField', file: 'text-field'} { name: 'TextField', file: 'text-field' }
) )
} }

Просмотреть файл

@ -1,6 +1,6 @@
'use strict' 'use strict'
const {ipcMain} = require('electron') const { ipcMain } = require('electron')
// The history operation in renderer is redirected to browser. // The history operation in renderer is redirected to browser.
ipcMain.on('ELECTRON_NAVIGATION_CONTROLLER', function (event, method, ...args) { ipcMain.on('ELECTRON_NAVIGATION_CONTROLLER', function (event, method, ...args) {

Просмотреть файл

@ -1,6 +1,6 @@
'use strict' 'use strict'
const {netLog, NetLog} = process.atomBinding('net_log') const { netLog, NetLog } = process.atomBinding('net_log')
NetLog.prototype.stopLogging = function (callback) { NetLog.prototype.stopLogging = function (callback) {
if (callback && typeof callback !== 'function') { if (callback && typeof callback !== 'function') {

Просмотреть файл

@ -1,12 +1,12 @@
'use strict' 'use strict'
const url = require('url') const url = require('url')
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
const {Readable} = require('stream') const { Readable } = require('stream')
const {app} = require('electron') const { app } = require('electron')
const {Session} = process.atomBinding('session') const { Session } = process.atomBinding('session')
const {net, Net} = process.atomBinding('net') const { net, Net } = process.atomBinding('net')
const {URLRequest} = net const { URLRequest } = net
// Net is an EventEmitter. // Net is an EventEmitter.
Object.setPrototypeOf(Net.prototype, EventEmitter.prototype) Object.setPrototypeOf(Net.prototype, EventEmitter.prototype)

Просмотреть файл

@ -1,5 +1,5 @@
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
const {Notification, isSupported} = process.atomBinding('notification') const { Notification, isSupported } = process.atomBinding('notification')
Object.setPrototypeOf(Notification.prototype, EventEmitter.prototype) Object.setPrototypeOf(Notification.prototype, EventEmitter.prototype)

Просмотреть файл

@ -1,5 +1,5 @@
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
const {powerMonitor, PowerMonitor} = process.atomBinding('power_monitor') const { powerMonitor, PowerMonitor } = process.atomBinding('power_monitor')
// PowerMonitor is an EventEmitter. // PowerMonitor is an EventEmitter.
Object.setPrototypeOf(PowerMonitor.prototype, EventEmitter.prototype) Object.setPrototypeOf(PowerMonitor.prototype, EventEmitter.prototype)

Просмотреть файл

@ -1,4 +1,4 @@
const {app, session} = require('electron') const { app, session } = require('electron')
// Global protocol APIs. // Global protocol APIs.
module.exports = process.atomBinding('protocol') module.exports = process.atomBinding('protocol')

Просмотреть файл

@ -1,5 +1,5 @@
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
const {screen, Screen} = process.atomBinding('screen') const { screen, Screen } = process.atomBinding('screen')
// Screen is an EventEmitter. // Screen is an EventEmitter.
Object.setPrototypeOf(Screen.prototype, EventEmitter.prototype) Object.setPrototypeOf(Screen.prototype, EventEmitter.prototype)

Просмотреть файл

@ -1,6 +1,6 @@
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
const {app} = require('electron') const { app } = require('electron')
const {fromPartition, Session, Cookies} = process.atomBinding('session') const { fromPartition, Session, Cookies } = process.atomBinding('session')
// Public API. // Public API.
Object.defineProperties(exports, { Object.defineProperties(exports, {

Просмотреть файл

@ -1,5 +1,5 @@
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
const {systemPreferences, SystemPreferences} = process.atomBinding('system_preferences') const { systemPreferences, SystemPreferences } = process.atomBinding('system_preferences')
// SystemPreferences is an EventEmitter. // SystemPreferences is an EventEmitter.
Object.setPrototypeOf(SystemPreferences.prototype, EventEmitter.prototype) Object.setPrototypeOf(SystemPreferences.prototype, EventEmitter.prototype)

Просмотреть файл

@ -2,8 +2,8 @@
const electron = require('electron') const electron = require('electron')
const {View} = electron const { View } = electron
const {TextField} = process.atomBinding('text_field') const { TextField } = process.atomBinding('text_field')
Object.setPrototypeOf(TextField.prototype, View.prototype) Object.setPrototypeOf(TextField.prototype, View.prototype)

Просмотреть файл

@ -1,14 +1,14 @@
'use strict' 'use strict'
const electron = require('electron') const electron = require('electron')
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
const {TopLevelWindow} = process.atomBinding('top_level_window') const { TopLevelWindow } = process.atomBinding('top_level_window')
Object.setPrototypeOf(TopLevelWindow.prototype, EventEmitter.prototype) Object.setPrototypeOf(TopLevelWindow.prototype, EventEmitter.prototype)
TopLevelWindow.prototype._init = function () { TopLevelWindow.prototype._init = function () {
// Avoid recursive require. // Avoid recursive require.
const {app} = electron const { app } = electron
// Simulate the application menu on platforms other than macOS. // Simulate the application menu on platforms other than macOS.
if (process.platform !== 'darwin') { if (process.platform !== 'darwin') {

Просмотреть файл

@ -1,4 +1,4 @@
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
let nextItemID = 1 let nextItemID = 1
@ -27,7 +27,7 @@ class TouchBar extends EventEmitter {
throw new Error('Must specify options object as first argument') throw new Error('Must specify options object as first argument')
} }
let {items, escapeItem} = options let { items, escapeItem } = options
// FIXME Support array as first argument, remove in 2.0 // FIXME Support array as first argument, remove in 2.0
if (Array.isArray(options)) { if (Array.isArray(options)) {
@ -83,7 +83,7 @@ class TouchBar extends EventEmitter {
} }
_addToWindow (window) { _addToWindow (window) {
const {id} = window const { id } = window
// Already added to window // Already added to window
if (this.windowListeners.hasOwnProperty(id)) return if (this.windowListeners.hasOwnProperty(id)) return
@ -195,7 +195,7 @@ TouchBar.TouchBarButton = class TouchBarButton extends TouchBarItem {
super() super()
if (config == null) config = {} if (config == null) config = {}
this._addImmutableProperty('type', 'button') this._addImmutableProperty('type', 'button')
const {click, icon, iconPosition, label, backgroundColor} = config const { click, icon, iconPosition, label, backgroundColor } = config
this._addLiveProperty('label', label) this._addLiveProperty('label', label)
this._addLiveProperty('backgroundColor', backgroundColor) this._addLiveProperty('backgroundColor', backgroundColor)
this._addLiveProperty('icon', icon) this._addLiveProperty('icon', icon)
@ -213,7 +213,7 @@ TouchBar.TouchBarColorPicker = class TouchBarColorPicker extends TouchBarItem {
super() super()
if (config == null) config = {} if (config == null) config = {}
this._addImmutableProperty('type', 'colorpicker') this._addImmutableProperty('type', 'colorpicker')
const {availableColors, change, selectedColor} = config const { availableColors, change, selectedColor } = config
this._addLiveProperty('availableColors', availableColors) this._addLiveProperty('availableColors', availableColors)
this._addLiveProperty('selectedColor', selectedColor) this._addLiveProperty('selectedColor', selectedColor)
@ -266,7 +266,7 @@ TouchBar.TouchBarSlider = class TouchBarSlider extends TouchBarItem {
super() super()
if (config == null) config = {} if (config == null) config = {}
this._addImmutableProperty('type', 'slider') this._addImmutableProperty('type', 'slider')
const {change, label, minValue, maxValue, value} = config const { change, label, minValue, maxValue, value } = config
this._addLiveProperty('label', label) this._addLiveProperty('label', label)
this._addLiveProperty('minValue', minValue) this._addLiveProperty('minValue', minValue)
this._addLiveProperty('maxValue', maxValue) this._addLiveProperty('maxValue', maxValue)
@ -294,7 +294,7 @@ TouchBar.TouchBarSegmentedControl = class TouchBarSegmentedControl extends Touch
constructor (config) { constructor (config) {
super() super()
if (config == null) config = {} if (config == null) config = {}
const {segmentStyle, segments, selectedIndex, change, mode} = config const { segmentStyle, segments, selectedIndex, change, mode } = config
this._addImmutableProperty('type', 'segmented_control') this._addImmutableProperty('type', 'segmented_control')
this._addLiveProperty('segmentStyle', segmentStyle) this._addLiveProperty('segmentStyle', segmentStyle)
this._addLiveProperty('segments', segments || []) this._addLiveProperty('segments', segments || [])
@ -314,8 +314,8 @@ TouchBar.TouchBarScrubber = class TouchBarScrubber extends TouchBarItem {
constructor (config) { constructor (config) {
super() super()
if (config == null) config = {} if (config == null) config = {}
const {items, selectedStyle, overlayStyle, showArrowButtons, continuous, mode} = config const { items, selectedStyle, overlayStyle, showArrowButtons, continuous, mode } = config
let {select, highlight} = config let { select, highlight } = config
this._addImmutableProperty('type', 'scrubber') this._addImmutableProperty('type', 'scrubber')
this._addLiveProperty('items', items) this._addLiveProperty('items', items)
this._addLiveProperty('selectedStyle', selectedStyle || null) this._addLiveProperty('selectedStyle', selectedStyle || null)

Просмотреть файл

@ -1,5 +1,5 @@
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
const {Tray} = process.atomBinding('tray') const { Tray } = process.atomBinding('tray')
Object.setPrototypeOf(Tray.prototype, EventEmitter.prototype) Object.setPrototypeOf(Tray.prototype, EventEmitter.prototype)

Просмотреть файл

@ -1,7 +1,7 @@
'use strict' 'use strict'
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
const {View} = process.atomBinding('view') const { View } = process.atomBinding('view')
Object.setPrototypeOf(View.prototype, EventEmitter.prototype) Object.setPrototypeOf(View.prototype, EventEmitter.prototype)

Просмотреть файл

@ -2,8 +2,8 @@
const electron = require('electron') const electron = require('electron')
const {View} = electron const { View } = electron
const {WebContentsView} = process.atomBinding('web_contents_view') const { WebContentsView } = process.atomBinding('web_contents_view')
Object.setPrototypeOf(WebContentsView.prototype, View.prototype) Object.setPrototypeOf(WebContentsView.prototype, View.prototype)

Просмотреть файл

@ -1,10 +1,10 @@
'use strict' 'use strict'
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
const electron = require('electron') const electron = require('electron')
const path = require('path') const path = require('path')
const url = require('url') const url = require('url')
const {app, ipcMain, session, NavigationController, deprecate} = electron const { app, ipcMain, session, NavigationController, deprecate } = electron
const errorUtils = require('../../common/error-utils') const errorUtils = require('../../common/error-utils')
@ -90,7 +90,7 @@ const defaultPrintingSetting = {
// JavaScript implementations of WebContents. // JavaScript implementations of WebContents.
const binding = process.atomBinding('web_contents') const binding = process.atomBinding('web_contents')
const {WebContents} = binding const { WebContents } = binding
Object.setPrototypeOf(NavigationController.prototype, EventEmitter.prototype) Object.setPrototypeOf(NavigationController.prototype, EventEmitter.prototype)
Object.setPrototypeOf(WebContents.prototype, NavigationController.prototype) Object.setPrototypeOf(WebContents.prototype, NavigationController.prototype)
@ -216,7 +216,7 @@ WebContents.prototype.loadFile = function (filePath, options = {}) {
if (typeof filePath !== 'string') { if (typeof filePath !== 'string') {
throw new Error('Must pass filePath as a string') throw new Error('Must pass filePath as a string')
} }
const {query, search, hash} = options const { query, search, hash } = options
return this.loadURL(url.format({ return this.loadURL(url.format({
protocol: 'file', protocol: 'file',
@ -285,7 +285,7 @@ WebContents.prototype._init = function () {
} }
// JavaScript wrapper of Debugger. // JavaScript wrapper of Debugger.
const {Debugger} = process.atomBinding('debugger') const { Debugger } = process.atomBinding('debugger')
Object.setPrototypeOf(Debugger.prototype, EventEmitter.prototype) Object.setPrototypeOf(Debugger.prototype, EventEmitter.prototype)

Просмотреть файл

@ -1,15 +1,15 @@
const {app, ipcMain, webContents, BrowserWindow} = require('electron') const { app, ipcMain, webContents, BrowserWindow } = require('electron')
const {getAllWebContents} = process.atomBinding('web_contents') const { getAllWebContents } = process.atomBinding('web_contents')
const renderProcessPreferences = process.atomBinding('render_process_preferences').forAllWebContents() const renderProcessPreferences = process.atomBinding('render_process_preferences').forAllWebContents()
const {Buffer} = require('buffer') const { Buffer } = require('buffer')
const fs = require('fs') const fs = require('fs')
const path = require('path') const path = require('path')
const url = require('url') const url = require('url')
// Mapping between extensionId(hostname) and manifest. // Mapping between extensionId(hostname) and manifest.
const manifestMap = {} // extensionId => manifest const manifestMap = {} // extensionId => manifest
const manifestNameMap = {} // name => manifest const manifestNameMap = {} // name => manifest
const devToolsExtensionNames = new Set() const devToolsExtensionNames = new Set()
const generateExtensionIdFromName = function (name) { const generateExtensionIdFromName = function (name) {
@ -154,7 +154,7 @@ ipcMain.on('CHROME_RUNTIME_CONNECT', function (event, extensionId, connectInfo)
} }
const portId = ++nextId const portId = ++nextId
event.returnValue = {tabId: page.webContents.id, portId: portId} event.returnValue = { tabId: page.webContents.id, portId: portId }
event.sender.once('render-view-deleted', () => { event.sender.once('render-view-deleted', () => {
if (page.webContents.isDestroyed()) return if (page.webContents.isDestroyed()) return
@ -318,7 +318,7 @@ const chromeExtensionHandler = function (request, callback) {
if (err) { if (err) {
// Disabled due to false positive in StandardJS // Disabled due to false positive in StandardJS
// eslint-disable-next-line standard/no-callback-literal // eslint-disable-next-line standard/no-callback-literal
return callback(-6) // FILE_NOT_FOUND return callback(-6) // FILE_NOT_FOUND
} else { } else {
return callback(content) return callback(content)
} }
@ -399,7 +399,7 @@ app.once('ready', function () {
const extensions = {} const extensions = {}
Object.keys(manifestNameMap).forEach(function (name) { Object.keys(manifestNameMap).forEach(function (name) {
const manifest = manifestNameMap[name] const manifest = manifestNameMap[name]
extensions[name] = {name: manifest.name, version: manifest.version} extensions[name] = { name: manifest.name, version: manifest.version }
}) })
return extensions return extensions
} }

Просмотреть файл

@ -1,7 +1,7 @@
'use strict' 'use strict'
const {ipcMain} = require('electron') const { ipcMain } = require('electron')
const {desktopCapturer} = process.atomBinding('desktop_capturer') const { desktopCapturer } = process.atomBinding('desktop_capturer')
const deepEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b) const deepEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b)
@ -65,7 +65,7 @@ desktopCapturer.emit = (event, name, sources) => {
// If the requestsQueue is not empty, start a new request handling. // If the requestsQueue is not empty, start a new request handling.
if (requestsQueue.length > 0) { if (requestsQueue.length > 0) {
const {captureWindow, captureScreen, thumbnailSize} = requestsQueue[0].options const { captureWindow, captureScreen, thumbnailSize } = requestsQueue[0].options
return desktopCapturer.startHandling(captureWindow, captureScreen, thumbnailSize) return desktopCapturer.startHandling(captureWindow, captureScreen, thumbnailSize)
} }
} }

Просмотреть файл

@ -1,6 +1,6 @@
'use strict' 'use strict'
const {ipcMain, webContents} = require('electron') const { ipcMain, webContents } = require('electron')
const parseFeaturesString = require('../common/parse-features-string') const parseFeaturesString = require('../common/parse-features-string')
// Doesn't exist in early initialization. // Doesn't exist in early initialization.
@ -191,7 +191,7 @@ const attachGuest = function (event, embedderFrameId, elementInstanceId, guestIn
if (!guestInstance) { if (!guestInstance) {
return return
} }
const {guest} = guestInstance const { guest } = guestInstance
// If this guest is already attached to an element then remove it // If this guest is already attached to an element then remove it
if (guestInstance.elementInstanceId) { if (guestInstance.elementInstanceId) {

Просмотреть файл

@ -1,7 +1,7 @@
'use strict' 'use strict'
const {BrowserWindow, ipcMain, webContents} = require('electron') const { BrowserWindow, ipcMain, webContents } = require('electron')
const {isSameOrigin} = process.atomBinding('v8_util') const { isSameOrigin } = process.atomBinding('v8_util')
const parseFeaturesString = require('../common/parse-features-string') const parseFeaturesString = require('../common/parse-features-string')
const hasProp = {}.hasOwnProperty const hasProp = {}.hasOwnProperty
@ -52,7 +52,7 @@ const mergeBrowserWindowOptions = function (embedder, options) {
// if parent's visibility is available, that overrides 'show' flag (#12125) // if parent's visibility is available, that overrides 'show' flag (#12125)
const win = BrowserWindow.fromWebContents(embedder.webContents) const win = BrowserWindow.fromWebContents(embedder.webContents)
if (win != null) { if (win != null) {
parentOptions = {...embedder.browserWindowOptions, show: win.isVisible()} parentOptions = { ...embedder.browserWindowOptions, show: win.isVisible() }
} }
// Inherit the original options if it is a BrowserWindow. // Inherit the original options if it is a BrowserWindow.
@ -247,16 +247,16 @@ ipcMain.on('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_OPEN', (event, url, frameName,
const referrer = { url: '', policy: 'default' } const referrer = { url: '', policy: 'default' }
ipcMain.emit('ELECTRON_GUEST_WINDOW_MANAGER_INTERNAL_WINDOW_OPEN', event, ipcMain.emit('ELECTRON_GUEST_WINDOW_MANAGER_INTERNAL_WINDOW_OPEN', event,
url, referrer, frameName, disposition, options, additionalFeatures) url, referrer, frameName, disposition, options, additionalFeatures)
}) })
// Routed window.open messages with fully parsed options // Routed window.open messages with fully parsed options
ipcMain.on('ELECTRON_GUEST_WINDOW_MANAGER_INTERNAL_WINDOW_OPEN', function (event, url, referrer, ipcMain.on('ELECTRON_GUEST_WINDOW_MANAGER_INTERNAL_WINDOW_OPEN', function (event, url, referrer,
frameName, disposition, options, frameName, disposition, options,
additionalFeatures, postData) { additionalFeatures, postData) {
options = mergeBrowserWindowOptions(event.sender, options) options = mergeBrowserWindowOptions(event.sender, options)
event.sender.emit('new-window', event, url, frameName, disposition, options, additionalFeatures, referrer) event.sender.emit('new-window', event, url, frameName, disposition, options, additionalFeatures, referrer)
const {newGuest} = event const { newGuest } = event
if ((event.sender.isGuest() && !event.sender.allowPopups) || event.defaultPrevented) { if ((event.sender.isGuest() && !event.sender.allowPopups) || event.defaultPrevented) {
if (newGuest != null) { if (newGuest != null) {
if (options.webContents === newGuest.webContents) { if (options.webContents === newGuest.webContents) {

Просмотреть файл

@ -1,6 +1,6 @@
'use strict' 'use strict'
const {Buffer} = require('buffer') const { Buffer } = require('buffer')
const fs = require('fs') const fs = require('fs')
const path = require('path') const path = require('path')
const util = require('util') const util = require('util')
@ -58,7 +58,7 @@ process.on('uncaughtException', function (error) {
}) })
// Emit 'exit' event on quit. // Emit 'exit' event on quit.
const {app} = require('electron') const { app } = require('electron')
app.on('quit', function (event, exitCode) { app.on('quit', function (event, exitCode) {
process.emit('exit', exitCode) process.emit('exit', exitCode)

Просмотреть файл

@ -1,11 +1,11 @@
'use strict' 'use strict'
const electron = require('electron') const electron = require('electron')
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
const fs = require('fs') const fs = require('fs')
const v8Util = process.atomBinding('v8_util') const v8Util = process.atomBinding('v8_util')
const {ipcMain, isPromise} = electron const { ipcMain, isPromise } = electron
const objectsRegistry = require('./objects-registry') const objectsRegistry = require('./objects-registry')
const bufferUtils = require('../common/buffer-utils') const bufferUtils = require('../common/buffer-utils')
@ -34,7 +34,7 @@ const getObjectMembers = function (object) {
// Map properties to descriptors. // Map properties to descriptors.
return names.map((name) => { return names.map((name) => {
let descriptor = Object.getOwnPropertyDescriptor(object, name) let descriptor = Object.getOwnPropertyDescriptor(object, name)
let member = {name, enumerable: descriptor.enumerable, writable: false} let member = { name, enumerable: descriptor.enumerable, writable: false }
if (descriptor.get === undefined && typeof object[name] === 'function') { if (descriptor.get === undefined && typeof object[name] === 'function') {
member.type = 'method' member.type = 'method'
} else { } else {
@ -190,7 +190,7 @@ const unwrapArgs = function (sender, contextId, args) {
let ret = {} let ret = {}
Object.defineProperty(ret.constructor, 'name', { value: meta.name }) Object.defineProperty(ret.constructor, 'name', { value: meta.name })
for (const {name, value} of meta.members) { for (const { name, value } of meta.members) {
ret[name] = metaToValue(value) ret[name] = metaToValue(value)
} }
return ret return ret
@ -404,7 +404,7 @@ ipcMain.on('ELECTRON_BROWSER_SANDBOX_LOAD', function (event) {
try { try {
preloadSrc = fs.readFileSync(preloadPath).toString() preloadSrc = fs.readFileSync(preloadPath).toString()
} catch (err) { } catch (err) {
preloadError = {stack: err ? err.stack : (new Error(`Failed to load "${preloadPath}"`)).stack} preloadError = { stack: err ? err.stack : (new Error(`Failed to load "${preloadPath}"`)).stack }
} }
} }
event.returnValue = { event.returnValue = {

Просмотреть файл

@ -1,10 +1,10 @@
'use strict' 'use strict'
const {spawn} = require('child_process') const { spawn } = require('child_process')
const os = require('os') const os = require('os')
const path = require('path') const path = require('path')
const electron = require('electron') const electron = require('electron')
const {app} = process.type === 'browser' ? electron : electron.remote const { app } = process.type === 'browser' ? electron : electron.remote
const binding = process.atomBinding('crash_reporter') const binding = process.atomBinding('crash_reporter')
class CrashReporter { class CrashReporter {

Просмотреть файл

@ -1,11 +1,11 @@
// Common modules, please sort alphabetically // Common modules, please sort alphabetically
module.exports = [ module.exports = [
{name: 'clipboard', file: 'clipboard'}, { name: 'clipboard', file: 'clipboard' },
{name: 'crashReporter', file: 'crash-reporter'}, { name: 'crashReporter', file: 'crash-reporter' },
{name: 'nativeImage', file: 'native-image'}, { name: 'nativeImage', file: 'native-image' },
{name: 'shell', file: 'shell'}, { name: 'shell', file: 'shell' },
// The internal modules, invisible unless you know their names. // The internal modules, invisible unless you know their names.
{name: 'deprecate', file: 'deprecate', private: true}, { name: 'deprecate', file: 'deprecate', private: true },
{name: 'deprecations', file: 'deprecations', private: true}, { name: 'deprecations', file: 'deprecations', private: true },
{name: 'isPromise', file: 'is-promise', private: true} { name: 'isPromise', file: 'is-promise', private: true }
] ]

Просмотреть файл

@ -1,7 +1,7 @@
(function () { (function () {
const asar = process.binding('atom_common_asar') const asar = process.binding('atom_common_asar')
const assert = require('assert') const assert = require('assert')
const {Buffer} = require('buffer') const { Buffer } = require('buffer')
const childProcess = require('child_process') const childProcess = require('child_process')
const path = require('path') const path = require('path')
const util = require('util') const util = require('util')
@ -48,22 +48,22 @@
// Separate asar package's path from full path. // Separate asar package's path from full path.
const splitPath = archivePathOrBuffer => { const splitPath = archivePathOrBuffer => {
// Shortcut for disabled asar. // Shortcut for disabled asar.
if (isAsarDisabled()) return {isAsar: false} if (isAsarDisabled()) return { isAsar: false }
// Check for a bad argument type. // Check for a bad argument type.
let archivePath = archivePathOrBuffer let archivePath = archivePathOrBuffer
if (Buffer.isBuffer(archivePathOrBuffer)) { if (Buffer.isBuffer(archivePathOrBuffer)) {
archivePath = archivePathOrBuffer.toString() archivePath = archivePathOrBuffer.toString()
} }
if (typeof archivePath !== 'string') return {isAsar: false} if (typeof archivePath !== 'string') return { isAsar: false }
if (archivePath.endsWith(ASAR_EXTENSION)) { if (archivePath.endsWith(ASAR_EXTENSION)) {
return {isAsar: true, asarPath: archivePath, filePath: ''} return { isAsar: true, asarPath: archivePath, filePath: '' }
} }
archivePath = path.normalize(archivePath) archivePath = path.normalize(archivePath)
const index = archivePath.lastIndexOf(`${ASAR_EXTENSION}${path.sep}`) const index = archivePath.lastIndexOf(`${ASAR_EXTENSION}${path.sep}`)
if (index === -1) return {isAsar: false} if (index === -1) return { isAsar: false }
// E.g. for "//some/path/to/archive.asar/then/internal.file"... // E.g. for "//some/path/to/archive.asar/then/internal.file"...
return { return {
@ -85,7 +85,7 @@
const msec = (date) => (date || fakeTime).getTime() const msec = (date) => (date || fakeTime).getTime()
const asarStatsToFsStats = function (stats) { const asarStatsToFsStats = function (stats) {
const {Stats, constants} = require('fs') const { Stats, constants } = require('fs')
let mode = constants.S_IROTH ^ constants.S_IRGRP ^ constants.S_IRUSR ^ constants.S_IWUSR let mode = constants.S_IROTH ^ constants.S_IRGRP ^ constants.S_IRUSR ^ constants.S_IWUSR
@ -98,20 +98,20 @@
} }
return new Stats( return new Stats(
1, // dev 1, // dev
mode, // mode mode, // mode
1, // nlink 1, // nlink
uid, uid,
gid, gid,
0, // rdev 0, // rdev
undefined, // blksize undefined, // blksize
++nextInode, // ino ++nextInode, // ino
stats.size, stats.size,
undefined, // blocks, undefined, // blocks,
msec(stats.atime), // atim_msec msec(stats.atime), // atim_msec
msec(stats.mtime), // mtim_msec msec(stats.mtime), // mtim_msec
msec(stats.ctime), // ctim_msec msec(stats.ctime), // ctim_msec
msec(stats.birthtime) // birthtim_msec msec(stats.birthtime) // birthtim_msec
) )
} }
@ -122,7 +122,7 @@
INVALID_ARCHIVE: 'INVALID_ARCHIVE' INVALID_ARCHIVE: 'INVALID_ARCHIVE'
} }
const createError = (errorType, {asarPath, filePath} = {}) => { const createError = (errorType, { asarPath, filePath } = {}) => {
let error let error
switch (errorType) { switch (errorType) {
case AsarError.NOT_FOUND: case AsarError.NOT_FOUND:
@ -154,14 +154,14 @@
const old = module[name] const old = module[name]
module[name] = function () { module[name] = function () {
const pathArgument = arguments[pathArgumentIndex] const pathArgument = arguments[pathArgumentIndex]
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return old.apply(this, arguments) if (!isAsar) return old.apply(this, arguments)
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) throw createError(AsarError.INVALID_ARCHIVE, {asarPath}) if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath })
const newPath = archive.copyFileOut(filePath) const newPath = archive.copyFileOut(filePath)
if (!newPath) throw createError(AsarError.NOT_FOUND, {asarPath, filePath}) if (!newPath) throw createError(AsarError.NOT_FOUND, { asarPath, filePath })
arguments[pathArgumentIndex] = newPath arguments[pathArgumentIndex] = newPath
return old.apply(this, arguments) return old.apply(this, arguments)
@ -173,7 +173,7 @@
const old = module[name] const old = module[name]
module[name] = function () { module[name] = function () {
const pathArgument = arguments[pathArgumentIndex] const pathArgument = arguments[pathArgumentIndex]
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return old.apply(this, arguments) if (!isAsar) return old.apply(this, arguments)
const callback = arguments[arguments.length - 1] const callback = arguments[arguments.length - 1]
@ -183,14 +183,14 @@
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) { if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, {asarPath}) const error = createError(AsarError.INVALID_ARCHIVE, { asarPath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
const newPath = archive.copyFileOut(filePath) const newPath = archive.copyFileOut(filePath)
if (!newPath) { if (!newPath) {
const error = createError(AsarError.NOT_FOUND, {asarPath, filePath}) const error = createError(AsarError.NOT_FOUND, { asarPath, filePath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
@ -202,17 +202,17 @@
if (old[util.promisify.custom]) { if (old[util.promisify.custom]) {
module[name][util.promisify.custom] = function () { module[name][util.promisify.custom] = function () {
const pathArgument = arguments[pathArgumentIndex] const pathArgument = arguments[pathArgumentIndex]
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return old[util.promisify.custom].apply(this, arguments) if (!isAsar) return old[util.promisify.custom].apply(this, arguments)
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) { if (!archive) {
return Promise.reject(createError(AsarError.INVALID_ARCHIVE, {asarPath})) return Promise.reject(createError(AsarError.INVALID_ARCHIVE, { asarPath }))
} }
const newPath = archive.copyFileOut(filePath) const newPath = archive.copyFileOut(filePath)
if (!newPath) { if (!newPath) {
return Promise.reject(createError(AsarError.NOT_FOUND, {asarPath, filePath})) return Promise.reject(createError(AsarError.NOT_FOUND, { asarPath, filePath }))
} }
arguments[pathArgumentIndex] = newPath arguments[pathArgumentIndex] = newPath
@ -235,35 +235,35 @@
fs.writeSync(logFDs[asarPath], `${offset}: ${filePath}\n`) fs.writeSync(logFDs[asarPath], `${offset}: ${filePath}\n`)
} }
const {lstatSync} = fs const { lstatSync } = fs
fs.lstatSync = pathArgument => { fs.lstatSync = pathArgument => {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return lstatSync(pathArgument) if (!isAsar) return lstatSync(pathArgument)
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) throw createError(AsarError.INVALID_ARCHIVE, {asarPath}) if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath })
const stats = archive.stat(filePath) const stats = archive.stat(filePath)
if (!stats) throw createError(AsarError.NOT_FOUND, {asarPath, filePath}) if (!stats) throw createError(AsarError.NOT_FOUND, { asarPath, filePath })
return asarStatsToFsStats(stats) return asarStatsToFsStats(stats)
} }
const {lstat} = fs const { lstat } = fs
fs.lstat = (pathArgument, callback) => { fs.lstat = (pathArgument, callback) => {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return lstat(pathArgument, callback) if (!isAsar) return lstat(pathArgument, callback)
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) { if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, {asarPath}) const error = createError(AsarError.INVALID_ARCHIVE, { asarPath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
const stats = archive.stat(filePath) const stats = archive.stat(filePath)
if (!stats) { if (!stats) {
const error = createError(AsarError.NOT_FOUND, {asarPath, filePath}) const error = createError(AsarError.NOT_FOUND, { asarPath, filePath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
@ -272,27 +272,27 @@
nextTick(callback, [null, fsStats]) nextTick(callback, [null, fsStats])
} }
const {statSync} = fs const { statSync } = fs
fs.statSync = pathArgument => { fs.statSync = pathArgument => {
const {isAsar} = splitPath(pathArgument) const { isAsar } = splitPath(pathArgument)
if (!isAsar) return statSync(pathArgument) if (!isAsar) return statSync(pathArgument)
// Do not distinguish links for now. // Do not distinguish links for now.
return fs.lstatSync(pathArgument) return fs.lstatSync(pathArgument)
} }
const {stat} = fs const { stat } = fs
fs.stat = (pathArgument, callback) => { fs.stat = (pathArgument, callback) => {
const {isAsar} = splitPath(pathArgument) const { isAsar } = splitPath(pathArgument)
if (!isAsar) return stat(pathArgument, callback) if (!isAsar) return stat(pathArgument, callback)
// Do not distinguish links for now. // Do not distinguish links for now.
process.nextTick(() => fs.lstat(pathArgument, callback)) process.nextTick(() => fs.lstat(pathArgument, callback))
} }
const {statSyncNoException} = fs const { statSyncNoException } = fs
fs.statSyncNoException = pathArgument => { fs.statSyncNoException = pathArgument => {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return statSyncNoException(pathArgument) if (!isAsar) return statSyncNoException(pathArgument)
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
@ -304,44 +304,44 @@
return asarStatsToFsStats(stats) return asarStatsToFsStats(stats)
} }
const {realpathSync} = fs const { realpathSync } = fs
fs.realpathSync = function (pathArgument) { fs.realpathSync = function (pathArgument) {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return realpathSync.apply(this, arguments) if (!isAsar) return realpathSync.apply(this, arguments)
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) { if (!archive) {
throw createError(AsarError.INVALID_ARCHIVE, {asarPath}) throw createError(AsarError.INVALID_ARCHIVE, { asarPath })
} }
const fileRealPath = archive.realpath(filePath) const fileRealPath = archive.realpath(filePath)
if (fileRealPath === false) { if (fileRealPath === false) {
throw createError(AsarError.NOT_FOUND, {asarPath, filePath}) throw createError(AsarError.NOT_FOUND, { asarPath, filePath })
} }
return path.join(realpathSync(asarPath), fileRealPath) return path.join(realpathSync(asarPath), fileRealPath)
} }
fs.realpathSync.native = function (pathArgument) { fs.realpathSync.native = function (pathArgument) {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return realpathSync.native.apply(this, arguments) if (!isAsar) return realpathSync.native.apply(this, arguments)
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) { if (!archive) {
throw createError(AsarError.INVALID_ARCHIVE, {asarPath}) throw createError(AsarError.INVALID_ARCHIVE, { asarPath })
} }
const fileRealPath = archive.realpath(filePath) const fileRealPath = archive.realpath(filePath)
if (fileRealPath === false) { if (fileRealPath === false) {
throw createError(AsarError.NOT_FOUND, {asarPath, filePath}) throw createError(AsarError.NOT_FOUND, { asarPath, filePath })
} }
return path.join(realpathSync.native(asarPath), fileRealPath) return path.join(realpathSync.native(asarPath), fileRealPath)
} }
const {realpath} = fs const { realpath } = fs
fs.realpath = function (pathArgument, cache, callback) { fs.realpath = function (pathArgument, cache, callback) {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return realpath.apply(this, arguments) if (!isAsar) return realpath.apply(this, arguments)
if (typeof cache === 'function') { if (typeof cache === 'function') {
@ -351,14 +351,14 @@
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) { if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, {asarPath}) const error = createError(AsarError.INVALID_ARCHIVE, { asarPath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
const fileRealPath = archive.realpath(filePath) const fileRealPath = archive.realpath(filePath)
if (fileRealPath === false) { if (fileRealPath === false) {
const error = createError(AsarError.NOT_FOUND, {asarPath, filePath}) const error = createError(AsarError.NOT_FOUND, { asarPath, filePath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
@ -374,7 +374,7 @@
} }
fs.realpath.native = function (pathArgument, cache, callback) { fs.realpath.native = function (pathArgument, cache, callback) {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return realpath.native.apply(this, arguments) if (!isAsar) return realpath.native.apply(this, arguments)
if (typeof cache === 'function') { if (typeof cache === 'function') {
@ -384,14 +384,14 @@
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) { if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, {asarPath}) const error = createError(AsarError.INVALID_ARCHIVE, { asarPath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
const fileRealPath = archive.realpath(filePath) const fileRealPath = archive.realpath(filePath)
if (fileRealPath === false) { if (fileRealPath === false) {
const error = createError(AsarError.NOT_FOUND, {asarPath, filePath}) const error = createError(AsarError.NOT_FOUND, { asarPath, filePath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
@ -406,14 +406,14 @@
}) })
} }
const {exists} = fs const { exists } = fs
fs.exists = (pathArgument, callback) => { fs.exists = (pathArgument, callback) => {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return exists(pathArgument, callback) if (!isAsar) return exists(pathArgument, callback)
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) { if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, {asarPath}) const error = createError(AsarError.INVALID_ARCHIVE, { asarPath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
@ -423,21 +423,21 @@
} }
fs.exists[util.promisify.custom] = pathArgument => { fs.exists[util.promisify.custom] = pathArgument => {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return exists[util.promisify.custom](pathArgument) if (!isAsar) return exists[util.promisify.custom](pathArgument)
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) { if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, {asarPath}) const error = createError(AsarError.INVALID_ARCHIVE, { asarPath })
return Promise.reject(error) return Promise.reject(error)
} }
return Promise.resolve(archive.stat(filePath) !== false) return Promise.resolve(archive.stat(filePath) !== false)
} }
const {existsSync} = fs const { existsSync } = fs
fs.existsSync = pathArgument => { fs.existsSync = pathArgument => {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return existsSync(pathArgument) if (!isAsar) return existsSync(pathArgument)
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
@ -446,9 +446,9 @@
return archive.stat(filePath) !== false return archive.stat(filePath) !== false
} }
const {access} = fs const { access } = fs
fs.access = function (pathArgument, mode, callback) { fs.access = function (pathArgument, mode, callback) {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return access.apply(this, arguments) if (!isAsar) return access.apply(this, arguments)
if (typeof mode === 'function') { if (typeof mode === 'function') {
@ -458,14 +458,14 @@
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) { if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, {asarPath}) const error = createError(AsarError.INVALID_ARCHIVE, { asarPath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
const info = archive.getFileInfo(filePath) const info = archive.getFileInfo(filePath)
if (!info) { if (!info) {
const error = createError(AsarError.NOT_FOUND, {asarPath, filePath}) const error = createError(AsarError.NOT_FOUND, { asarPath, filePath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
@ -477,13 +477,13 @@
const stats = archive.stat(filePath) const stats = archive.stat(filePath)
if (!stats) { if (!stats) {
const error = createError(AsarError.NOT_FOUND, {asarPath, filePath}) const error = createError(AsarError.NOT_FOUND, { asarPath, filePath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
if (mode & fs.constants.W_OK) { if (mode & fs.constants.W_OK) {
const error = createError(AsarError.NO_ACCESS, {asarPath, filePath}) const error = createError(AsarError.NO_ACCESS, { asarPath, filePath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
@ -491,21 +491,21 @@
nextTick(callback) nextTick(callback)
} }
const {accessSync} = fs const { accessSync } = fs
fs.accessSync = function (pathArgument, mode) { fs.accessSync = function (pathArgument, mode) {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return accessSync.apply(this, arguments) if (!isAsar) return accessSync.apply(this, arguments)
if (mode == null) mode = fs.constants.F_OK if (mode == null) mode = fs.constants.F_OK
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) { if (!archive) {
throw createError(AsarError.INVALID_ARCHIVE, {asarPath}) throw createError(AsarError.INVALID_ARCHIVE, { asarPath })
} }
const info = archive.getFileInfo(filePath) const info = archive.getFileInfo(filePath)
if (!info) { if (!info) {
throw createError(AsarError.NOT_FOUND, {asarPath, filePath}) throw createError(AsarError.NOT_FOUND, { asarPath, filePath })
} }
if (info.unpacked) { if (info.unpacked) {
@ -515,17 +515,17 @@
const stats = archive.stat(filePath) const stats = archive.stat(filePath)
if (!stats) { if (!stats) {
throw createError(AsarError.NOT_FOUND, {asarPath, filePath}) throw createError(AsarError.NOT_FOUND, { asarPath, filePath })
} }
if (mode & fs.constants.W_OK) { if (mode & fs.constants.W_OK) {
throw createError(AsarError.NO_ACCESS, {asarPath, filePath}) throw createError(AsarError.NO_ACCESS, { asarPath, filePath })
} }
} }
const {readFile} = fs const { readFile } = fs
fs.readFile = function (pathArgument, options, callback) { fs.readFile = function (pathArgument, options, callback) {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return readFile.apply(this, arguments) if (!isAsar) return readFile.apply(this, arguments)
if (typeof options === 'function') { if (typeof options === 'function') {
@ -539,17 +539,17 @@
throw new TypeError('Bad arguments') throw new TypeError('Bad arguments')
} }
const {encoding} = options const { encoding } = options
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) { if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, {asarPath}) const error = createError(AsarError.INVALID_ARCHIVE, { asarPath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
const info = archive.getFileInfo(filePath) const info = archive.getFileInfo(filePath)
if (!info) { if (!info) {
const error = createError(AsarError.NOT_FOUND, {asarPath, filePath}) const error = createError(AsarError.NOT_FOUND, { asarPath, filePath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
@ -567,7 +567,7 @@
const buffer = Buffer.alloc(info.size) const buffer = Buffer.alloc(info.size)
const fd = archive.getFd() const fd = archive.getFd()
if (!(fd >= 0)) { if (!(fd >= 0)) {
const error = createError(AsarError.NOT_FOUND, {asarPath, filePath}) const error = createError(AsarError.NOT_FOUND, { asarPath, filePath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
@ -578,16 +578,16 @@
}) })
} }
const {readFileSync} = fs const { readFileSync } = fs
fs.readFileSync = function (pathArgument, options) { fs.readFileSync = function (pathArgument, options) {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return readFileSync.apply(this, arguments) if (!isAsar) return readFileSync.apply(this, arguments)
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) throw createError(AsarError.INVALID_ARCHIVE, {asarPath}) if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath })
const info = archive.getFileInfo(filePath) const info = archive.getFileInfo(filePath)
if (!info) throw createError(AsarError.NOT_FOUND, {asarPath, filePath}) if (!info) throw createError(AsarError.NOT_FOUND, { asarPath, filePath })
if (info.size === 0) return (options) ? '' : Buffer.alloc(0) if (info.size === 0) return (options) ? '' : Buffer.alloc(0)
if (info.unpacked) { if (info.unpacked) {
@ -603,31 +603,31 @@
throw new TypeError('Bad arguments') throw new TypeError('Bad arguments')
} }
const {encoding} = options const { encoding } = options
const buffer = Buffer.alloc(info.size) const buffer = Buffer.alloc(info.size)
const fd = archive.getFd() const fd = archive.getFd()
if (!(fd >= 0)) throw createError(AsarError.NOT_FOUND, {asarPath, filePath}) if (!(fd >= 0)) throw createError(AsarError.NOT_FOUND, { asarPath, filePath })
logASARAccess(asarPath, filePath, info.offset) logASARAccess(asarPath, filePath, info.offset)
fs.readSync(fd, buffer, 0, info.size, info.offset) fs.readSync(fd, buffer, 0, info.size, info.offset)
return (encoding) ? buffer.toString(encoding) : buffer return (encoding) ? buffer.toString(encoding) : buffer
} }
const {readdir} = fs const { readdir } = fs
fs.readdir = function (pathArgument, callback) { fs.readdir = function (pathArgument, callback) {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return readdir.apply(this, arguments) if (!isAsar) return readdir.apply(this, arguments)
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) { if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, {asarPath}) const error = createError(AsarError.INVALID_ARCHIVE, { asarPath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
const files = archive.readdir(filePath) const files = archive.readdir(filePath)
if (!files) { if (!files) {
const error = createError(AsarError.NOT_FOUND, {asarPath, filePath}) const error = createError(AsarError.NOT_FOUND, { asarPath, filePath })
nextTick(callback, [error]) nextTick(callback, [error])
return return
} }
@ -635,27 +635,27 @@
nextTick(callback, [null, files]) nextTick(callback, [null, files])
} }
const {readdirSync} = fs const { readdirSync } = fs
fs.readdirSync = function (pathArgument) { fs.readdirSync = function (pathArgument) {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return readdirSync.apply(this, arguments) if (!isAsar) return readdirSync.apply(this, arguments)
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
if (!archive) { if (!archive) {
throw createError(AsarError.INVALID_ARCHIVE, {asarPath}) throw createError(AsarError.INVALID_ARCHIVE, { asarPath })
} }
const files = archive.readdir(filePath) const files = archive.readdir(filePath)
if (!files) { if (!files) {
throw createError(AsarError.NOT_FOUND, {asarPath, filePath}) throw createError(AsarError.NOT_FOUND, { asarPath, filePath })
} }
return files return files
} }
const {internalModuleReadJSON} = process.binding('fs') const { internalModuleReadJSON } = process.binding('fs')
process.binding('fs').internalModuleReadJSON = pathArgument => { process.binding('fs').internalModuleReadJSON = pathArgument => {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return internalModuleReadJSON(pathArgument) if (!isAsar) return internalModuleReadJSON(pathArgument)
const archive = getOrCreateArchive(asarPath) const archive = getOrCreateArchive(asarPath)
@ -666,7 +666,7 @@
if (info.size === 0) return '' if (info.size === 0) return ''
if (info.unpacked) { if (info.unpacked) {
const realPath = archive.copyFileOut(filePath) const realPath = archive.copyFileOut(filePath)
return fs.readFileSync(realPath, {encoding: 'utf8'}) return fs.readFileSync(realPath, { encoding: 'utf8' })
} }
const buffer = Buffer.alloc(info.size) const buffer = Buffer.alloc(info.size)
@ -678,9 +678,9 @@
return buffer.toString('utf8') return buffer.toString('utf8')
} }
const {internalModuleStat} = process.binding('fs') const { internalModuleStat } = process.binding('fs')
process.binding('fs').internalModuleStat = pathArgument => { process.binding('fs').internalModuleStat = pathArgument => {
const {isAsar, asarPath, filePath} = splitPath(pathArgument) const { isAsar, asarPath, filePath } = splitPath(pathArgument)
if (!isAsar) return internalModuleStat(pathArgument) if (!isAsar) return internalModuleStat(pathArgument)
// -ENOENT // -ENOENT
@ -699,14 +699,14 @@
// This is to work around the recursive looping bug of mkdirp since it is // This is to work around the recursive looping bug of mkdirp since it is
// widely used. // widely used.
if (process.platform === 'win32') { if (process.platform === 'win32') {
const {mkdir} = fs const { mkdir } = fs
fs.mkdir = (pathArgument, mode, callback) => { fs.mkdir = (pathArgument, mode, callback) => {
if (typeof mode === 'function') { if (typeof mode === 'function') {
callback = mode callback = mode
mode = undefined mode = undefined
} }
const {isAsar, filePath} = splitPath(pathArgument) const { isAsar, filePath } = splitPath(pathArgument)
if (isAsar && filePath.length > 0) { if (isAsar && filePath.length > 0) {
const error = createError(AsarError.NOT_DIR) const error = createError(AsarError.NOT_DIR)
nextTick(callback, [error]) nextTick(callback, [error])
@ -716,9 +716,9 @@
mkdir(pathArgument, mode, callback) mkdir(pathArgument, mode, callback)
} }
const {mkdirSync} = fs const { mkdirSync } = fs
fs.mkdirSync = function (pathArgument, mode) { fs.mkdirSync = function (pathArgument, mode) {
const {isAsar, filePath} = splitPath(pathArgument) const { isAsar, filePath } = splitPath(pathArgument)
if (isAsar && filePath.length) throw createError(AsarError.NOT_DIR) if (isAsar && filePath.length) throw createError(AsarError.NOT_DIR)
return mkdirSync(pathArgument, mode) return mkdirSync(pathArgument, mode)
} }
@ -729,7 +729,7 @@
// called by `childProcess.{exec,execSync}`, causing // called by `childProcess.{exec,execSync}`, causing
// Electron to consider the full command as a single path // Electron to consider the full command as a single path
// to an archive. // to an archive.
const {exec, execSync} = childProcess const { exec, execSync } = childProcess
childProcess.exec = invokeWithNoAsar(exec) childProcess.exec = invokeWithNoAsar(exec)
childProcess.exec[util.promisify.custom] = invokeWithNoAsar(exec[util.promisify.custom]) childProcess.exec[util.promisify.custom] = invokeWithNoAsar(exec[util.promisify.custom])
childProcess.execSync = invokeWithNoAsar(execSync) childProcess.execSync = invokeWithNoAsar(execSync)

Просмотреть файл

@ -43,7 +43,7 @@ if (process.type === 'browser') {
if (process.platform === 'win32') { if (process.platform === 'win32') {
// Always returns EOF for stdin stream. // Always returns EOF for stdin stream.
const {Readable} = require('stream') const { Readable } = require('stream')
const stdin = new Readable() const stdin = new Readable()
stdin.push(null) stdin.push(null)
process.__defineGetter__('stdin', function () { process.__defineGetter__('stdin', function () {

Просмотреть файл

@ -2,7 +2,7 @@
'use strict' 'use strict'
const {send, sendSync} = binding const { send, sendSync } = binding
const ipcRenderer = { const ipcRenderer = {
send (...args) { send (...args) {
@ -18,7 +18,7 @@ const ipcRenderer = {
once () {} once () {}
} }
let {guestInstanceId, hiddenPage, openerId, nativeWindowOpen} = binding let { guestInstanceId, hiddenPage, openerId, nativeWindowOpen } = binding
if (guestInstanceId != null) guestInstanceId = parseInt(guestInstanceId) if (guestInstanceId != null) guestInstanceId = parseInt(guestInstanceId)
if (openerId != null) openerId = parseInt(openerId) if (openerId != null) openerId = parseInt(openerId)

Просмотреть файл

@ -1,4 +1,4 @@
const {ipcRenderer, nativeImage} = require('electron') const { ipcRenderer, nativeImage } = require('electron')
const includes = [].includes const includes = [].includes
let currentId = 0 let currentId = 0

Просмотреть файл

@ -5,11 +5,11 @@ const moduleList = require('../module-list')
common.defineProperties(exports) common.defineProperties(exports)
for (const { for (const {
name, name,
file, file,
enabled = true, enabled = true,
private: isPrivate = false private: isPrivate = false
} of moduleList) { } of moduleList) {
if (!enabled) { if (!enabled) {
continue continue
} }

Просмотреть файл

@ -8,8 +8,8 @@ module.exports = [
file: 'desktop-capturer', file: 'desktop-capturer',
enabled: features.isDesktopCapturerEnabled() enabled: features.isDesktopCapturerEnabled()
}, },
{name: 'ipcRenderer', file: 'ipc-renderer', enabled: true}, { name: 'ipcRenderer', file: 'ipc-renderer', enabled: true },
{name: 'remote', file: 'remote', enabled: true}, { name: 'remote', file: 'remote', enabled: true },
{name: 'screen', file: 'screen', enabled: true}, { name: 'screen', file: 'screen', enabled: true },
{name: 'webFrame', file: 'web-frame', enabled: true} { name: 'webFrame', file: 'web-frame', enabled: true }
] ]

Просмотреть файл

@ -1,7 +1,7 @@
'use strict' 'use strict'
const v8Util = process.atomBinding('v8_util') const v8Util = process.atomBinding('v8_util')
const {ipcRenderer, isPromise} = require('electron') const { ipcRenderer, isPromise } = require('electron')
const resolvePromise = Promise.resolve.bind(Promise) const resolvePromise = Promise.resolve.bind(Promise)
const CallbacksRegistry = require('../callbacks-registry') const CallbacksRegistry = require('../callbacks-registry')
@ -127,7 +127,7 @@ function setObjectMembers (ref, object, metaId, members) {
let descriptorFunction = proxyFunctionProperties(remoteMemberFunction, metaId, member.name) let descriptorFunction = proxyFunctionProperties(remoteMemberFunction, metaId, member.name)
descriptor.get = () => { descriptor.get = () => {
descriptorFunction.ref = ref // The member should reference its object. descriptorFunction.ref = ref // The member should reference its object.
return descriptorFunction return descriptorFunction
} }
// Enable monkey-patch the method // Enable monkey-patch the method
@ -214,7 +214,7 @@ function metaToValue (meta) {
value: () => meta.value, value: () => meta.value,
array: () => meta.members.map((member) => metaToValue(member)), array: () => meta.members.map((member) => metaToValue(member)),
buffer: () => bufferUtils.metaToBuffer(meta.value), buffer: () => bufferUtils.metaToBuffer(meta.value),
promise: () => resolvePromise({then: metaToValue(meta.then)}), promise: () => resolvePromise({ then: metaToValue(meta.then) }),
error: () => metaToPlainObject(meta), error: () => metaToPlainObject(meta),
date: () => new Date(meta.value), date: () => new Date(meta.value),
exception: () => { throw metaToException(meta) } exception: () => { throw metaToException(meta) }
@ -261,7 +261,7 @@ function metaToValue (meta) {
function metaToPlainObject (meta) { function metaToPlainObject (meta) {
const obj = (() => meta.type === 'error' ? new Error() : {})() const obj = (() => meta.type === 'error' ? new Error() : {})()
for (let i = 0; i < meta.members.length; i++) { for (let i = 0; i < meta.members.length; i++) {
let {name, value} = meta.members[i] let { name, value } = meta.members[i]
obj[name] = value obj[name] = value
} }
return obj return obj
@ -350,7 +350,7 @@ const addBuiltinProperty = (name) => {
const browserModules = const browserModules =
require('../../common/api/module-list').concat( require('../../common/api/module-list').concat(
require('../../browser/api/module-list')) require('../../browser/api/module-list'))
// And add a helper receiver for each one. // And add a helper receiver for each one.
browserModules browserModules

Просмотреть файл

@ -1,7 +1,7 @@
'use strict' 'use strict'
const {EventEmitter} = require('events') const { EventEmitter } = require('events')
const {webFrame, WebFrame} = process.atomBinding('web_frame') const { webFrame, WebFrame } = process.atomBinding('web_frame')
// WebFrame is an EventEmitter. // WebFrame is an EventEmitter.
Object.setPrototypeOf(WebFrame.prototype, EventEmitter.prototype) Object.setPrototypeOf(WebFrame.prototype, EventEmitter.prototype)

Просмотреть файл

@ -1,4 +1,4 @@
const {ipcRenderer} = require('electron') const { ipcRenderer } = require('electron')
const Event = require('./extensions/event') const Event = require('./extensions/event')
const url = require('url') const url = require('url')
@ -99,14 +99,14 @@ exports.injectTo = function (extensionId, isBackgroundPage, context) {
// Parse the optional args. // Parse the optional args.
let targetExtensionId = extensionId let targetExtensionId = extensionId
let connectInfo = {name: ''} let connectInfo = { name: '' }
if (args.length === 1) { if (args.length === 1) {
connectInfo = args[0] connectInfo = args[0]
} else if (args.length === 2) { } else if (args.length === 2) {
[targetExtensionId, connectInfo] = args [targetExtensionId, connectInfo] = args
} }
const {tabId, portId} = ipcRenderer.sendSync('CHROME_RUNTIME_CONNECT', targetExtensionId, connectInfo) const { tabId, portId } = ipcRenderer.sendSync('CHROME_RUNTIME_CONNECT', targetExtensionId, connectInfo)
return new Port(tabId, portId, extensionId, connectInfo.name) return new Port(tabId, portId, extensionId, connectInfo.name)
}, },

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше