Merge branch 'update-code-samples' of https://github.com/stevekinney/electron into stevekinney-update-code-samples

This commit is contained in:
Cheng Zhao 2016-05-05 20:55:25 +09:00
commit 969a30fc3b
38 changed files with 258 additions and 252 deletions

View file

@ -6,8 +6,8 @@ The following example shows how to quit the application when the last window is
closed:
```javascript
const app = require('electron').app;
app.on('window-all-closed', function() {
const { app } = require('electron');
app.on('window-all-closed', () => {
app.quit();
});
```
@ -237,7 +237,7 @@ should prevent the default behavior with `event.preventDefault()` and call
`callback(username, password)` with the credentials.
```javascript
app.on('login', function(event, webContents, request, authInfo, callback) {
app.on('login', (event, webContents, request, authInfo, callback) => {
event.preventDefault();
callback('username', 'secret');
})
@ -481,9 +481,9 @@ An example of activating the window of primary instance when a second instance
starts:
```javascript
var myWindow = null;
let myWindow = null;
var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) {
const shouldQuit = app.makeSingleInstance((commandLine, workingDirectory) => {
// Someone tried to run a second instance, we should focus our window.
if (myWindow) {
if (myWindow.isMinimized()) myWindow.restore();
@ -497,7 +497,7 @@ if (shouldQuit) {
}
// Create myWindow, load the rest of the app, etc...
app.on('ready', function() {
app.on('ready', () => {
});
```

View file

@ -4,13 +4,13 @@
```javascript
// In the main process.
const BrowserWindow = require('electron').BrowserWindow;
const { BrowserWindow } = require('electron');
// Or in the renderer process.
const BrowserWindow = require('electron').remote.BrowserWindow;
const { BrowserWindow } = require('electron').remote;
var win = new BrowserWindow({ width: 800, height: 600, show: false });
win.on('closed', function() {
let win = new BrowserWindow({ width: 800, height: 600, show: false });
win.on('closed', () => {
win = null;
});
@ -315,7 +315,7 @@ Commands are lowercased with underscores replaced with hyphens and the
e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`.
```javascript
someWindow.on('app-command', function(e, cmd) {
someWindow.on('app-command', (e, cmd) => {
// Navigate the window back when the user hits their mouse back button
if (cmd === 'browser-backward' && someWindow.webContents.canGoBack()) {
someWindow.webContents.goBack();

View file

@ -7,11 +7,11 @@ your app's main script before the [ready][ready] event of the [app][app] module
is emitted:
```javascript
const app = require('electron').app;
const { app } = require('electron');
app.commandLine.appendSwitch('remote-debugging-port', '8315');
app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1');
app.on('ready', function() {
app.on('ready', () => {
// Your code here
});
```

View file

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

View file

@ -8,7 +8,7 @@ This module does not include a web interface so you need to open
result.
```javascript
const contentTracing = require('electron').contentTracing;
const { contentTracing } = require('electron');
const options = {
categoryFilter: '*',
@ -18,8 +18,8 @@ const options = {
contentTracing.startRecording(options, function() {
console.log('Tracing started');
setTimeout(function() {
contentTracing.stopRecording('', function(path) {
setTimeout(() => {
contentTracing.stopRecording('', (path) => {
console.log('Tracing data recorded to ' + path);
});
}, 5000);

View file

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

View file

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

View file

@ -6,7 +6,7 @@ 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').dialog;
const { dialog } = require('electron');
console.log(dialog.showOpenDialog({ properties: [ 'openFile', 'openDirectory', 'multiSelections' ]}));
```
@ -14,7 +14,7 @@ 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.dialog;
const { dialog } = require('electron').remote;
```
## Methods

View file

@ -8,17 +8,17 @@ control the download item.
```javascript
// In the main process.
win.webContents.session.on('will-download', function(event, item, webContents) {
win.webContents.session.on('will-download', (event, item, webContents) => {
// Set the save path, making Electron not to prompt a save dialog.
item.setSavePath('/tmp/save.pdf');
console.log(item.getMimeType());
console.log(item.getFilename());
console.log(item.getTotalBytes());
item.on('updated', function() {
item.on('updated', () => {
console.log('Received bytes: ' + item.getReceivedBytes());
});
item.on('done', function(e, state) {
if (state == "completed") {
item.on('done', (e, state) => {
if (state === "completed") {
console.log("Download successfully");
} else {
console.log("Download is cancelled or interrupted that can't be resumed");

View file

@ -15,16 +15,16 @@ Example on getting a real path from a dragged-onto-the-app file:
</div>
<script>
var holder = document.getElementById('holder');
holder.ondragover = function () {
const holder = document.getElementById('holder');
holder.ondragover = () => {
return false;
};
holder.ondragleave = holder.ondragend = function () {
holder.ondragleave = holder.ondragend = () => {
return false;
};
holder.ondrop = function (e) {
holder.ondrop = (e) => {
e.preventDefault();
var file = e.dataTransfer.files[0];
const file = e.dataTransfer.files[0];
console.log('File you dragged here is', file.path);
return false;
};

View file

@ -14,8 +14,8 @@ To create a frameless window, you need to set `frame` to `false` in
```javascript
const BrowserWindow = require('electron').BrowserWindow;
var 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
var 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
var win = new BrowserWindow({ transparent: true, frame: false });
let win = new BrowserWindow({ transparent: true, frame: false });
```
### Limitations

View file

@ -12,12 +12,11 @@ event of the app module is emitted.
```javascript
const electron = require('electron');
const app = electron.app;
const globalShortcut = electron.globalShortcut;
const { app, globalShortcut } = electron;
app.on('ready', function() {
app.on('ready', () => {
// Register a 'CommandOrControl+X' shortcut listener.
var ret = globalShortcut.register('CommandOrControl+X', function() {
const ret = globalShortcut.register('CommandOrControl+X', function() {
console.log('CommandOrControl+X is pressed');
});
@ -29,7 +28,7 @@ app.on('ready', function() {
console.log(globalShortcut.isRegistered('CommandOrControl+X'));
});
app.on('will-quit', function() {
app.on('will-quit', () => {
// Unregister a shortcut.
globalShortcut.unregister('CommandOrControl+X');

View file

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

View file

@ -15,16 +15,14 @@ the user right clicks the page:
```html
<!-- index.html -->
<script>
const remote = require('electron').remote;
const Menu = remote.Menu;
const MenuItem = remote.MenuItem;
const { Menu, MenuItem } = require('electron').remote;
var menu = new Menu();
menu.append(new MenuItem({ label: 'MenuItem1', click: function() { console.log('item 1 clicked'); } }));
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 }));
window.addEventListener('contextmenu', function (e) {
window.addEventListener('contextmenu', (e) => {
e.preventDefault();
menu.popup(remote.getCurrentWindow());
}, false);
@ -35,7 +33,7 @@ An example of creating the application menu in the render process with the
simple template API:
```javascript
var template = [
const template = [
{
label: 'Edit',
submenu: [
@ -80,33 +78,32 @@ var template = [
{
label: 'Reload',
accelerator: 'CmdOrCtrl+R',
click: function(item, focusedWindow) {
if (focusedWindow)
focusedWindow.reload();
click: (item, focusedWindow) => {
if (focusedWindow) focusedWindow.reload();
}
},
{
label: 'Toggle Full Screen',
accelerator: (function() {
if (process.platform == 'darwin')
accelerator: (() => {
if (process.platform === 'darwin')
return 'Ctrl+Command+F';
else
return 'F11';
})(),
click: function(item, focusedWindow) {
click: (item, focusedWindow) => {
if (focusedWindow)
focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
}
},
{
label: 'Toggle Developer Tools',
accelerator: (function() {
accelerator: (() => {
if (process.platform == 'darwin')
return 'Alt+Command+I';
else
return 'Ctrl+Shift+I';
})(),
click: function(item, focusedWindow) {
click: (item, focusedWindow) => {
if (focusedWindow)
focusedWindow.webContents.toggleDevTools();
}
@ -135,14 +132,14 @@ var template = [
submenu: [
{
label: 'Learn More',
click: function() { require('electron').shell.openExternal('http://electron.atom.io') }
click: () => { require('electron').shell.openExternal('http://electron.atom.io') }
},
]
},
];
if (process.platform == 'darwin') {
var name = require('electron').remote.app.getName();
if (process.platform === 'darwin') {
const name = require('electron').remote.app.getName();
template.unshift({
label: name,
submenu: [
@ -181,7 +178,7 @@ if (process.platform == 'darwin') {
{
label: 'Quit',
accelerator: 'Command+Q',
click: function() { app.quit(); }
click: () => { app.quit(); }
},
]
});
@ -197,7 +194,7 @@ if (process.platform == 'darwin') {
);
}
var menu = Menu.buildFromTemplate(template);
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
```

View file

@ -9,15 +9,15 @@ For example, when creating a tray or setting a window's icon, you can pass an
image file path as a `String`:
```javascript
var appIcon = new Tray('/Users/somebody/images/icon.png');
var window = new BrowserWindow({icon: '/Users/somebody/images/window.png'});
const appIcon = new Tray('/Users/somebody/images/icon.png');
let window = new BrowserWindow({icon: '/Users/somebody/images/window.png'});
```
Or read the image from the clipboard which returns a `nativeImage`:
```javascript
var image = clipboard.readImage();
var appIcon = new Tray(image);
const image = clipboard.readImage();
const appIcon = new Tray(image);
```
## Supported Formats

View file

@ -8,8 +8,8 @@ event of the `app` module is emitted.
For example:
```javascript
app.on('ready', function() {
require('electron').powerMonitor.on('suspend', function() {
app.on('ready', () => {
require('electron').powerMonitor.on('suspend', () => {
console.log('The system is going to sleep');
});
});

View file

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

View file

@ -27,8 +27,8 @@ the global scope when node integration is turned off:
```javascript
// preload.js
var _setImmediate = setImmediate;
var _clearImmediate = clearImmediate;
const _setImmediate = setImmediate;
const _clearImmediate = clearImmediate;
process.once('loaded', function() {
global.setImmediate = _setImmediate;
global.clearImmediate = _clearImmediate;

View file

@ -7,13 +7,13 @@ An example of implementing a protocol that has the same effect as the
```javascript
const electron = require('electron');
const app = electron.app;
const { app } = electron;
const path = require('path');
app.on('ready', function() {
var protocol = electron.protocol;
const { protocol } = electron;
protocol.registerFileProtocol('atom', function(request, callback) {
var url = request.url.substr(7);
const url = request.url.substr(7);
callback({path: path.normalize(__dirname + '/' + url)});
}, function (error) {
if (error)
@ -95,9 +95,9 @@ should be called with either a `Buffer` object or an object that has the `data`,
Example:
```javascript
protocol.registerBufferProtocol('atom', function(request, callback) {
protocol.registerBufferProtocol('atom', (request, callback) => {
callback({mimeType: 'text/html', data: new Buffer('<h5>Response</h5>')});
}, function (error) {
}, (error) => {
if (error)
console.error('Failed to register protocol')
});

View file

@ -14,8 +14,7 @@ similar to Java's [RMI][rmi]. An example of creating a browser window from a
renderer process:
```javascript
const remote = require('electron').remote;
const BrowserWindow = remote.BrowserWindow;
const { BrowserWindow } = require('electron').remote;
var win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL('https://github.com');
@ -69,26 +68,22 @@ For instance you can't use a function from the renderer process in an
```javascript
// main process mapNumbers.js
exports.withRendererCallback = function(mapper) {
exports.withRendererCallback = (mapper) => {
return [1,2,3].map(mapper);
}
exports.withLocalCallback = function() {
return exports.mapNumbers(function(x) {
return x + 1;
});
exports.withLocalCallback = () => {
return exports.mapNumbers(x => x + 1);
}
```
```javascript
// renderer process
var mapNumbers = require("remote").require("./mapNumbers");
const mapNumbers = require("remote").require("./mapNumbers");
var withRendererCb = mapNumbers.withRendererCallback(function(x) {
return x + 1;
})
const withRendererCb = mapNumbers.withRendererCallback(x => x + 1);
var withLocalCb = mapNumbers.withLocalCallback()
const withLocalCb = mapNumbers.withLocalCallback()
console.log(withRendererCb, withLocalCb) // [true, true, true], [2, 3, 4]
```
@ -104,7 +99,7 @@ For example, the following code seems innocent at first glance. It installs a
callback for the `close` event on a remote object:
```javascript
remote.getCurrentWindow().on('close', function() {
remote.getCurrentWindow().on('close', () => {
// blabla...
});
```

View file

@ -14,15 +14,13 @@ An example of creating a window that fills the whole screen:
```javascript
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const { app, BrowserWindow } = electron;
var mainWindow;
let mainWindow;
app.on('ready', function() {
var electronScreen = electron.screen;
var size = electronScreen.getPrimaryDisplay().workAreaSize;
mainWindow = new BrowserWindow({ width: size.width, height: size.height });
app.on('ready', () => {
const { width, height } = electron.screen.getPrimaryDisplay().workAreaSize;
mainWindow = new BrowserWindow({ width, height });
});
```
@ -30,16 +28,15 @@ Another example of creating a window in the external display:
```javascript
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const { app, BrowserWindow } = electron;
var mainWindow;
let mainWindow;
app.on('ready', function() {
app.on('ready', () => {
var electronScreen = electron.screen;
var displays = electronScreen.getAllDisplays();
var externalDisplay = null;
for (var i in displays) {
for (let i in displays) {
if (displays[i].bounds.x != 0 || displays[i].bounds.y != 0) {
externalDisplay = displays[i];
break;

View file

@ -9,12 +9,12 @@ property of [`webContents`](web-contents.md) which is a property of
[`BrowserWindow`](browser-window.md).
```javascript
const BrowserWindow = require('electron').BrowserWindow;
const { BrowserWindow } = require('electron');
var win = new BrowserWindow({ width: 800, height: 600 });
let win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL("http://github.com");
var ses = win.webContents.session;
const ses = win.webContents.session;
```
## Methods
@ -47,7 +47,7 @@ You can create a `Session` object in the `session` module:
```javascript
const session = require('electron').session;
var ses = session.fromPartition('persist:name');
const ses = session.fromPartition('persist:name');
```
### Instance Events
@ -66,9 +66,9 @@ Calling `event.preventDefault()` will cancel the download and `item` will not be
available from next tick of the process.
```javascript
session.defaultSession.on('will-download', function(event, item, webContents) {
session.defaultSession.on('will-download', (event, item, webContents) => {
event.preventDefault();
require('request')(item.getURL(), function(data) {
require('request')(item.getURL(), (data) => {
require('fs').writeFileSync('/somewhere', data);
});
});
@ -84,19 +84,19 @@ The `cookies` gives you ability to query and modify cookies. For example:
```javascript
// Query all cookies.
session.defaultSession.cookies.get({}, function(error, cookies) {
session.defaultSession.cookies.get({}, (error, cookies) => {
console.log(cookies);
});
// Query all cookies associated with a specific url.
session.defaultSession.cookies.get({ url : "http://www.github.com" }, function(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.
var cookie = { url : "http://www.github.com", name : "dummy_name", value : "dummy" };
session.defaultSession.cookies.set(cookie, function(error) {
const cookie = { url : "http://www.github.com", name : "dummy_name", value : "dummy" };
session.defaultSession.cookies.set(cookie, (error) => {
if (error)
console.error(error);
});
@ -285,8 +285,8 @@ Calling `setCertificateVerifyProc(null)` will revert back to default certificate
verify proc.
```javascript
myWindow.webContents.session.setCertificateVerifyProc(function(hostname, cert, callback) {
if (hostname == 'github.com')
myWindow.webContents.session.setCertificateVerifyProc((hostname, cert, callback) => {
if (hostname === 'github.com')
callback(true);
else
callback(false);
@ -305,9 +305,9 @@ Sets the handler which can be used to respond to permission requests for the `se
Calling `callback(true)` will allow the permission and `callback(false)` will reject it.
```javascript
session.fromPartition(partition).setPermissionRequestHandler(function(webContents, permission, callback) {
session.fromPartition(partition).setPermissionRequestHandler((webContents, permission, callback) => {
if (webContents.getURL() === host) {
if (permission == "notifications") {
if (permission === "notifications") {
callback(false); // denied.
return;
}
@ -342,11 +342,11 @@ called with an `response` object when `listener` has done its work.
```javascript
// Modify the user agent for all requests to the following urls.
var filter = {
const filter = {
urls: ["https://*.github.com/*", "*://electron.github.io"]
};
session.defaultSession.webRequest.onBeforeSendHeaders(filter, function(details, callback) {
session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
details.requestHeaders['User-Agent'] = "MyAgent";
callback({cancel: false, requestHeaders: details.requestHeaders});
});

View file

@ -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').shell;
const { shell } = require('electron');
shell.openExternal('https://github.com');
```

View file

@ -19,13 +19,11 @@ scripts to be able to use those modules.
The main process script is just like a normal Node.js script:
```javascript
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const { app, BrowserWindow } = require('electron');
var window = null;
let window = null;
app.on('ready', function() {
app.on('ready', () => {
window = new BrowserWindow({width: 800, height: 600});
window.loadURL('https://github.com');
});
@ -39,7 +37,7 @@ extra ability to use node modules:
<html>
<body>
<script>
const remote = require('electron').remote;
const { remote } = require('electron');
console.log(remote.app.getVersion());
</script>
</body>
@ -50,16 +48,29 @@ To run your app, read [Run your app](../tutorial/quick-start.md#run-your-app).
## Destructuring assignment
If you are using CoffeeScript or Babel, you can also use
As of 0.37, you can use
[destructuring assignment][destructuring-assignment] to make it easier to use
built-in modules:
built-in modules.
```javascript
const {app, BrowserWindow} = require('electron')
const { app, BrowserWindow } = require('electron');
```
However if you are using plain JavaScript, you have to wait until Chrome fully
supports ES6.
If you need the entire `electron` module, you can require it and then using
destructuring to access the individual modules from `electron`.
```javascript
const electron = require('electron');
const { app, BrowserWindow } = electron;
```
This is equivalent to the following code:
```javascript
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
```
## Disable old styles of using built-in modules

View file

@ -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()) {

View file

@ -8,10 +8,10 @@ const app = electron.app;
const Menu = electron.Menu;
const Tray = electron.Tray;
var appIcon = null;
app.on('ready', function(){
let appIcon = null;
app.on('ready', () => {
appIcon = new Tray('/path/to/my/icon');
var contextMenu = Menu.buildFromTemplate([
const contextMenu = Menu.buildFromTemplate([
{ label: 'Item1', type: 'radio' },
{ label: 'Item2', type: 'radio' },
{ label: 'Item3', type: 'radio', checked: true },
@ -20,7 +20,6 @@ app.on('ready', function(){
appIcon.setToolTip('This is my application.');
appIcon.setContextMenu(contextMenu);
});
```
__Platform limitations:__

View file

@ -9,12 +9,12 @@ the [`BrowserWindow`](browser-window.md) object. An example of accessing the
`webContents` object:
```javascript
const BrowserWindow = require('electron').BrowserWindow;
const { BrowserWindow } = require('electron');
var win = new BrowserWindow({width: 800, height: 1500});
let win = new BrowserWindow({width: 800, height: 1500});
win.loadURL("http://github.com");
var webContents = win.webContents;
let webContents = win.webContents;
```
## Events
@ -398,10 +398,10 @@ Initiates a download of the resource at `url` without navigating. The
Returns URL of the current web page.
```javascript
var win = new BrowserWindow({width: 800, height: 600});
let win = new BrowserWindow({width: 800, height: 600});
win.loadURL("http://github.com");
var currentURL = win.webContents.getURL();
let currentURL = win.webContents.getURL();
```
### `webContents.getTitle()`
@ -671,22 +671,22 @@ By default, an empty `options` will be regarded as:
```
```javascript
const BrowserWindow = require('electron').BrowserWindow;
const { BrowserWindow } = require('electron');
const fs = require('fs');
var 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');
win.webContents.on("did-finish-load", function() {
win.webContents.on('did-finish-load', () => {
// Use default printing options
win.webContents.printToPDF({}, function(error, data) {
win.webContents.printToPDF({}, (error, data) => {
if (error) throw error;
fs.writeFile("/tmp/print.pdf", data, function(error) {
fs.writeFile('/tmp/print.pdf', data, (error) => {
if (error)
throw error;
console.log("Write PDF successfully.");
})
})
console.log('Write PDF successfully.');
});
});
});
```
@ -761,12 +761,13 @@ An example of sending messages from the main process to the renderer process:
```javascript
// In the main process.
var window = null;
app.on('ready', function() {
window = new BrowserWindow({width: 800, height: 600});
window.loadURL('file://' + __dirname + '/index.html');
window.webContents.on('did-finish-load', function() {
window.webContents.send('ping', 'whoooooooh!');
let mainWindow = 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!');
});
});
```
@ -776,7 +777,7 @@ app.on('ready', function() {
<html>
<body>
<script>
require('electron').ipcRenderer.on('ping', function(event, message) {
require('electron').ipcRenderer.on('ping', (event, message) => {
console.log(message); // Prints "whoooooooh!"
});
</script>
@ -892,8 +893,8 @@ Returns true if the process of saving page has been initiated successfully.
```javascript
win.loadURL('https://github.com');
win.webContents.on('did-finish-load', function() {
win.webContents.savePage('/tmp/test.html', 'HTMLComplete', function(error) {
win.webContents.on('did-finish-load', () => {
win.webContents.savePage('/tmp/test.html', 'HTMLComplete', (error) => {
if (!error)
console.log("Save page successfully");
});
@ -930,13 +931,13 @@ try {
console.log("Debugger attach failed : ", err);
};
win.webContents.debugger.on('detach', function(event, reason) {
win.webContents.debugger.on('detach', (event, reason) => {
console.log("Debugger detached due to : ", reason);
});
win.webContents.debugger.on('message', function(event, method, params) {
if (method == "Network.requestWillBeSent") {
if (params.request.url == "https://www.github.com")
win.webContents.debugger.on('message', (event, method, params) => {
if (method === "Network.requestWillBeSent") {
if (params.request.url === "https://www.github.com")
win.webContents.debugger.detach();
}
})

View file

@ -5,7 +5,7 @@
An example of zooming current page to 200%.
```javascript
var webFrame = require('electron').webFrame;
const { webFrame } = require('electron');
webFrame.setZoomFactor(2);
```

View file

@ -31,18 +31,20 @@ and displays a "loading..." message during the load time:
```html
<script>
onload = function() {
var webview = document.getElementById("foo");
var indicator = document.querySelector(".indicator");
onload = () => {
const webview = document.getElementById('foo');
const indicator = document.querySelector('.indicator');
var loadstart = function() {
indicator.innerText = "loading...";
const loadstart = () => {
indicator.innerText = 'loading...';
}
var loadstop = function() {
indicator.innerText = "";
const loadstop = () => {
indicator.innerText = '';
}
webview.addEventListener("did-start-loading", loadstart);
webview.addEventListener("did-stop-loading", loadstop);
webview.addEventListener('did-start-loading', loadstart);
webview.addEventListener('did-stop-loading', loadstop);
}
</script>
```
@ -211,7 +213,7 @@ The `webview` tag has the following methods:
**Example**
```javascript
webview.addEventListener("dom-ready", function() {
webview.addEventListener("dom-ready", () => {
webview.openDevTools();
});
```
@ -642,10 +644,12 @@ 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
webview.addEventListener('new-window', function(e) {
var protocol = require('url').parse(e.url).protocol;
const { shell } = require('electron');
webview.addEventListener('new-window', (e) => {
const protocol = require('url').parse(e.url).protocol;
if (protocol === 'http:' || protocol === 'https:') {
require('electron').shell.openExternal(e.url);
shell.openExternal(e.url);
}
});
```
@ -700,7 +704,7 @@ The following example code navigates the `webview` to `about:blank` when the
guest attempts to close itself.
```javascript
webview.addEventListener('close', function() {
webview.addEventListener('close', () => {
webview.src = 'about:blank';
});
```
@ -719,7 +723,7 @@ between guest page and embedder page:
```javascript
// In embedder page.
webview.addEventListener('ipc-message', function(event) {
webview.addEventListener('ipc-message', (event) => {
console.log(event.channel);
// Prints "pong"
});
@ -728,8 +732,8 @@ webview.send('ping');
```javascript
// In guest page.
var ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.on('ping', function() {
var { ipcRenderer } = require('electron');
ipcRenderer.on('ping', () => {
ipcRenderer.sendToHost('pong');
});
```

View file

@ -60,16 +60,16 @@ If you want a quick fix, you can make the variables global by changing your
code from this:
```javascript
app.on('ready', function() {
var tray = new Tray('/path/to/icon.png');
app.on('ready', () => {
const tray = new Tray('/path/to/icon.png');
})
```
to this:
```javascript
var tray = null;
app.on('ready', function() {
let tray = null;
app.on('ready', () => {
tray = new Tray('/path/to/icon.png');
})
```
@ -84,7 +84,7 @@ To solve this, you can turn off node integration in Electron:
```javascript
// In the main process.
var mainWindow = new BrowserWindow({
let mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: false
}

View file

@ -92,7 +92,7 @@ a value it and its type is noted below. If you were to listen and respond to
this event it might look something like this:
```javascript
Alarm.on('wake-up', function(time) {
Alarm.on('wake-up', (time) => {
console.log(time)
})
```

View file

@ -71,8 +71,8 @@ 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').BrowserWindow;
var win = new BrowserWindow({width: 800, height: 600});
const { BrowserWindow } = require('electron');
let win = new BrowserWindow({width: 800, height: 600});
win.loadURL('file:///path/to/example.asar/static/index.html');
```
@ -86,7 +86,7 @@ For example, to get a file with `$.get`:
```html
<script>
var $ = require('./jquery.min.js');
$.get('file:///path/to/example.asar/file.txt', function(data) {
$.get('file:///path/to/example.asar/file.txt', (data) => {
console.log(data);
});
</script>
@ -99,7 +99,7 @@ content of `asar` archive as file. For this purpose you can use the built-in
`original-fs` module which provides original `fs` APIs without `asar` support:
```javascript
var originalFs = require('original-fs');
const originalFs = require('original-fs');
originalFs.readFileSync('/path/to/example.asar');
```

View file

@ -18,7 +18,7 @@ the currently running operating system's native notification APIs to display it.
**Note:** Since this is an HTML5 API it is only available in the renderer process.
```javascript
var myNotification = new Notification('Title', {
let myNotification = new Notification('Title', {
body: 'Lorem Ipsum Dolor Sit Amet'
});
@ -117,8 +117,8 @@ const electron = require('electron');
const app = electron.app;
const Menu = electron.Menu;
var dockMenu = Menu.buildFromTemplate([
{ label: 'New Window', click: function() { console.log('New Window'); } },
const dockMenu = Menu.buildFromTemplate([
{ label: 'New Window', click: () => { console.log('New Window'); } },
{ label: 'New Window with Settings', submenu: [
{ label: 'Basic' },
{ label: 'Pro'}
@ -209,24 +209,25 @@ You can use [BrowserWindow.setThumbarButtons][setthumbarbuttons] to set
thumbnail toolbar in your application:
```javascript
const BrowserWindow = require('electron').BrowserWindow;
const { BrowserWindow } = require('electron');
const path = require('path');
var win = new BrowserWindow({
let win = new BrowserWindow({
width: 800,
height: 600
});
win.setThumbarButtons([
{
tooltip: "button1",
icon: path.join(__dirname, 'button1.png'),
click: function() { console.log("button2 clicked"); }
click: () => { console.log("button2 clicked"); }
},
{
tooltip: "button2",
icon: path.join(__dirname, 'button2.png'),
flags:['enabled', 'dismissonclick'],
click: function() { console.log("button2 clicked."); }
click: () => { console.log("button2 clicked."); }
}
]);
```
@ -266,7 +267,7 @@ To set the progress bar for a Window, you can use the
[BrowserWindow.setProgressBar][setprogressbar] API:
```javascript
var window = new BrowserWindow({...});
let window = new BrowserWindow({...});
window.setProgressBar(0.5);
```
@ -293,7 +294,7 @@ To set the overlay icon for a window, you can use the
[BrowserWindow.setOverlayIcon][setoverlayicon] API:
```javascript
var window = new BrowserWindow({...});
let window = new BrowserWindow({...});
window.setOverlayIcon('path/to/overlay.png', 'Description for overlay');
```
@ -315,7 +316,7 @@ To set the represented file of window, you can use the
[BrowserWindow.setDocumentEdited][setdocumentedited] APIs:
```javascript
var window = new BrowserWindow({...});
let window = new BrowserWindow({...});
window.setRepresentedFilename('/etc/passwd');
window.setDocumentEdited(true);
```

View file

@ -10,10 +10,11 @@ const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
var onlineStatusWindow;
app.on('ready', function() {
let onlineStatusWindow;
app.on('ready', () => {
onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
onlineStatusWindow.loadURL('file://' + __dirname + '/online-status.html');
onlineStatusWindow.loadURL(`file://${__dirname}/online-status.html`);
});
```
@ -24,7 +25,7 @@ _online-status.html_
<html>
<body>
<script>
var alertOnlineStatus = function() {
const alertOnlineStatus = () => {
window.alert(navigator.onLine ? 'online' : 'offline');
};
@ -51,13 +52,14 @@ const app = electron.app;
const ipcMain = electron.ipcMain;
const BrowserWindow = electron.BrowserWindow;
var onlineStatusWindow;
app.on('ready', function() {
let onlineStatusWindow;
app.on('ready', () => {
onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
onlineStatusWindow.loadURL('file://' + __dirname + '/online-status.html');
onlineStatusWindow.loadURL(`file://${__dirname}/online-status.html`);
});
ipcMain.on('online-status-changed', function(event, status) {
ipcMain.on('online-status-changed', (event, status) => {
console.log(status);
});
```
@ -69,8 +71,8 @@ _online-status.html_
<html>
<body>
<script>
const ipcRenderer = require('electron').ipcRenderer;
var updateOnlineStatus = function() {
const { ipcRenderer } = require('electron');
const updateOnlineStatus = () => {
ipcRenderer.send('online-status-changed', navigator.onLine ? 'online' : 'offline');
};

View file

@ -82,54 +82,54 @@ example being:
```javascript
const electron = require('electron')
// Module to control application life.
const app = electron.app
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
const BrowserWindow = electron.BrowserWindow;
// 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 mainWindow;
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600})
mainWindow = new BrowserWindow({width: 800, height: 600});
// and load the index.html of the app.
mainWindow.loadURL('file://' + __dirname + '/index.html')
mainWindow.loadURL(`file://${__dirname}/index.html`);
// Open the DevTools.
mainWindow.webContents.openDevTools()
mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', function () {
mainWindow.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
})
mainWindow = null;
});
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
app.on('ready', createWindow);
// Quit when all windows are closed.
app.on('window-all-closed', function () {
app.on('window-all-closed', () => {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
app.quit();
}
})
});
app.on('activate', function () {
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) {
createWindow()
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.

View file

@ -28,7 +28,7 @@ app.commandLine.appendSwitch('ppapi-flash-path', '/path/to/libpepflashplayer.so'
// Optional: Specify flash version, for example, v17.0.0.169
app.commandLine.appendSwitch('ppapi-flash-version', '17.0.0.169');
app.on('ready', function() {
app.on('ready', () => {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
@ -36,7 +36,7 @@ app.on('ready', function() {
plugins: true
}
});
mainWindow.loadURL('file://' + __dirname + '/index.html');
mainWindow.loadURL(`file://${__dirname}/index.html`);
// Something else
});
```

View file

@ -43,7 +43,7 @@ and where to find Electron's binary:
```javascript
const webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder()
const driver = new webdriver.Builder()
// The "9515" is the port opened by chrome driver.
.usingServer('http://localhost:9515')
.withCapabilities({
@ -58,7 +58,7 @@ var driver = new webdriver.Builder()
driver.get('http://www.google.com');
driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');
driver.findElement(webdriver.By.name('btnG')).click();
driver.wait(function() {
driver.wait(() => {
return driver.getTitle().then(function(title) {
return title === 'webdriver - Google Search';
});
@ -94,29 +94,29 @@ $ npm install webdriverio
```javascript
const webdriverio = require('webdriverio');
var options = {
host: "localhost", // Use localhost as chrome driver server
port: 9515, // "9515" is the port opened by chrome driver.
desiredCapabilities: {
browserName: 'chrome',
chromeOptions: {
binary: '/Path-to-Your-App/electron', // Path to your Electron binary.
args: [/* cli arguments */] // Optional, perhaps 'app=' + /path/to/your/app/
}
const options = {
host: 'localhost', // Use localhost as chrome driver server
port: 9515, // "9515" is the port opened by chrome driver.
desiredCapabilities: {
browserName: 'chrome',
chromeOptions: {
binary: '/Path-to-Your-App/electron', // Path to your Electron binary.
args: [/* cli arguments */] // Optional, perhaps 'app=' + /path/to/your/app/
}
}
};
var client = webdriverio.remote(options);
client
.init()
.url('http://google.com')
.setValue('#q', 'webdriverio')
.click('#btnG')
.getTitle().then(function(title) {
console.log('Title was: ' + title);
})
.end();
.init()
.url('http://google.com')
.setValue('#q', 'webdriverio')
.click('#btnG')
.getTitle().then((title) => {
console.log('Title was: ' + title);
})
.end();
```
## Workflow

View file

@ -59,8 +59,8 @@ 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');
var mainWindow = null;
app.on('ready', function() {
let mainWindow = null;
app.on('ready', () => {
mainWindow = new BrowserWindow({
webPreferences: {
// The `plugins` have to be enabled.