Merge remote-tracking branch 'upstream/master' into speedup-gpu

This commit is contained in:
gellert 2016-08-01 12:00:34 +02:00
commit 439ad94afe
85 changed files with 1592 additions and 757 deletions

View file

@ -6,10 +6,10 @@ 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();
});
app.quit()
})
```
## Events
@ -192,15 +192,17 @@ certificate you should prevent the default behavior with
`event.preventDefault()` and call `callback(true)`.
```javascript
const {app} = require('electron')
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
if (url === 'https://github.com') {
// Verification logic.
event.preventDefault();
callback(true);
event.preventDefault()
callback(true)
} else {
callback(false);
callback(false)
}
});
})
```
### Event: 'select-client-certificate'
@ -228,10 +230,12 @@ and `callback` needs to be called with an entry filtered from the list. Using
certificate from the store.
```javascript
const {app} = require('electron')
app.on('select-client-certificate', (event, webContents, url, list, callback) => {
event.preventDefault();
callback(list[0]);
});
event.preventDefault()
callback(list[0])
})
```
### Event: 'login'
@ -259,10 +263,12 @@ should prevent the default behavior with `event.preventDefault()` and call
`callback(username, password)` with the credentials.
```javascript
const {app} = require('electron')
app.on('login', (event, webContents, request, authInfo, callback) => {
event.preventDefault();
callback('username', 'secret');
});
event.preventDefault()
callback('username', 'secret')
})
```
### Event: 'gpu-process-crashed'
@ -331,6 +337,8 @@ An example of restarting current instance immediately and adding a new command
line argument to the new instance:
```javascript
const {app} = require('electron')
app.relaunch({args: process.argv.slice(1) + ['--relaunch']})
app.exit(0)
```
@ -537,24 +545,24 @@ An example of activating the window of primary instance when a second instance
starts:
```javascript
let myWindow = null;
const {app} = require('electron')
let myWindow = null
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();
myWindow.focus();
if (myWindow.isMinimized()) myWindow.restore()
myWindow.focus()
}
});
})
if (shouldQuit) {
app.quit();
return;
app.quit()
}
// Create myWindow, load the rest of the app, etc...
app.on('ready', () => {
});
})
```
### `app.releaseSingleInstance()`

View file

@ -6,8 +6,8 @@
// In the main process.
const {BrowserWindow} = require('electron')
// Or in the renderer process.
const {BrowserWindow} = require('electron').remote
// Or use `remote` from the renderer process.
// const {BrowserWindow} = require('electron').remote
let win = new BrowserWindow({width: 800, height: 600})
win.on('closed', () => {
@ -35,6 +35,7 @@ process has done drawing for the first time, showing window after this event
will have no visual flash:
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({show: false})
win.once('ready-to-show', () => {
win.show()
@ -52,6 +53,8 @@ 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:
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({backgroundColor: '#2e2c29'})
win.loadURL('https://github.com')
```
@ -64,8 +67,12 @@ to set `backgroundColor` to make app feel more native.
By using `parent` option, you can create child windows:
```javascript
const {BrowserWindow} = require('electron')
let top = new BrowserWindow()
let child = new BrowserWindow({parent: top})
child.show()
top.show()
```
The `child` window will always show on top of the `top` window.
@ -76,6 +83,8 @@ 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:
```javascript
const {BrowserWindow} = require('electron')
let child = new BrowserWindow({parent: top, modal: true, show: false})
child.loadURL('https://github.com')
child.once('ready-to-show', () => {
@ -310,14 +319,14 @@ close. For example:
```javascript
window.onbeforeunload = (e) => {
console.log('I do not want to be closed');
console.log('I do not want to be closed')
// Unlike usual browsers that a message box will be prompted to users, returning
// a non-void value will silently cancel the close.
// It is recommended to use the dialog API to let the user confirm closing the
// application.
e.returnValue = false;
};
e.returnValue = false
}
```
#### Event: 'closed'
@ -416,12 +425,14 @@ Commands are lowercased, underscores are replaced with hyphens, and the
e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`.
```javascript
someWindow.on('app-command', (e, cmd) => {
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.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();
if (cmd === 'browser-backward' && win.webContents.canGoBack()) {
win.webContents.goBack()
}
});
})
```
#### Event: 'scroll-touch-begin' _macOS_
@ -498,7 +509,10 @@ an Object containing `name` and `version` properties.
To check if a DevTools extension is installed you can run the following:
```javascript
const {BrowserWindow} = require('electron')
let installed = BrowserWindow.getDevToolsExtensions().hasOwnProperty('devtron')
console.log(installed)
```
**Note:** This API cannot be called before the `ready` event of the `app` module
@ -509,8 +523,10 @@ is emitted.
Objects created with `new BrowserWindow` have the following properties:
```javascript
const {BrowserWindow} = require('electron')
// 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.webContents`
@ -613,7 +629,7 @@ Returns a boolean, whether the window is in fullscreen mode.
#### `win.setAspectRatio(aspectRatio[, extraSize])` _macOS_
* `aspectRatio` The aspect ratio to maintain for some portion of the
* `aspectRatio` Float - The aspect ratio to maintain for some portion of the
content view.
* `extraSize` Object (optional) - The extra size not to be included while
maintaining the aspect ratio.
@ -806,13 +822,19 @@ window.
#### `win.setSheetOffset(offsetY[, offsetX])` _macOS_
* `offsetY` Float
* `offsetX` Float (optional)
Changes the attachment point for sheets on macOS. By default, sheets are
attached just below the window frame, but you may want to display them beneath
a HTML-rendered toolbar. For example:
```javascript
let toolbarRect = document.getElementById('toolbar').getBoundingClientRect();
win.setSheetOffset(toolbarRect.height);
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
let toolbarRect = document.getElementById('toolbar').getBoundingClientRect()
win.setSheetOffset(toolbarRect.height)
```
#### `win.flashFrame(flag)`

View file

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

View file

