Merge branch 'document-fixes-4' of https://github.com/preco21/electron into preco21-document-fixes-4

This commit is contained in:
Cheng Zhao 2016-05-11 09:23:52 +09:00
Родитель d0b39bc4fe ebc7f5cba0
Коммит 1d6f05c9bb
37 изменённых файлов: 249 добавлений и 233 удалений

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

@ -6,7 +6,7 @@ The following example shows how to quit the application when the last window is
closed:
```javascript
const { app } = require('electron');
const {app} = require('electron');
app.on('window-all-closed', () => {
app.quit();
});
@ -175,8 +175,8 @@ certificate you should prevent the default behavior with
`event.preventDefault()` and call `callback(true)`.
```javascript
app.on('certificate-error', function(event, webContents, url, error, certificate, callback) {
if (url == "https://github.com") {
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
if (url === 'https://github.com') {
// Verification logic.
event.preventDefault();
callback(true);
@ -206,10 +206,10 @@ and `callback` needs to be called with an entry filtered from the list. Using
certificate from the store.
```javascript
app.on('select-client-certificate', function(event, webContents, url, list, callback) {
app.on('select-client-certificate', (event, webContents, url, list, callback) => {
event.preventDefault();
callback(list[0]);
})
});
```
### Event: 'login'
@ -240,7 +240,7 @@ should prevent the default behavior with `event.preventDefault()` and call
app.on('login', (event, webContents, request, authInfo, callback) => {
event.preventDefault();
callback('username', 'secret');
})
});
```
### Event: 'gpu-process-crashed'

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

@ -4,12 +4,12 @@
```javascript
// In the main process.
const { BrowserWindow } = require('electron');
const {BrowserWindow} = require('electron');
// Or in the renderer process.
const { BrowserWindow } = require('electron').remote;
const {BrowserWindow} = require('electron').remote;
let win = new BrowserWindow({ width: 800, height: 600, show: false });
let win = new BrowserWindow({width: 800, height: 600, show: false});
win.on('closed', () => {
win = null;
});
@ -220,7 +220,7 @@ reloaded. In Electron, returning an empty string or `false` would cancel the
close. For example:
```javascript
window.onbeforeunload = function(e) {
window.onbeforeunload = (e) => {
console.log('I do not want to be closed');
// Unlike usual browsers, in which a string should be returned and the user is
@ -392,7 +392,7 @@ Objects created with `new BrowserWindow` have the following properties:
```javascript
// In this example `win` is our instance
var win = new BrowserWindow({ width: 800, height: 600 });
let win = new BrowserWindow({width: 800, height: 600});
```
### `win.webContents`
@ -689,7 +689,7 @@ attached just below the window frame, but you may want to display them beneath
a HTML-rendered toolbar. For example:
```javascript
var toolbarRect = document.getElementById('toolbar').getBoundingClientRect();
let toolbarRect = document.getElementById('toolbar').getBoundingClientRect();
win.setSheetOffset(toolbarRect.height);
```

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

@ -7,7 +7,7 @@ your app's main script before the [ready][ready] event of the [app][app] module
is emitted:
```javascript
const { app } = require('electron');
const {app} = require('electron');
app.commandLine.appendSwitch('remote-debugging-port', '8315');
app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1');
@ -109,7 +109,7 @@ Enables net log events to be saved and writes them to `path`.
## --ssl-version-fallback-min=`version`
Sets the minimum SSL/TLS version ("tls1", "tls1.1" or "tls1.2") that TLS
Sets the minimum SSL/TLS version (`tls1`, `tls1.1` or `tls1.2`) that TLS
fallback will accept.
## --cipher-suite-blacklist=`cipher_suites`

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

@ -5,7 +5,7 @@
The following example shows how to write a string to the clipboard:
```javascript
const { clipboard } = require('electron');
const {clipboard} = require('electron');
clipboard.writeText('Example String');
```

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

@ -8,14 +8,14 @@ This module does not include a web interface so you need to open
result.
```javascript
const { contentTracing } = require('electron');
const {contentTracing} = require('electron');
const options = {
categoryFilter: '*',
traceOptions: 'record-until-full,enable-sampling'
}
};
contentTracing.startRecording(options, function() {
contentTracing.startRecording(options, () => {
console.log('Tracing started');
setTimeout(() => {

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

@ -6,7 +6,7 @@ The following is an example of automatically submitting a crash report to a
remote server:
```javascript
const { crashReporter } = require('electron');
const {crashReporter} = require('electron');
crashReporter.start({
productName: 'YourName',

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

@ -5,12 +5,12 @@ microphone, camera, or screen.
```javascript
// In the renderer process.
var { desktopCapturer } = require('electron');
const {desktopCapturer} = require('electron');
desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
if (error) throw error;
for (var i = 0; i < sources.length; ++i) {
if (sources[i].name == "Electron") {
for (let i = 0; i < sources.length; ++i) {
if (sources[i].name === 'Electron') {
navigator.webkitGetUserMedia({
audio: false,
video: {

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

@ -5,16 +5,17 @@
An example of showing a dialog to select multiple files and directories:
```javascript
var win = ...; // BrowserWindow in which to show the dialog
const { dialog } = require('electron');
console.log(dialog.showOpenDialog({ properties: [ 'openFile', 'openDirectory', 'multiSelections' ]}));
let win = ...; // BrowserWindow in which to show the dialog
const {dialog} = require('electron');
console.log(dialog.showOpenDialog({properties: ['openFile', 'openDirectory', 'multiSelections']}));
```
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:
```javascript
const { dialog } = require('electron').remote;
const {dialog} = require('electron').remote;
```
## Methods
@ -42,10 +43,10 @@ selected when you want to limit the user to a specific type. For example:
```javascript
{
filters: [
{ name: 'Images', extensions: ['jpg', 'png', 'gif'] },
{ name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
{ name: 'Custom File Type', extensions: ['as'] },
{ name: 'All Files', extensions: ['*'] }
{name: 'Images', extensions: ['jpg', 'png', 'gif']},
{name: 'Movies', extensions: ['mkv', 'avi', 'mp4']},
{name: 'Custom File Type', extensions: ['as']},
{name: 'All Files', extensions: ['*']}
]
}
```

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

@ -18,10 +18,10 @@ win.webContents.session.on('will-download', (event, item, webContents) => {
console.log('Received bytes: ' + item.getReceivedBytes());
});
item.on('done', (e, state) => {
if (state === "completed") {
console.log("Download successfully");
if (state === 'completed') {
console.log('Download successfully');
} else {
console.log("Download is cancelled or interrupted that can't be resumed");
console.log('Download is cancelled or interrupted that can\'t be resumed');
}
});
});

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

@ -14,8 +14,8 @@ To create a frameless window, you need to set `frame` to `false` in
```javascript
const { BrowserWindow } = require('electron');
let win = new BrowserWindow({ width: 800, height: 600, frame: false });
const {BrowserWindow} = require('electron');
let win = new BrowserWindow({width: 800, height: 600, frame: false});
```
### Alternatives on OS X
@ -28,7 +28,7 @@ the window controls ("traffic lights") for standard window actions.
You can do so by specifying the new `titleBarStyle` option:
```javascript
let win = new BrowserWindow({ 'titleBarStyle': 'hidden' });
let win = new BrowserWindow({titleBarStyle: 'hidden'});
```
## Transparent window
@ -37,7 +37,7 @@ By setting the `transparent` option to `true`, you can also make the frameless
window transparent:
```javascript
let win = new BrowserWindow({ transparent: true, frame: false });
let win = new BrowserWindow({transparent: true, frame: false});
```
### Limitations

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

@ -11,12 +11,11 @@ not have the keyboard focus. You should not use this module until the `ready`
event of the app module is emitted.
```javascript
const electron = require('electron');
const { app, globalShortcut } = electron;
const {app, globalShortcut} = require('electron');
app.on('ready', () => {
// Register a 'CommandOrControl+X' shortcut listener.
const ret = globalShortcut.register('CommandOrControl+X', function() {
const ret = globalShortcut.register('CommandOrControl+X', () => {
console.log('CommandOrControl+X is pressed');
});

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

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

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

@ -15,13 +15,13 @@ the user right clicks the page:
```html
<!-- index.html -->
<script>
const { remote } = require('electron');
const { Menu, MenuItem } = remote;
const {remote} = require('electron');
const {Menu, MenuItem} = remote;
const menu = new Menu();
menu.append(new MenuItem({ label: 'MenuItem1', click: () => { console.log('item 1 clicked'); } }));
menu.append(new MenuItem({ type: 'separator' }));
menu.append(new MenuItem({ label: 'MenuItem2', type: 'checkbox', checked: true }));
menu.append(new MenuItem({label: 'MenuItem1', click() { console.log('item 1 clicked'); }}));
menu.append(new MenuItem({type: 'separator'}));
menu.append(new MenuItem({label: 'MenuItem2', type: 'checkbox', checked: true}));
window.addEventListener('contextmenu', (e) => {
e.preventDefault();
@ -79,32 +79,22 @@ const template = [
{
label: 'Reload',
accelerator: 'CmdOrCtrl+R',
click: (item, focusedWindow) => {
click(item, focusedWindow) {
if (focusedWindow) focusedWindow.reload();
}
},
{
label: 'Toggle Full Screen',
accelerator: (() => {
if (process.platform === 'darwin')
return 'Ctrl+Command+F';
else
return 'F11';
})(),
click: (item, focusedWindow) => {
accelerator: process.platform === 'darwin' ? 'Ctrl+Command+F' : 'F11',
click(item, focusedWindow) {
if (focusedWindow)
focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
}
},
{
label: 'Toggle Developer Tools',
accelerator: (() => {
if (process.platform == 'darwin')
return 'Alt+Command+I';
else
return 'Ctrl+Shift+I';
})(),
click: (item, focusedWindow) => {
accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
click(item, focusedWindow) {
if (focusedWindow)
focusedWindow.webContents.toggleDevTools();
}
@ -133,7 +123,7 @@ const template = [
submenu: [
{
label: 'Learn More',
click: () => { require('electron').shell.openExternal('http://electron.atom.io') }
click() { require('electron').shell.openExternal('http://electron.atom.io'); }
},
]
},
@ -179,7 +169,7 @@ if (process.platform === 'darwin') {
{
label: 'Quit',
accelerator: 'Command+Q',
click: () => { app.quit(); }
click() { app.quit(); }
},
]
});

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

@ -10,7 +10,7 @@ image file path as a `String`:
```javascript
const appIcon = new Tray('/Users/somebody/images/icon.png');
let window = new BrowserWindow({icon: '/Users/somebody/images/window.png'});
let win = new BrowserWindow({icon: '/Users/somebody/images/window.png'});
```
Or read the image from the clipboard which returns a `nativeImage`:
@ -49,7 +49,7 @@ images/
```javascript
var appIcon = new Tray('/Users/somebody/images/icon.png');
let appIcon = new Tray('/Users/somebody/images/icon.png');
```
Following suffixes for DPI are also supported:
@ -118,7 +118,7 @@ The following methods are available on instances of `nativeImage`:
```javascript
const nativeImage = require('electron').nativeImage;
var image = nativeImage.createFromPath('/Users/somebody/images/icon.png');
let image = nativeImage.createFromPath('/Users/somebody/images/icon.png');
```
### `image.toPng()`

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

@ -5,7 +5,7 @@
For example:
```javascript
const { powerSaveBlocker } = require('electron');
const {powerSaveBlocker} = require('electron');
const id = powerSaveBlocker.start('prevent-display-sleep');
console.log(powerSaveBlocker.isStarted(id));

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

@ -32,7 +32,7 @@ the global scope when node integration is turned off:
// preload.js
const _setImmediate = setImmediate;
const _clearImmediate = clearImmediate;
process.once('loaded', function() {
process.once('loaded', () => {
global.setImmediate = _setImmediate;
global.clearImmediate = _clearImmediate;
});

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

@ -6,18 +6,18 @@ An example of implementing a protocol that has the same effect as the
`file://` protocol:
```javascript
const {app, protocol} = require('electron')
const path = require('path')
const {app, protocol} = require('electron');
const path = require('path');
app.on('ready', function () {
protocol.registerFileProtocol('atom', function (request, callback) {
const url = request.url.substr(7)
callback({path: path.normalize(__dirname + '/' + url)})
}, function (error) {
app.on('ready', () => {
protocol.registerFileProtocol('atom', (request, callback) => {
const url = request.url.substr(7);
callback({path: path.normalize(__dirname + '/' + url)});
}, (error) => {
if (error)
console.error('Failed to register protocol')
})
})
console.error('Failed to register protocol');
});
});
```
**Note:** All methods unless specified can only be used after the `ready` event
of the `app` module gets emitted.
@ -52,10 +52,10 @@ So if you want to register a custom protocol to replace the `http` protocol, you
have to register it as standard scheme:
```javascript
protocol.registerStandardSchemes(['atom'])
app.on('ready', function () {
protocol.registerHttpProtocol('atom', ...)
})
protocol.registerStandardSchemes(['atom']);
app.on('ready', () => {
protocol.registerHttpProtocol('atom', ...);
});
```
**Note:** This method can only be used before the `ready` event of the `app`
@ -123,7 +123,7 @@ protocol.registerBufferProtocol('atom', (request, callback) => {
callback({mimeType: 'text/html', data: new Buffer('<h5>Response</h5>')});
}, (error) => {
if (error)
console.error('Failed to register protocol')
console.error('Failed to register protocol');
});
```

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

@ -14,9 +14,9 @@ similar to Java's [RMI][rmi]. An example of creating a browser window from a
renderer process:
```javascript
const { BrowserWindow } = require('electron').remote;
const {BrowserWindow} = require('electron').remote;
var win = new BrowserWindow({ width: 800, height: 600 });
let win = new BrowserWindow({width: 800, height: 600});
win.loadURL('https://github.com');
```
@ -70,22 +70,22 @@ For instance you can't use a function from the renderer process in an
// main process mapNumbers.js
exports.withRendererCallback = (mapper) => {
return [1,2,3].map(mapper);
}
};
exports.withLocalCallback = () => {
return exports.mapNumbers(x => x + 1);
}
};
```
```javascript
// renderer process
const mapNumbers = require("remote").require("./mapNumbers");
const mapNumbers = require('remote').require('./mapNumbers');
const withRendererCb = mapNumbers.withRendererCallback(x => x + 1);
const withLocalCb = mapNumbers.withLocalCallback()
const withLocalCb = mapNumbers.withLocalCallback();
console.log(withRendererCb, withLocalCb) // [true, true, true], [2, 3, 4]
console.log(withRendererCb, withLocalCb); // [true, true, true], [2, 3, 4]
```
As you can see, the renderer callback's synchronous return value was not as

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

@ -8,43 +8,40 @@ emitted (by invoking or requiring it).
`screen` is an [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter).
**Note:** In the renderer / DevTools, `window.screen` is a reserved DOM
property, so writing `var screen = require('electron').screen` will not work.
property, so writing `let {screen} = require('electron')` will not work.
In our examples below, we use `electronScreen` as the variable name instead.
An example of creating a window that fills the whole screen:
```javascript
const electron = require('electron');
const { app, BrowserWindow } = electron;
const {app, BrowserWindow, screen: electronScreen} = require('electron');
let mainWindow;
let win;
app.on('ready', () => {
const { width, height } = electron.screen.getPrimaryDisplay().workAreaSize;
mainWindow = new BrowserWindow({ width, height });
const {width, height} = electronScreen.getPrimaryDisplay().workAreaSize;
win = new BrowserWindow({width, height});
});
```
Another example of creating a window in the external display:
```javascript
const electron = require('electron');
const { app, BrowserWindow } = electron;
const {app, BrowserWindow, screen: electronScreen} = require('electron');
let mainWindow;
let win;
app.on('ready', () => {
var electronScreen = electron.screen;
var displays = electronScreen.getAllDisplays();
var externalDisplay = null;
let displays = electronScreen.getAllDisplays();
let externalDisplay = null;
for (let i in displays) {
if (displays[i].bounds.x != 0 || displays[i].bounds.y != 0) {
if (displays[i].bounds.x !== 0 || displays[i].bounds.y !== 0) {
externalDisplay = displays[i];
break;
}
}
if (externalDisplay) {
mainWindow = new BrowserWindow({
win = new BrowserWindow({
x: externalDisplay.bounds.x + 50,
y: externalDisplay.bounds.y + 50
});

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

@ -9,10 +9,10 @@ property of [`webContents`](web-contents.md) which is a property of
[`BrowserWindow`](browser-window.md).
```javascript
const { BrowserWindow } = require('electron');
const {BrowserWindow} = require('electron');
let win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL("http://github.com");
let win = new BrowserWindow({width: 800, height: 600});
win.loadURL('http://github.com');
const ses = win.webContents.session;
```
@ -89,13 +89,13 @@ session.defaultSession.cookies.get({}, (error, cookies) => {
});
// 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(cookies);
});
// Set a cookie with the given cookie data;
// may overwrite equivalent cookies if they exist.
const cookie = { url : "http://www.github.com", name : "dummy_name", value : "dummy" };
const cookie = {url : 'http://www.github.com', name : 'dummy_name', value : 'dummy'};
session.defaultSession.cookies.set(cookie, (error) => {
if (error)
console.error(error);
@ -307,7 +307,7 @@ Calling `callback(true)` will allow the permission and `callback(false)` will re
```javascript
session.fromPartition(partition).setPermissionRequestHandler((webContents, permission, callback) => {
if (webContents.getURL() === host) {
if (permission === "notifications") {
if (permission === 'notifications') {
callback(false); // denied.
return;
}
@ -343,7 +343,7 @@ called with an `response` object when `listener` has done its work.
```javascript
// Modify the user agent for all requests to the following urls.
const filter = {
urls: ["https://*.github.com/*", "*://electron.github.io"]
urls: ['https://*.github.com/*', '*://electron.github.io']
};
session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {

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

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

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

@ -19,13 +19,13 @@ scripts to be able to use those modules.
The main process script is just like a normal Node.js script:
```javascript
const { app, BrowserWindow } = require('electron');
const {app, BrowserWindow} = require('electron');
let window = null;
let win = null;
app.on('ready', () => {
window = new BrowserWindow({width: 800, height: 600});
window.loadURL('https://github.com');
win = new BrowserWindow({width: 800, height: 600});
win.loadURL('https://github.com');
});
```
@ -37,8 +37,8 @@ extra ability to use node modules:
<html>
<body>
<script>
const { remote } = require('electron');
console.log(remote.app.getVersion());
const {app} = require('electron').remote;
console.log(app.getVersion());
</script>
</body>
</html>
@ -53,7 +53,7 @@ As of 0.37, you can use
built-in modules.
```javascript
const { app, BrowserWindow } = require('electron');
const {app, BrowserWindow} = require('electron');
```
If you need the entire `electron` module, you can require it and then using
@ -61,7 +61,7 @@ destructuring to access the individual modules from `electron`.
```javascript
const electron = require('electron');
const { app, BrowserWindow } = electron;
const {app, BrowserWindow} = electron;
```
This is equivalent to the following code:
@ -88,7 +88,7 @@ process.env.ELECTRON_HIDE_INTERNAL_MODULES = 'true'
Or call the `hideInternalModules` API:
```javascript
require('electron').hideInternalModules()
require('electron').hideInternalModules();
```
[gui]: https://en.wikipedia.org/wiki/Graphical_user_interface

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

@ -56,7 +56,7 @@ 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):
```javascript
let browserOptions = { width: 1000, height: 800 };
let browserOptions = {width: 1000, height: 800};
// Make the window transparent only if the platform supports it.
if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) {

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

@ -3,19 +3,16 @@
> Add icons and context menus to the system's notification area.
```javascript
const electron = require('electron');
const app = electron.app;
const Menu = electron.Menu;
const Tray = electron.Tray;
const {app, Menu, Tray} = require('electron');
let appIcon = null;
app.on('ready', () => {
appIcon = new Tray('/path/to/my/icon');
const contextMenu = Menu.buildFromTemplate([
{ label: 'Item1', type: 'radio' },
{ label: 'Item2', type: 'radio' },
{ label: 'Item3', type: 'radio', checked: true },
{ label: 'Item4', type: 'radio' }
{label: 'Item1', type: 'radio'},
{label: 'Item2', type: 'radio'},
{label: 'Item3', type: 'radio', checked: true},
{label: 'Item4', type: 'radio'}
]);
appIcon.setToolTip('This is my application.');
appIcon.setContextMenu(contextMenu);

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

@ -9,10 +9,10 @@ the [`BrowserWindow`](browser-window.md) object. An example of accessing the
`webContents` object:
```javascript
const { BrowserWindow } = require('electron');
const {BrowserWindow} = require('electron');
let win = new BrowserWindow({width: 800, height: 1500});
win.loadURL("http://github.com");
win.loadURL('http://github.com');
let webContents = win.webContents;
```
@ -384,8 +384,8 @@ e.g. the `http://` or `file://`. If the load should bypass http cache then
use the `pragma` header to achieve it.
```javascript
const options = {"extraHeaders" : "pragma: no-cache\n"}
webContents.loadURL(url, options)
const options = {extraHeaders: 'pragma: no-cache\n'};
webContents.loadURL(url, options);
```
### `webContents.downloadURL(url)`
@ -401,7 +401,7 @@ Returns URL of the current web page.
```javascript
let win = new BrowserWindow({width: 800, height: 600});
win.loadURL("http://github.com");
win.loadURL('http://github.com');
let currentURL = win.webContents.getURL();
```
@ -603,12 +603,12 @@ the request can be obtained by subscribing to
Stops any `findInPage` request for the `webContents` with the provided `action`.
```javascript
webContents.on('found-in-page', function(event, result) {
webContents.on('found-in-page', (event, result) => {
if (result.finalUpdate)
webContents.stopFindInPage("clearSelection");
webContents.stopFindInPage('clearSelection');
});
const requestId = webContents.findInPage("api");
const requestId = webContents.findInPage('api');
```
### `webContents.hasServiceWorker(callback)`
@ -673,7 +673,7 @@ By default, an empty `options` will be regarded as:
```
```javascript
const { BrowserWindow } = require('electron');
const {BrowserWindow} = require('electron');
const fs = require('fs');
let win = new BrowserWindow({width: 800, height: 600});
@ -700,8 +700,8 @@ Adds the specified path to DevTools workspace. Must be used after DevTools
creation:
```javascript
mainWindow.webContents.on('devtools-opened', function() {
mainWindow.webContents.addWorkSpace(__dirname);
win.webContents.on('devtools-opened', () => {
win.webContents.addWorkSpace(__dirname);
});
```
@ -763,13 +763,13 @@ An example of sending messages from the main process to the renderer process:
```javascript
// In the main process.
let mainWindow = null;
let win = null;
app.on('ready', () => {
mainWindow = new BrowserWindow({width: 800, height: 600});
mainWindow.loadURL(`file://${__dirname}/index.html`);
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.webContents.send('ping', 'whoooooooh!');
win = new BrowserWindow({width: 800, height: 600});
win.loadURL(`file://${__dirname}/index.html`);
win.webContents.on('did-finish-load', () => {
win.webContents.send('ping', 'whoooooooh!');
});
});
```
@ -887,7 +887,7 @@ End subscribing for frame presentation events.
* `HTMLOnly` - Save only the HTML of the page.
* `HTMLComplete` - Save complete-html page.
* `MHTML` - Save complete-html page as MHTML.
* `callback` Function - `function(error) {}`.
* `callback` Function - `(error) => {}`.
* `error` Error
Returns true if the process of saving page has been initiated successfully.
@ -898,7 +898,7 @@ win.loadURL('https://github.com');
win.webContents.on('did-finish-load', () => {
win.webContents.savePage('/tmp/test.html', 'HTMLComplete', (error) => {
if (!error)
console.log("Save page successfully");
console.log('Save page successfully');
});
});
```
@ -928,23 +928,23 @@ Debugger API serves as an alternate transport for [remote debugging protocol][rd
```javascript
try {
win.webContents.debugger.attach("1.1");
win.webContents.debugger.attach('1.1');
} catch(err) {
console.log("Debugger attach failed : ", err);
console.log('Debugger attach failed : ', err);
};
win.webContents.debugger.on('detach', (event, reason) => {
console.log("Debugger detached due to : ", reason);
console.log('Debugger detached due to : ', reason);
});
win.webContents.debugger.on('message', (event, method, params) => {
if (method === "Network.requestWillBeSent") {
if (params.request.url === "https://www.github.com")
if (method === 'Network.requestWillBeSent') {
if (params.request.url === 'https://www.github.com')
win.webContents.debugger.detach();
}
})
});
win.webContents.debugger.sendCommand("Network.enable");
win.webContents.debugger.sendCommand('Network.enable');
```
#### `webContents.debugger.attach([protocolVersion])`

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

@ -5,7 +5,7 @@
An example of zooming current page to 200%.
```javascript
const { webFrame } = require('electron');
const {webFrame} = require('electron');
webFrame.setZoomFactor(2);
```
@ -58,8 +58,8 @@ whether the word passed is correctly spelled.
An example of using [node-spellchecker][spellchecker] as provider:
```javascript
webFrame.setSpellCheckProvider("en-US", true, {
spellCheck: function(text) {
webFrame.setSpellCheckProvider('en-US', true, {
spellCheck(text) {
return !(require('spellchecker').isMisspelled(text));
}
});

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

@ -37,15 +37,15 @@ and displays a "loading..." message during the load time:
const loadstart = () => {
indicator.innerText = 'loading...';
}
};
const loadstop = () => {
indicator.innerText = '';
}
};
webview.addEventListener('did-start-loading', loadstart);
webview.addEventListener('did-stop-loading', loadstop);
}
};
</script>
```
@ -213,7 +213,7 @@ The `webview` tag has the following methods:
**Example**
```javascript
webview.addEventListener("dom-ready", () => {
webview.addEventListener('dom-ready', () => {
webview.openDevTools();
});
```
@ -600,7 +600,7 @@ The following example code forwards all log messages to the embedder's console
without regard for log level or other properties.
```javascript
webview.addEventListener('console-message', function(e) {
webview.addEventListener('console-message', (e) => {
console.log('Guest page logged a message:', e.message);
});
```
@ -620,12 +620,12 @@ Fired when a result is available for
[`webview.findInPage`](web-view-tag.md#webviewtagfindinpage) request.
```javascript
webview.addEventListener('found-in-page', function(e) {
webview.addEventListener('found-in-page', (e) => {
if (e.result.finalUpdate)
webview.stopFindInPage("keepSelection");
webview.stopFindInPage('keepSelection');
});
const rquestId = webview.findInPage("test");
const rquestId = webview.findInPage('test');
```
### Event: 'new-window'
@ -644,7 +644,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.
```javascript
const { shell } = require('electron');
const {shell} = require('electron');
webview.addEventListener('new-window', (e) => {
const protocol = require('url').parse(e.url).protocol;
@ -732,7 +732,7 @@ webview.send('ping');
```javascript
// In guest page.
var { ipcRenderer } = require('electron');
const {ipcRenderer} = require('electron');
ipcRenderer.on('ping', () => {
ipcRenderer.sendToHost('pong');
});

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

@ -65,7 +65,7 @@ code from this:
```javascript
app.on('ready', () => {
const tray = new Tray('/path/to/icon.png');
})
});
```
to this:
@ -74,7 +74,7 @@ to this:
let tray = null;
app.on('ready', () => {
tray = new Tray('/path/to/icon.png');
})
});
```
## I can not use jQuery/RequireJS/Meteor/AngularJS in Electron.
@ -87,7 +87,7 @@ To solve this, you can turn off node integration in Electron:
```javascript
// In the main process.
let mainWindow = new BrowserWindow({
let win = new BrowserWindow({
webPreferences: {
nodeIntegration: false
}

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

@ -93,6 +93,6 @@ this event it might look something like this:
```javascript
Alarm.on('wake-up', (time) => {
console.log(time)
})
console.log(time);
});
```

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

@ -71,7 +71,7 @@ require('/path/to/example.asar/dir/module.js');
You can also display a web page in an `asar` archive with `BrowserWindow`:
```javascript
const { BrowserWindow } = require('electron');
const {BrowserWindow} = require('electron');
let win = new BrowserWindow({width: 800, height: 600});
win.loadURL('file:///path/to/example.asar/static/index.html');
```
@ -85,7 +85,7 @@ For example, to get a file with `$.get`:
```html
<script>
var $ = require('./jquery.min.js');
let $ = require('./jquery.min.js');
$.get('file:///path/to/example.asar/file.txt', (data) => {
console.log(data);
});

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

@ -22,9 +22,9 @@ let myNotification = new Notification('Title', {
body: 'Lorem Ipsum Dolor Sit Amet'
});
myNotification.onclick = function () {
console.log('Notification clicked')
}
myNotification.onclick = () => {
console.log('Notification clicked');
};
```
While code and user experience across operating systems are similar, there
@ -118,7 +118,7 @@ const app = electron.app;
const Menu = electron.Menu;
const dockMenu = Menu.buildFromTemplate([
{ label: 'New Window', click: () => { console.log('New Window'); } },
{ label: 'New Window', click() { console.log('New Window'); } },
{ label: 'New Window with Settings', submenu: [
{ label: 'Basic' },
{ label: 'Pro'}
@ -209,7 +209,7 @@ You can use [BrowserWindow.setThumbarButtons][setthumbarbuttons] to set
thumbnail toolbar in your application:
```javascript
const { BrowserWindow } = require('electron');
const {BrowserWindow} = require('electron');
const path = require('path');
let win = new BrowserWindow({
@ -219,15 +219,15 @@ let win = new BrowserWindow({
win.setThumbarButtons([
{
tooltip: "button1",
tooltip: 'button1',
icon: path.join(__dirname, 'button1.png'),
click: () => { console.log("button2 clicked"); }
click() { console.log('button2 clicked'); }
},
{
tooltip: "button2",
tooltip: 'button2',
icon: path.join(__dirname, 'button2.png'),
flags:['enabled', 'dismissonclick'],
click: () => { console.log("button2 clicked."); }
flags: ['enabled', 'dismissonclick'],
click() { console.log('button2 clicked.'); }
}
]);
```
@ -267,8 +267,8 @@ To set the progress bar for a Window, you can use the
[BrowserWindow.setProgressBar][setprogressbar] API:
```javascript
let window = new BrowserWindow({...});
window.setProgressBar(0.5);
let win = new BrowserWindow({...});
win.setProgressBar(0.5);
```
## Icon Overlays in Taskbar (Windows)
@ -294,8 +294,8 @@ To set the overlay icon for a window, you can use the
[BrowserWindow.setOverlayIcon][setoverlayicon] API:
```javascript
let window = new BrowserWindow({...});
window.setOverlayIcon('path/to/overlay.png', 'Description for overlay');
let win = new BrowserWindow({...});
win.setOverlayIcon('path/to/overlay.png', 'Description for overlay');
```
## Represented File of Window (OS X)
@ -316,9 +316,9 @@ To set the represented file of window, you can use the
[BrowserWindow.setDocumentEdited][setdocumentedited] APIs:
```javascript
let window = new BrowserWindow({...});
window.setRepresentedFilename('/etc/passwd');
window.setDocumentEdited(true);
let win = new BrowserWindow({...});
win.setRepresentedFilename('/etc/passwd');
win.setDocumentEdited(true);
```
[addrecentdocument]: ../api/app.md#appaddrecentdocumentpath-os-x-windows

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

@ -71,7 +71,7 @@ _online-status.html_
<html>
<body>
<script>
const { ipcRenderer } = require('electron');
const {ipcRenderer} = require('electron');
const updateOnlineStatus = () => {
ipcRenderer.send('online-status-changed', navigator.onLine ? 'online' : 'offline');
};

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

@ -80,32 +80,32 @@ The `main.js` should create windows and handle system events, a typical
example being:
```javascript
const electron = require('electron')
const electron = require('electron');
// Module to control application life.
const app = electron.app;
const {app} = electron;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;
const {BrowserWindow} = electron;
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
let win;
function createWindow () {
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600});
win = new BrowserWindow({width: 800, height: 600});
// and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/index.html`);
win.loadURL(`file://${__dirname}/index.html`);
// Open the DevTools.
mainWindow.webContents.openDevTools();
win.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', () => {
win.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
win = null;
});
}
@ -126,14 +126,13 @@ app.on('window-all-closed', () => {
app.on('activate', () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
if (win === null) {
createWindow();
}
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
```
Finally the `index.html` is the web page you want to show:

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

@ -1,35 +1,68 @@
# Security, Native Capabilities, and Your Responsibility
As web developers, we usually enjoy the strong security net of the browser - the risks associated with the code we write is relatively small. We rely on the fairly limited amount of power and capabilities granted to a website – and trust that our users enjoy a browser built by a large team of engineers that is able to quickly respond to newly discovered security threats.
As web developers, we usually enjoy the strong security net of the browser - the
risks associated with the code we write is relatively small. We rely on the
fairly limited amount of power and capabilities granted to a website – and trust
that our users enjoy a browser built by a large team of engineers that is able
to quickly respond to newly discovered security threats.
When working with Electron, it is important to understand that Electron is not a web browser. It allows you to build powerful desktop apps with web technologies. Its core feature is the ability to build software is just as powerful as completely native applications, eclipsing the limited feature set of a website. The inherent risks scale with the additional powers granted to your code.
When working with Electron, it is important to understand that Electron isnot a
web browser. It allows you to build powerful desktop apps with web technologies.
Its core feature is the ability to build software is just as powerful as
completely native applications, eclipsing the limited feature set of a website.
The inherent risks scale with the additional powers granted to your code.
With that in mind, be aware that displaying arbitrary content from untrusted sources poses a severe security risk that Electron is not built to handle. In fact, the most popular Electron apps (Atom, Slack, Visual Studio Code, etc) display primarily local content (or trusted, secure remote content without Node integration) – if your application executes code from an online source, it is your responsibility to ensure that the code is not malicious.
With that in mind, be aware that displaying arbitrary content from untrusted
sources poses a severe security risk that Electron is not built to handle.
In fact, the most popular Electron apps (Atom, Slack, Visual Studio Code, etc)
display primarily local content (or trusted, secure remote content without Node
integration) – if your application executes code from an online source, it is
your responsibility to ensure that the code is not malicious.
## Chromium Security Issues and Upgrades
While Electron strives to support new versions of Chromium as soon as possible, developers should be aware that upgrading is a serious undertaking - involving hand-editing dozens or even hundreds of files. Given the resources and contributions available today, Electron will often not be on the very latest version of Chromium, lagging behind by either days or weeks.
While Electron strives to support new versions of Chromium as soon as possible,
developers should be aware that upgrading is a serious undertaking - involving
hand-editing dozens or even hundreds of files. Given the resources and
contributions available today, Electron will often not be on the very latest
version of Chromium, lagging behind by either days or weeks.
We feel that our current system of updating the Chromium component strikes an appropriate balance between the resources we have available and the needs of the majority of applications built on top of the framework. We definitely are interested in hearing more about specific use cases from the people that build things on top of Electron. Pull requests and contributions supporting this effort are always very welcome.
We feel that our current system of updating the Chromium component strikes an
appropriate balance between the resources we have available and the needs of the
majority of applications built on top of the framework. We definitely are
interested in hearing more about specific use cases from the people that build
things on top of Electron. Pull requests and contributions supporting this
effort are always very welcome.
## Ignoring Above Advice
A security issue exists whenever you receive code from a remote destination and execute it locally. As an example, consider a remote website being displayed inside a browser window. If an attacker somehow manages to change said content (either by attacking the source directly, or by sitting between your app and the actual destination), they will be able to execute native code on the user's machine.
A security issue exists whenever you receive code from a remote destination and
execute it locally. As an example, consider a remote website being displayed
inside a browser window. If an attacker somehow manages to change said content
(either by attacking the source directly, or by sitting between your app and
the actual destination), they will be able to execute native code on the user's
machine.
> :warning: Under no circumstances should you load and execute remote code with enabled Node integration. Instead, use only local files (packaged together with your application) to execute Node code. To display remote content, use the `webview` tag and make sure to disable the `nodeIntegration`.
> :warning: Under no circumstances should you load and execute remote code with
enabled Node integration. Instead, use only local files (packaged together with
your application) to execute Node code. To display remote content, use the
`webview` tag and make sure to disable the `nodeIntegration`.
#### Checklist
This is not bulletproof, but at the least, you should attempt the following:
* Only display secure (https) content
* Disable the Node integration in all renderers that display remote content (using `webPreferences`)
* Do not disable `webSecurity`. Disabling it will disable the same-origin policy.
* Do not set `allowDisplayingInsecureContent` to true.
* Do not set `allowRunningInsecureContent` to true.
* Do not enable `experimentalFeatures` or `experimentalCanvasFeatures` unless you know what you're doing.
* Do not use `blinkFeatures` unless you know what you're doing.
* WebViews: Set `nodeintegration` to false
* WebViews: Do not use `disablewebsecurity`
* WebViews: Do not use `allowpopups`
* WebViews: Do not use `insertCSS` or `executeJavaScript` with remote CSS/JS.
Again, this list merely minimizes the risk, it does not remove it. If your goal is to display a website, a browser will be a more secure option.
* Only display secure (https) content
* Disable the Node integration in all renderers that display remote content
(using `webPreferences`)
* Do not disable `webSecurity`. Disabling it will disable the same-origin policy.
* Do not set `allowDisplayingInsecureContent` to true.
* Do not set `allowRunningInsecureContent` to true.
* Do not enable `experimentalFeatures` or `experimentalCanvasFeatures` unless
you know what you're doing.
* Do not use `blinkFeatures` unless you know what you're doing.
* WebViews: Set `nodeintegration` to false
* WebViews: Do not use `disablewebsecurity`
* WebViews: Do not use `allowpopups`
* WebViews: Do not use `insertCSS` or `executeJavaScript` with remote CSS/JS.
Again, this list merely minimizes the risk, it does not remove it. If your goal
is to display a website, a browser will be a more secure option.

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

@ -29,14 +29,14 @@ app.commandLine.appendSwitch('ppapi-flash-path', '/path/to/libpepflashplayer.so'
app.commandLine.appendSwitch('ppapi-flash-version', '17.0.0.169');
app.on('ready', () => {
mainWindow = new BrowserWindow({
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
plugins: true
}
});
mainWindow.loadURL(`file://${__dirname}/index.html`);
win.loadURL(`file://${__dirname}/index.html`);
// Something else
});
```

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

@ -59,7 +59,7 @@ driver.get('http://www.google.com');
driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');
driver.findElement(webdriver.By.name('btnG')).click();
driver.wait(() => {
return driver.getTitle().then(function(title) {
return driver.getTitle().then((title) => {
return title === 'webdriver - Google Search';
});
}, 1000);
@ -106,7 +106,7 @@ const options = {
}
};
var client = webdriverio.remote(options);
let client = webdriverio.remote(options);
client
.init()

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

@ -59,14 +59,14 @@ app.commandLine.appendSwitch('widevine-cdm-path', '/path/to/widevinecdmadapter.p
// The version of plugin can be got from `chrome://plugins` page in Chrome.
app.commandLine.appendSwitch('widevine-cdm-version', '1.4.8.866');
let mainWindow = null;
let win = null;
app.on('ready', () => {
mainWindow = new BrowserWindow({
win = new BrowserWindow({
webPreferences: {
// The `plugins` have to be enabled.
plugins: true
}
})
});
});
```