@ -5,16 +5,17 @@
The following example shows how to write a string to the clipboard:
```javascript
const {clipboard} = require('electron');
clipboard.writeText('Example String');
const {clipboard} = require('electron')
clipboard.writeText('Example String')
```
On X Window systems, there is also a selection clipboard. To manipulate it
you need to pass `selection` to each method:
```javascript
clipboard.writeText('Example String', 'selection');
console.log(clipboard.readText('selection'));
const {clipboard} = require('electron')
clipboard.writeText('Example String', 'selection')
console.log(clipboard.readText('selection'))
```
## Methods
@ -109,7 +110,8 @@ Returns an array of supported formats for the clipboard `type`.
Returns whether the clipboard supports the format of specified `data`.
```javascript
console.log(clipboard.has('<p>selection</p>'));
const {clipboard} = require('electron')
console.log(clipboard.has('<p>selection</p>'))
```
### `clipboard.read(data[, type])` _Experimental_
@ -130,6 +132,7 @@ Reads `data` from the clipboard.
* `type` String (optional)
```javascript
clipboard.write({text: 'test', html: "<b>test</b>"});
const {clipboard} = require('electron')
clipboard.write({text: 'test', html: '<b>test</b>'})
```
Writes `data` to the clipboard.

View file

@ -8,22 +8,22 @@ 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, () => {
console.log('Tracing started');
console.log('Tracing started')
setTimeout(() => {
contentTracing.stopRecording('', (path) => {
console.log('Tracing data recorded to ' + path);
});
}, 5000);
});
console.log('Tracing data recorded to ' + path)
})
}, 5000)
})
```
## Methods

View file

@ -6,14 +6,14 @@ 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',
companyName: 'YourCompany',
submitURL: 'https://your-domain.com/url-to-submit',
autoSubmit: true
});
})
```
For setting up a server to accept and process crash reports, you can use

View file

@ -1,14 +1,17 @@
# desktopCapturer
> List `getUserMedia` sources for capturing audio, video, and images from a
microphone, camera, or screen.
> Access information about media sources that can be used to capture audio and
> video from the desktop using the [`navigator.webkitGetUserMedia`] API.
The following example shows how to capture video from a desktop window whose
title is `Electron`:
```javascript
// In the renderer process.
const {desktopCapturer} = require('electron');
const {desktopCapturer} = require('electron')
desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
if (error) throw error;
if (error) throw error
for (let i = 0; i < sources.length; ++i) {
if (sources[i].name === 'Electron') {
navigator.webkitGetUserMedia({
@ -23,29 +26,28 @@ desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
maxHeight: 720
}
}
}, gotStream, getUserMediaError);
return;
}, handleStream, handleError)
return
}
}
});
})
function gotStream(stream) {
document.querySelector('video').src = URL.createObjectURL(stream);
function handleStream (stream) {
document.querySelector('video').src = URL.createObjectURL(stream)
}
function getUserMediaError(e) {
console.log('getUserMediaError');
function handleError (e) {
console.log(e)
}
```
When creating a constraints object for the `navigator.webkitGetUserMedia` call,
if you are using a source from `desktopCapturer` your `chromeMediaSource` must
be set to `"desktop"` and your `audio` must be set to `false`.
To capture video from a source provided by `desktopCapturer` the constraints
passed to [`navigator.webkitGetUserMedia`] must include
`chromeMediaSource: 'desktop'`, and `audio: false`.
If you wish to
capture the audio and video from the entire desktop you can set
`chromeMediaSource` to `"screen"` and `audio` to `true`. When using this method
you cannot specify a `chromeMediaSourceId`.
To capture both audio and video from the entire desktop the constraints passed
to [`navigator.webkitGetUserMedia`] must include `chromeMediaSource: 'screen'`,
and `audio: true`, but should not include a `chromeMediaSourceId` constraint.
## Methods
@ -56,24 +58,28 @@ The `desktopCapturer` module has the following methods:
* `options` Object
* `types` Array - An array of String that lists the types of desktop sources
to be captured, available types are `screen` and `window`.
* `thumbnailSize` Object (optional) - The suggested size that thumbnail should
be scaled, it is `{width: 150, height: 150}` by default.
* `thumbnailSize` Object (optional) - The suggested size that the media source
thumbnail should be scaled to, defaults to `{width: 150, height: 150}`.
* `callback` Function
Starts a request to get all desktop sources, `callback` will be called with
`callback(error, sources)` when the request is completed.
Starts gathering information about all available desktop media sources,
and calls `callback(error, sources)` when finished.
The `sources` is an array of `Source` objects, each `Source` represents a
captured screen or individual window, and has following properties:
`sources` is an array of `Source` objects, each `Source` represents a
screen or an individual window that can be captured, and has the following
properties:
* `id` String - The id of the captured window or screen used in
`navigator.webkitGetUserMedia`. The format looks like `window:XX` or
`screen:XX` where `XX` is a random generated number.
* `name` String - The described name of the capturing screen or window. If the
source is a screen, the name will be `Entire Screen` or `Screen <index>`; if
it is a window, the name will be the window's title.
* `thumbnail` [NativeImage](native-image.md) - A thumbnail native image.
* `id` String - The identifier of a window or screen that can be used as a
`chromeMediaSourceId` constraint when calling
[`navigator.webkitGetUserMedia`]. The format of the identifier will be
`window:XX` or `screen:XX`, where `XX` is a random generated number.
* `name` String - A screen source will be named either `Entire Screen` or
`Screen <index>`, while the name of a window source will match the window
title.
* `thumbnail` [NativeImage](native-image.md) - A thumbnail image. **Note:**
There is no guarantee that the size of the thumbnail is the same as the
`thumnbailSize` specified in the `options` passed to
`desktopCapturer.getSources`. The actual size depends on the scale of the
screen or window.
**Note:** There is no guarantee that the size of `source.thumbnail` is always
the same as the `thumnbailSize` in `options`. It also depends on the scale of
the screen or window.
[`navigator.webkitGetUserMedia`]: https://developer.mozilla.org/en/docs/Web/API/Navigator/getUserMedia

View file

@ -5,17 +5,16 @@
An example of showing a dialog to select multiple files and directories:
```javascript
let win = ...; // BrowserWindow in which to show the dialog
const {dialog} = require('electron');
console.log(dialog.showOpenDialog({properties: ['openFile', 'openDirectory', 'multiSelections']}));
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
console.log(dialog)
```
## Methods
@ -42,7 +41,7 @@ otherwise it returns `undefined`.
The `filters` specifies an array of file types that can be displayed or
selected when you want to limit the user to a specific type. For example:
```javascript
```
{
filters: [
{name: 'Images', extensions: ['jpg', 'png', 'gif']},

View file

@ -8,6 +8,8 @@ control the download item.
```javascript
// In the main process.
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.webContents.session.on('will-download', (event, item, webContents) => {
// Set the save path, making Electron not to prompt a save dialog.
item.setSavePath('/tmp/save.pdf')
@ -78,6 +80,12 @@ The API is only available in session's `will-download` callback function.
If user doesn't set the save path via the API, Electron will use the original
routine to determine the save path(Usually prompts a save dialog).
### `downloadItem.getSavePath()`
Returns the save path of the download item. This will be either the path
set via `downloadItem.setSavePath(path)` or the path selected from the shown
save dialog.
### `downloadItem.pause()`
Pauses the download.

View file

@ -15,19 +15,19 @@ Example on getting a real path from a dragged-onto-the-app file:
</div>
<script>
const holder = document.getElementById('holder');
const holder = document.getElementById('holder')
holder.ondragover = () => {
return false;
};
}
holder.ondragleave = holder.ondragend = () => {
return false;
};
}
holder.ondrop = (e) => {
e.preventDefault();
e.preventDefault()
for (let f of e.dataTransfer.files) {
console.log('File(s) you dragged here: ', f.path);
console.log('File(s) you dragged here: ', f.path)
}
return false;
};
}
</script>
```

View file

@ -16,6 +16,7 @@ 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})
win.show()
```
### Alternatives on macOS
@ -28,7 +29,9 @@ the window controls ("traffic lights") for standard window actions.
You can do so by specifying the new `titleBarStyle` option:
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({titleBarStyle: 'hidden'})
win.show()
```
## Transparent window
@ -37,7 +40,9 @@ By setting the `transparent` option to `true`, you can also make the frameless
window transparent:
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({transparent: true, frame: false})
win.show()
```
### Limitations
@ -66,6 +71,8 @@ events, you can call the [win.setIgnoreMouseEvents(ignore)][ignore-mouse-events]
API:
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.setIgnoreMouseEvents(true)
```

View file

@ -11,29 +11,29 @@ not have the keyboard focus. You should not use this module until the `ready`
event of the app module is emitted.
```javascript
const {app, globalShortcut} = require('electron');
const {app, globalShortcut} = require('electron')
app.on('ready', () => {
// Register a 'CommandOrControl+X' shortcut listener.
const ret = globalShortcut.register('CommandOrControl+X', () => {
console.log('CommandOrControl+X is pressed');
});
console.log('CommandOrControl+X is pressed')
})
if (!ret) {
console.log('registration failed');
console.log('registration failed')
}
// Check whether a shortcut is registered.
console.log(globalShortcut.isRegistered('CommandOrControl+X'));
});
console.log(globalShortcut.isRegistered('CommandOrControl+X'))
})
app.on('will-quit', () => {
// Unregister a shortcut.
globalShortcut.unregister('CommandOrControl+X');
globalShortcut.unregister('CommandOrControl+X')
// Unregister all shortcuts.
globalShortcut.unregisterAll();
});
globalShortcut.unregisterAll()
})
```
## Methods

View file

@ -23,27 +23,27 @@ 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');
});
console.log(arg) // prints "ping"
event.sender.send('asynchronous-reply', 'pong')
})
ipcMain.on('synchronous-message', (event, arg) => {
console.log(arg); // prints "ping"
event.returnValue = 'pong';
});
console.log(arg) // prints "ping"
event.returnValue = 'pong'
})
```
```javascript
// In renderer process (web page).
const {ipcRenderer} = require('electron');
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong"
const {ipcRenderer} = require('electron')
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // prints "pong"
ipcRenderer.on('asynchronous-reply', (event, arg) => {
console.log(arg); // prints "pong"
});
ipcRenderer.send('asynchronous-message', 'ping');
console.log(arg) // prints "pong"
})
ipcRenderer.send('asynchronous-message', 'ping')
```
## Listening for Messages

View file

@ -15,18 +15,18 @@ the user right clicks the page:
```html
<!-- index.html -->
<script>
const {remote} = require('electron');
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}));
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', (e) => {
e.preventDefault();
menu.popup(remote.getCurrentWindow());
}, false);
e.preventDefault()
menu.popup(remote.getCurrentWindow())
}, false)
</script>
```
@ -34,6 +34,8 @@ An example of creating the application menu in the render process with the
simple template API:
```javascript
const {Menu} = require('electron')
const template = [
{
label: 'Edit',
@ -64,7 +66,7 @@ const template = [
},
{
role: 'selectall'
},
}
]
},
{
@ -73,8 +75,8 @@ const template = [
{
label: 'Reload',
accelerator: 'CmdOrCtrl+R',
click(item, focusedWindow) {
if (focusedWindow) focusedWindow.reload();
click (item, focusedWindow) {
if (focusedWindow) focusedWindow.reload()
}
},
{
@ -83,11 +85,10 @@ const template = [
{
label: 'Toggle Developer Tools',
accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
click(item, focusedWindow) {
if (focusedWindow)
focusedWindow.webContents.toggleDevTools();
click (item, focusedWindow) {
if (focusedWindow) focusedWindow.webContents.toggleDevTools()
}
},
}
]
},
{
@ -98,7 +99,7 @@ const template = [
},
{
role: 'close'
},
}
]
},
{
@ -106,14 +107,14 @@ const template = [
submenu: [
{
label: 'Learn More',
click() { require('electron').shell.openExternal('http://electron.atom.io'); }
},
click () { require('electron').shell.openExternal('http://electron.atom.io') }
}
]
},
];
}
]
if (process.platform === 'darwin') {
const name = require('electron').remote.app.getName();
const name = require('electron').remote.app.getName()
template.unshift({
label: name,
submenu: [
@ -144,9 +145,9 @@ if (process.platform === 'darwin') {
},
{
role: 'quit'
},
}
]
});
})
// Window menu.
template[3].submenu = [
{
@ -170,11 +171,11 @@ if (process.platform === 'darwin') {
label: 'Bring All to Front',
role: 'front'
}
];
]
}
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
```
## Class: Menu
@ -227,16 +228,14 @@ The `menu` object has the following instance methods:
#### `menu.popup([browserWindow, x, y, positioningItem])`
* `browserWindow` BrowserWindow (optional) - Default is `null`.
* `x` Number (optional) - Default is -1.
* `y` Number (**required** if `x` is used) - Default is -1.
* `browserWindow` BrowserWindow (optional) - Default is `BrowserWindow.getFocusedWindow()`.
* `x` Number (optional) - Default is the current mouse cursor position.
* `y` Number (**required** if `x` is used) - Default is the current mouse cursor position.
* `positioningItem` Number (optional) _macOS_ - The index of the menu item to
be positioned under the mouse cursor at the specified coordinates. Default is
-1.
Pops up this menu as a context menu in the `browserWindow`. You can optionally
provide a `x, y` coordinate to place the menu at, otherwise it will be placed
at the current mouse cursor position.
Pops up this menu as a context menu in the `browserWindow`.
#### `menu.append(menuItem)`
@ -322,7 +321,7 @@ the first item.
Template:
```javascript
```
[
{label: '4', id: '4'},
{label: '5', id: '5'},
@ -344,7 +343,7 @@ Menu:
Template:
```javascript
```
[
{label: 'a', position: 'endof=letters'},
{label: '1', position: 'endof=numbers'},

View file

@ -9,15 +9,20 @@ For example, when creating a tray or setting a window's icon, you can pass an
image file path as a `String`:
```javascript
const {BrowserWindow, Tray} = require('electron')
const appIcon = new Tray('/Users/somebody/images/icon.png')
let win = new BrowserWindow({icon: '/Users/somebody/images/window.png'})
console.log(appIcon, win)
```
Or read the image from the clipboard which returns a `nativeImage`:
```javascript
const {clipboard, Tray} = require('electron')
const image = clipboard.readImage()
const appIcon = new Tray(image)
console.log(appIcon)
```
## Supported Formats
@ -30,6 +35,8 @@ quality it is recommended to include at least the following sizes in the icon:
* 16x16
* 32x32
* 40x40
* 48x48
* 64x64
* 256x256
@ -55,7 +62,9 @@ images/
```javascript
const {Tray} = require('electron')
let appIcon = new Tray('/Users/somebody/images/icon.png')
console.log(appIcon)
```
Following suffixes for DPI are also supported:
@ -105,8 +114,10 @@ Creates an empty `NativeImage` instance.
Creates a new `NativeImage` instance from a file located at `path`.
```javascript
const {nativeImage} = require('electron')
const nativeImage = require('electron').nativeImage
let image = nativeImage.createFromPath('/Users/somebody/images/icon.png')
console.log(image)
```
### `nativeImage.createFromBuffer(buffer[, scaleFactor])`

View file

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

View file

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

View file

@ -16,12 +16,12 @@ the global scope when node integration is turned off:
```javascript
// preload.js
const _setImmediate = setImmediate;
const _clearImmediate = clearImmediate;
const _setImmediate = setImmediate
const _clearImmediate = clearImmediate
process.once('loaded', () => {
global.setImmediate = _setImmediate;
global.clearImmediate = _clearImmediate;
});
global.setImmediate = _setImmediate
global.clearImmediate = _clearImmediate
})
```
## Properties

View file

@ -6,19 +6,19 @@ 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', () => {
protocol.registerFileProtocol('atom', (request, callback) => {
const url = request.url.substr(7);
callback({path: path.normalize(__dirname + '/' + url)});
const url = request.url.substr(7)
callback({path: path.normalize(`${__dirname}/${url}`)})
}, (error) => {
if (error)
console.error('Failed to register protocol');
});
});
if (error) 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,12 @@ 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']);
const {app, protocol} = require('electron')
protocol.registerStandardSchemes(['atom'])
app.on('ready', () => {
protocol.registerHttpProtocol('atom', ...);
});
protocol.registerHttpProtocol('atom', '...')
})
```
**Note:** This method can only be used before the `ready` event of the `app`
@ -119,12 +121,13 @@ should be called with either a `Buffer` object or an object that has the `data`,
Example:
```javascript
const {protocol} = require('electron')
protocol.registerBufferProtocol('atom', (request, callback) => {
callback({mimeType: 'text/html', data: new Buffer('<h5>Response</h5>')});
callback({mimeType: 'text/html', data: new Buffer('<h5>Response</h5>')})
}, (error) => {
if (error)
console.error('Failed to register protocol');
});
if (error) console.error('Failed to register protocol')
})
```
### `protocol.registerStringProtocol(scheme, handler[, completion])`

View file

@ -14,10 +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;
let win = new BrowserWindow({width: 800, height: 600});
win.loadURL('https://github.com');
const {BrowserWindow} = require('electron').remote
let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('https://github.com')
```
**Note:** for the reverse (access the renderer process from the main process),
@ -70,23 +69,22 @@ For instance you can't use a function from the renderer process in an
```javascript
// main process mapNumbers.js
exports.withRendererCallback = (mapper) => {
return [1,2,3].map(mapper);
};
return [1, 2, 3].map(mapper)
}
exports.withLocalCallback = () => {
return [1,2,3].map(x => x + 1);
};
return [1, 2, 3].map(x => x + 1)
}
```
```javascript
// renderer process
const mapNumbers = require('electron').remote.require('./mapNumbers');
const mapNumbers = require('electron').remote.require('./mapNumbers')
const withRendererCb = mapNumbers.withRendererCallback(x => x + 1)
const withLocalCb = mapNumbers.withLocalCallback()
const withRendererCb = mapNumbers.withRendererCallback(x => x + 1);
const withLocalCb = mapNumbers.withLocalCallback();
console.log(withRendererCb, withLocalCb); // [undefined, undefined, undefined], [2, 3, 4]
console.log(withRendererCb, withLocalCb)
// [undefined, undefined, undefined], [2, 3, 4]
```
As you can see, the renderer callback's synchronous return value was not as
@ -100,9 +98,9 @@ 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', () => {
// blabla...
});
require('electron').remote.getCurrentWindow().on('close', () => {
// window was closed...
})
```
But remember the callback is referenced by the main process until you
@ -124,7 +122,8 @@ The built-in modules in the main process are added as getters in the `remote`
module, so you can use them directly like the `electron` module.
```javascript
const app = remote.app;
const app = require('electron').remote.app
console.log(app)
```
## Methods

View file

@ -21,7 +21,8 @@ let win
app.on('ready', () => {
const {width, height} = electron.screen.getPrimaryDisplay().workAreaSize
win = new BrowserWindow({width, height})
});
win.loadURL('https://github.com')
})
```
Another example of creating a window in the external display:
@ -43,6 +44,7 @@ app.on('ready', () => {
x: externalDisplay.bounds.x + 50,
y: externalDisplay.bounds.y + 50
})
win.loadURL('https://github.com')
}
})
```

View file

@ -1,4 +1,4 @@
# session
# session
> Manage browser sessions, cookies, cache, proxy settings, etc.
@ -8,12 +8,13 @@ You can also access the `session` of existing pages by using the `session`
property of [`WebContents`](web-contents.md), or from the `session` module.
```javascript
const {session, BrowserWindow} = require('electron')
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('http://github.com')
const ses = win.webContents.session
console.log(ses.getUserAgent())
```
## Methods
@ -52,9 +53,9 @@ Returns the default session object of the app.
You can create a `Session` object in the `session` module:
```javascript
const session = require('electron').session;
const ses = session.fromPartition('persist:name');
const {session} = require('electron')
const ses = session.fromPartition('persist:name')
console.log(ses.getUserAgent())
```
### Instance Events
@ -73,12 +74,13 @@ Calling `event.preventDefault()` will cancel the download and `item` will not be
available from next tick of the process.
```javascript
const {session} = require('electron')
session.defaultSession.on('will-download', (event, item, webContents) => {
event.preventDefault();
event.preventDefault()
require('request')(item.getURL(), (data) => {
require('fs').writeFileSync('/somewhere', data);
});
});
require('fs').writeFileSync('/somewhere', data)
})
})
```
### Instance Methods
@ -220,13 +222,13 @@ Emulates network with the given configuration for the `session`.
```javascript
// To emulate a GPRS connection with 50kbps throughput and 500 ms latency.
window.webContents.session.enableNetworkEmulation({
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
});
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
})
// To emulate a network outage.
window.webContents.session.enableNetworkEmulation({offline: true});
window.webContents.session.enableNetworkEmulation({offline: true})
```
#### `ses.disableNetworkEmulation()`
@ -247,12 +249,12 @@ Calling `setCertificateVerifyProc(null)` will revert back to default certificate
verify proc.
```javascript
myWindow.webContents.session.setCertificateVerifyProc((hostname, cert, callback) => {
if (hostname === 'github.com')
callback(true);
else
callback(false);
});
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.webContents.session.setCertificateVerifyProc((hostname, cert, callback) => {
callback(hostname === 'github.com')
})
```
#### `ses.setPermissionRequestHandler(handler)`
@ -267,16 +269,14 @@ 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((webContents, permission, callback) => {
if (webContents.getURL() === host) {
if (permission === 'notifications') {
callback(false); // denied.
return;
}
const {session} = require('electron')
session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => {
if (webContents.getURL() === 'some-host' && permission === 'notifications') {
return callback(false) // denied.
}
callback(true);
});
callback(true)
})
```
#### `ses.clearHostResolverCache([callback])`
@ -294,6 +294,7 @@ Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate
authentication.
```javascript
const {session} = require('electron')
// consider any url ending with `example.com`, `foobar.com`, `baz`
// for integrated authentication.
session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz')
@ -340,13 +341,12 @@ const {app, session} = require('electron')
const path = require('path')
app.on('ready', function () {
const protocol = session.fromPartition(partitionName).protocol
const protocol = session.fromPartition('some-partition').protocol
protocol.registerFileProtocol('atom', function (request, callback) {
var url = request.url.substr(7)
callback({path: path.normalize(__dirname + '/' + url)})
callback({path: path.normalize(`${__dirname}/${url}`)})
}, function (error) {
if (error)
console.error('Failed to register protocol')
if (error) console.error('Failed to register protocol')
})
})
```
@ -359,22 +359,23 @@ The `Cookies` class gives you ability to query and modify cookies. Instances of
For example:
```javascript
const {session} = require('electron')
// Query all cookies.
session.defaultSession.cookies.get({}, (error, cookies) => {
console.log(cookies)
console.log(error, cookies)
})
// Query all cookies associated with a specific url.
session.defaultSession.cookies.get({url: 'http://www.github.com'}, (error, cookies) => {
console.log(cookies)
console.log(error, 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'}
session.defaultSession.cookies.set(cookie, (error) => {
if (error)
console.error(error)
if (error) console.error(error)
})
```
@ -464,13 +465,15 @@ called with an `response` object when `listener` has done its work.
An example of adding `User-Agent` header for requests:
```javascript
const {session} = require('electron')
// Modify the user agent for all requests to the following urls.
const filter = {
urls: ['https://*.github.com/*', '*://electron.github.io']
}
session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
details.requestHeaders['User-Agent'] = "MyAgent"
details.requestHeaders['User-Agent'] = 'MyAgent'
callback({cancel: false, requestHeaders: details.requestHeaders})
})
```

View file

@ -7,9 +7,9 @@ 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');
shell.openExternal('https://github.com')
```
## Methods
@ -48,3 +48,37 @@ Move the given file to trash and returns a boolean status for the operation.
### `shell.beep()`
Play the beep sound.
### `shell.writeShortcutLink(shortcutPath[, operation], options)` _Windows_
* `shortcutPath` String
* `operation` String (optional) - Default is `create`, can be one of followings:
* `create` - Creates a new shortcut, overwriting if necessary.
* `update` - Updates specified properties only on an existing shortcut.
* `replace` - Overwrites an existing shortcut, fails if the shortcut doesn't
exist.
* `options` Object
* `target` String - The target to launch from this shortcut.
* `cwd` String (optional) - The target to launch from this shortcut. Default
is empty.
* `args` String (optional) - The arguments to be applied to `target` when
launching from this shortcut. Default is empty.
* `description` String (optional) - The description of the shortcut. Default
is empty.
* `icon` String (optional) - The path to the icon, can be a DLL or EXE. `icon`
and `iconIndex` have to be set together. Default is empty, which uses the
target's icon.
* `iconIndex` Integer (optional) - The resource ID of icon when `icon` is a
DLL or EXE. Default is 0.
* `appUserModelId` String (optional) - The Application User Model ID. Default
is empty.
Creates or updates a shortcut link at `shortcutPath`. On success `true` is
returned, otherwise `false` is returned.
### `shell.readShortcutLink(shortcutPath)` _Windows_
Resolves the shortcut link at `shortcutPath`, an object is returned with the
fields described in the `options` of `shell.writeShortcutLink`.
An exception will be thrown when any error happens.

View file

@ -19,14 +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');
let win = null;
const {app, BrowserWindow} = require('electron')
let win = null
app.on('ready', () => {
win = new BrowserWindow({width: 800, height: 600});
win.loadURL('https://github.com');
});
win = new BrowserWindow({width: 800, height: 600})
win.loadURL('https://github.com')
})
```
The renderer process is no different than a normal web page, except for the
@ -37,8 +36,8 @@ extra ability to use node modules:
<html>
<body>
<script>
const {app} = require('electron').remote;
console.log(app.getVersion());
const {app} = require('electron').remote
console.log(app.getVersion())
</script>
</body>
</html>
@ -53,23 +52,43 @@ As of 0.37, you can use
built-in modules.
```javascript
const {app, BrowserWindow} = require('electron');
const {app, BrowserWindow} = require('electron')
let win
app.on('ready', () => {
win = new BrowserWindow()
win.loadURL('https://github.com')
})
```
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;
const electron = require('electron')
const {app, BrowserWindow} = electron
let win
app.on('ready', () => {
win = new BrowserWindow()
win.loadURL('https://github.com')
})
```
This is equivalent to the following code:
```javascript
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
let win
app.on('ready', () => {
win = new BrowserWindow()
win.loadURL('https://github.com')
})
```
[gui]: https://en.wikipedia.org/wiki/Graphical_user_interface

View file

@ -3,8 +3,8 @@
> Get system preferences.
```javascript
const {systemPreferences} = require('electron');
console.log(systemPreferences.isDarkMode());
const {systemPreferences} = require('electron')
console.log(systemPreferences.isDarkMode())
```
## Methods
@ -79,23 +79,24 @@ 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};
const {BrowserWindow, systemPreferences} = require('electron')
let browserOptions = {width: 1000, height: 800}
// Make the window transparent only if the platform supports it.
if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) {
browserOptions.transparent = true;
browserOptions.frame = false;
browserOptions.transparent = true
browserOptions.frame = false
}
// Create the window.
let win = new BrowserWindow(browserOptions);
let win = new BrowserWindow(browserOptions)
// Navigate.
if (browserOptions.transparent) {
win.loadURL('file://' + __dirname + '/index.html');
win.loadURL(`file://${__dirname}/index.html`)
} else {
// No transparency, so we load a fallback that uses basic styles.
win.loadURL('file://' + __dirname + '/fallback.html');
win.loadURL(`file://${__dirname}/fallback.html`)
}
```

View file

@ -13,7 +13,7 @@ app.on('ready', () => {
{label: 'Item2', type: 'radio'},
{label: 'Item3', type: 'radio', checked: true},
{label: 'Item4', type: 'radio'}
]);
])
tray.setToolTip('This is my application.')
tray.setContextMenu(contextMenu)
})
@ -31,8 +31,18 @@ __Platform limitations:__
you have to call `setContextMenu` again. For example:
```javascript
contextMenu.items[2].checked = false;
appIcon.setContextMenu(contextMenu);
const {Menu, Tray} = require('electron')
const appIcon = new Tray('/path/to/my/icon')
const contextMenu = Menu.buildFromTemplate([
{label: 'Item1', type: 'radio'},
{label: 'Item2', type: 'radio'}
])
// Make a change to the context menu
contextMenu.items[2].checked = false
// Call this again for Linux because we modified the context menu
appIcon.setContextMenu(contextMenu)
```
* On Windows it is recommended to use `ICO` icons to get best visual effects.
@ -173,12 +183,36 @@ Sets the hover text for this tray icon.
Sets the title displayed aside of the tray icon in the status bar.
#### `tray.setHighlightMode(highlight)` _macOS_
#### `tray.setHighlightMode(mode)` _macOS_
* `highlight` Boolean
* `mode` String highlight mode with one of the following values:
* `'selection'` - Highlight the tray icon when it is clicked and also when
its context menu is open. This is the default.
* `'always'` - Always highlight the tray icon.
* `'never'` - Never highlight the tray icon.
Sets whether the tray icon's background becomes highlighted (in blue)
when the tray icon is clicked. Defaults to true.
Sets when the tray's icon background becomes highlighted (in blue).
**Note:** You can use `highlightMode` with a [`BrowserWindow`](browser-window.md)
by toggling between `'never'` and `'always'` modes when the window visibility
changes.
```js
const {BrowserWindow, Tray} = require('electron')
const win = new BrowserWindow({width: 800, height: 600})
const tray = new Tray('/path/to/my/icon')
tray.on('click', () => {
win.isVisible() ? win.hide() : win.show()
})
win.on('show', () => {
tray.setHighlightMode('always')
})
win.on('hide', () => {
tray.setHighlightMode('never')
})
```
#### `tray.displayBalloon(options)` _Windows_

View file

@ -9,12 +9,13 @@ 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');
let win = new BrowserWindow({width: 800, height: 1500})
win.loadURL('http://github.com')
let contents = win.webContents;
let contents = win.webContents
console.log(contents)
```
## Methods
@ -22,7 +23,8 @@ let contents = win.webContents;
These methods can be accessed from the `webContents` module:
```js
const {webContents} = require('electron');
const {webContents} = require('electron')
console.log(webContents)
```
### `webContents.getAllWebContents()`
@ -437,6 +439,7 @@ first available device will be selected. `callback` should be called with
cancel the request.
```javascript
const {app, webContents} = require('electron')
app.commandLine.appendSwitch('enable-web-bluetooth')
app.on('ready', () => {
@ -508,8 +511,9 @@ 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 {webContents} = require('electron')
const options = {extraHeaders: 'pragma: no-cache\n'}
webContents.loadURL('https://github.com', options)
```
#### `contents.downloadURL(url)`
@ -524,10 +528,12 @@ Initiates a download of the resource at `url` without navigating. The
Returns URL of the current web page.
```javascript
let win = new BrowserWindow({width: 800, height: 600});
win.loadURL('http://github.com');
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('http://github.com')
let currentURL = win.webContents.getURL();
let currentURL = win.webContents.getURL()
console.log(currentURL)
```
#### `contents.getTitle()`
@ -661,6 +667,13 @@ Executes the editing command `cut` in web page.
Executes the editing command `copy` in web page.
### `contents.copyImageAt(x, y)`
* `x` Integer
* `y` Integer
Copy the image at the given position to the clipboard.
#### `contents.paste()`
Executes the editing command `paste` in web page.
@ -731,12 +744,13 @@ the request can be obtained by subscribing to
Stops any `findInPage` request for the `webContents` with the provided `action`.
```javascript
const {webContents} = require('electron')
webContents.on('found-in-page', (event, result) => {
if (result.finalUpdate)
webContents.stopFindInPage('clearSelection');
});
if (result.finalUpdate) webContents.stopFindInPage('clearSelection')
})
const requestId = webContents.findInPage('api');
const requestId = webContents.findInPage('api')
console.log(requestId)
```
#### `contents.capturePage([rect, ]callback)`
@ -802,7 +816,7 @@ The `callback` will be called with `callback(error, data)` on completion. The
By default, an empty `options` will be regarded as:
```javascript
```
{
marginsType: 0,
printBackground: false,
@ -814,23 +828,22 @@ By default, an empty `options` will be regarded as:
An example of `webContents.printToPDF`:
```javascript
const {BrowserWindow} = require('electron');
const fs = require('fs');
const {BrowserWindow} = require('electron')
const fs = require('fs')
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')
win.webContents.on('did-finish-load', () => {
// Use default printing options
win.webContents.printToPDF({}, (error, data) => {
if (error) throw error;
if (error) throw error
fs.writeFile('/tmp/print.pdf', data, (error) => {
if (error)
throw error;
console.log('Write PDF successfully.');
});
});
});
if (error) throw error
console.log('Write PDF successfully.')
})
})
})
```
#### `contents.addWorkSpace(path)`
@ -841,9 +854,11 @@ Adds the specified path to DevTools workspace. Must be used after DevTools
creation:
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.webContents.on('devtools-opened', () => {
win.webContents.addWorkSpace(__dirname);
});
win.webContents.addWorkSpace(__dirname)
})
```
#### `contents.removeWorkSpace(path)`
@ -904,15 +919,16 @@ An example of sending messages from the main process to the renderer process:
```javascript
// In the main process.
let win = null;
const {app, BrowserWindow} = require('electron')
let win = null
app.on('ready', () => {
win = new BrowserWindow({width: 800, height: 600});
win.loadURL(`file://${__dirname}/index.html`);
win = new BrowserWindow({width: 800, height: 600})
win.loadURL(`file://${__dirname}/index.html`)
win.webContents.on('did-finish-load', () => {
win.webContents.send('ping', 'whoooooooh!');
});
});
win.webContents.send('ping', 'whoooooooh!')
})
})
```
```html
@ -921,8 +937,8 @@ app.on('ready', () => {
<body>
<script>
require('electron').ipcRenderer.on('ping', (event, message) => {
console.log(message); // Prints "whoooooooh!"
});
console.log(message) // Prints 'whoooooooh!'
})
</script>
</body>
</html>
@ -943,7 +959,7 @@ app.on('ready', () => {
(screenPosition == mobile) (default: `{x: 0, y: 0}`)
* `x` Integer - Set the x axis offset from top left corner
* `y` Integer - Set the y axis offset from top left corner
* `deviceScaleFactor` Integer - Set the device scale factor (if zero defaults to
* `deviceScaleFactor` Float - Set the device scale factor (if zero defaults to
original device scale factor) (default: `0`)
* `viewSize` Object - Set the emulated view size (empty means no override)
* `width` Integer - Set the emulated view width
@ -1051,14 +1067,16 @@ the cursor when dragging.
Returns true if the process of saving page has been initiated successfully.
```javascript
win.loadURL('https://github.com');
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
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');
});
});
if (!error) console.log('Save page successfully')
})
})
```
#### `contents.showDefinitionForSelection()` _macOS_
@ -1120,24 +1138,28 @@ Get the debugger instance for this webContents.
Debugger API serves as an alternate transport for [remote debugging protocol][rdp].
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
try {
win.webContents.debugger.attach('1.1');
} catch(err) {
console.log('Debugger attach failed : ', err);
};
win.webContents.debugger.attach('1.1')
} catch (err) {
console.log('Debugger attach failed : ', err)
}
win.webContents.debugger.on('detach', (event, reason) => {
console.log('Debugger detached due to : ', reason);
});
console.log('Debugger detached due to : ', reason)
})
win.webContents.debugger.on('message', (event, method, params) => {
if (method === 'Network.requestWillBeSent') {
if (params.request.url === 'https://www.github.com')
win.webContents.debugger.detach();
if (params.request.url === 'https://www.github.com') {
win.webContents.debugger.detach()
}
}
});
})
win.webContents.debugger.sendCommand('Network.enable');
win.webContents.debugger.sendCommand('Network.enable')
```
### Instance Methods

View file

@ -5,9 +5,9 @@
An example of zooming current page to 200%.
```javascript
const {webFrame} = require('electron');
const {webFrame} = require('electron')
webFrame.setZoomFactor(2);
webFrame.setZoomFactor(2)
```
## Methods
@ -58,11 +58,12 @@ whether the word passed is correctly spelled.
An example of using [node-spellchecker][spellchecker] as provider:
```javascript
const {webFrame} = require('electron')
webFrame.setSpellCheckProvider('en-US', true, {
spellCheck(text) {
return !(require('spellchecker').isMisspelled(text));
spellCheck (text) {
return !(require('spellchecker').isMisspelled(text))
}
});
})
```
### `webFrame.registerURLSchemeAsSecure(scheme)`
@ -112,12 +113,13 @@ Returns an object describing usage information of Blink's internal memory
caches.
```javascript
const {webFrame} = require('electron')
console.log(webFrame.getResourceUsage())
```
This will generate:
```javascript
```
{
images: {
count: 22,
@ -130,8 +132,8 @@ This will generate:
cssStyleSheets: { /* same with "images" */ },
xslStyleSheets: { /* same with "images" */ },
fonts: { /* same with "images" */ },
other: { /* same with "images" */ },
}
other: { /* same with "images" */ }
})
```
### `webFrame.clearCache()`

View file

@ -12,7 +12,7 @@ app. It doesn't have the same permissions as your web page and all interactions
between your app and embedded content will be asynchronous. This keeps your app
safe from the embedded content.
For security purpose, `webview` can only be used in `BrowserWindow`s that have
For security purposes, `webview` can only be used in `BrowserWindow`s that have
`nodeIntegration` enabled.
## Example
@ -35,20 +35,20 @@ and displays a "loading..." message during the load time:
```html
<script>
onload = () => {
const webview = document.getElementById('foo');
const indicator = document.querySelector('.indicator');
const webview = document.getElementById('foo')
const indicator = document.querySelector('.indicator')
const loadstart = () => {
indicator.innerText = 'loading...';
};
indicator.innerText = 'loading...'
}
const loadstop = () => {
indicator.innerText = '';
};
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>
```
@ -223,9 +223,10 @@ The `webview` tag has the following methods:
**Example**
```javascript
const webview = document.getElementById('foo')
webview.addEventListener('dom-ready', () => {
webview.openDevTools();
});
webview.openDevTools()
})
```
### `<webview>.loadURL(url[, options])`
@ -618,9 +619,10 @@ The following example code forwards all log messages to the embedder's console
without regard for log level or other properties.
```javascript
const webview = document.getElementById('foo')
webview.addEventListener('console-message', (e) => {
console.log('Guest page logged a message:', e.message);
});
console.log('Guest page logged a message:', e.message)
})
```
### Event: 'found-in-page'
@ -638,12 +640,13 @@ Fired when a result is available for
[`webview.findInPage`](web-view-tag.md#webviewtagfindinpage) request.
```javascript
const webview = document.getElementById('foo')
webview.addEventListener('found-in-page', (e) => {
if (e.result.finalUpdate)
webview.stopFindInPage('keepSelection');
});
if (e.result.finalUpdate) webview.stopFindInPage('keepSelection')
})
const requestId = webview.findInPage('test');
const requestId = webview.findInPage('test')
console.log(requestId)
```
### Event: 'new-window'
@ -662,14 +665,15 @@ 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')
const webview = document.getElementById('foo')
webview.addEventListener('new-window', (e) => {
const protocol = require('url').parse(e.url).protocol;
const protocol = require('url').parse(e.url).protocol
if (protocol === 'http:' || protocol === 'https:') {
shell.openExternal(e.url);
shell.openExternal(e.url)
}
});
})
```
### Event: 'will-navigate'
@ -722,9 +726,10 @@ The following example code navigates the `webview` to `about:blank` when the
guest attempts to close itself.
```javascript
const webview = document.getElementById('foo')
webview.addEventListener('close', () => {
webview.src = 'about:blank';
});
webview.src = 'about:blank'
})
```
### Event: 'ipc-message'
@ -741,19 +746,20 @@ between guest page and embedder page:
```javascript
// In embedder page.
const webview = document.getElementById('foo')
webview.addEventListener('ipc-message', (event) => {
console.log(event.channel);
console.log(event.channel)
// Prints "pong"
});
webview.send('ping');
})
webview.send('ping')
```
```javascript
// In guest page.
const {ipcRenderer} = require('electron');
const {ipcRenderer} = require('electron')
ipcRenderer.on('ping', () => {
ipcRenderer.sendToHost('pong');
});
ipcRenderer.sendToHost('pong')
})
```
### Event: 'crashed'