chore: update ref to docs (🤖)
This commit is contained in:
Родитель
97bf9c47f5
Коммит
78668bfa88
|
@ -505,6 +505,10 @@ and `workingDirectory` is its current working directory. Usually
|
|||
applications respond to this by making their primary window focused and
|
||||
non-minimized.
|
||||
|
||||
**Note:** `argv` will not be exactly the same list of arguments as those passed
|
||||
to the second instance. The order might change and additional arguments might be appended.
|
||||
If you need to maintain the exact same arguments, it's advised to use `additionalData` instead.
|
||||
|
||||
**Note:** If the second instance is started by a different user than the first, the `argv` array will not include the arguments.
|
||||
|
||||
This event is guaranteed to be emitted after the `ready` event of `app`
|
||||
|
|
|
@ -1043,6 +1043,8 @@ height areas you have within the overall content view.
|
|||
The aspect ratio is not respected when window is resized programmatically with
|
||||
APIs like `win.setSize`.
|
||||
|
||||
To reset an aspect ratio, pass 0 as the `aspectRatio` value: `win.setAspectRatio(0)`.
|
||||
|
||||
#### `win.setBackgroundColor(backgroundColor)`
|
||||
|
||||
* `backgroundColor` string - Color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type.
|
||||
|
@ -1455,13 +1457,16 @@ Returns `boolean` - Whether the window's document has been edited.
|
|||
|
||||
#### `win.blurWebView()`
|
||||
|
||||
#### `win.capturePage([rect])`
|
||||
#### `win.capturePage([rect, opts])`
|
||||
|
||||
* `rect` [Rectangle](latest/api/structures/rectangle.md) (optional) - The bounds to capture
|
||||
* `opts` Object (optional)
|
||||
* `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`.
|
||||
* `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`.
|
||||
|
||||
Returns `Promise<NativeImage>` - Resolves with a [NativeImage](latest/api/native-image.md)
|
||||
|
||||
Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. If the page is not visible, `rect` may be empty.
|
||||
Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. If the page is not visible, `rect` may be empty. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true.
|
||||
|
||||
#### `win.loadURL(url[, options])`
|
||||
|
||||
|
|
|
@ -246,7 +246,7 @@ app.whenReady().then(() => {
|
|||
const selectedDevice = details.deviceList.find((device) => {
|
||||
return device.vendorId === '9025' && device.productId === '67'
|
||||
})
|
||||
callback(selectedPort?.deviceId)
|
||||
callback(selectedDevice?.deviceId)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
@ -436,6 +436,118 @@ const portConnect = async () => {
|
|||
}
|
||||
```
|
||||
|
||||
#### Event: 'select-usb-device'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `details` Object
|
||||
* `deviceList` [USBDevice[]](latest/api/structures/usb-device.md)
|
||||
* `frame` [WebFrameMain](latest/api/web-frame-main.md)
|
||||
* `callback` Function
|
||||
* `deviceId` string (optional)
|
||||
|
||||
Emitted when a USB device needs to be selected when a call to
|
||||
`navigator.usb.requestDevice` is made. `callback` should be called with
|
||||
`deviceId` to be selected; passing no arguments to `callback` will
|
||||
cancel the request. Additionally, permissioning on `navigator.usb` can
|
||||
be further managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler)
|
||||
and [ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler).
|
||||
|
||||
```javascript
|
||||
const { app, BrowserWindow } = require('electron')
|
||||
|
||||
let win = null
|
||||
|
||||
app.whenReady().then(() => {
|
||||
win = new BrowserWindow()
|
||||
|
||||
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
|
||||
if (permission === 'usb') {
|
||||
// Add logic here to determine if permission should be given to allow USB selection
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
// Optionally, retrieve previously persisted devices from a persistent store (fetchGrantedDevices needs to be implemented by developer to fetch persisted permissions)
|
||||
const grantedDevices = fetchGrantedDevices()
|
||||
|
||||
win.webContents.session.setDevicePermissionHandler((details) => {
|
||||
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'usb') {
|
||||
if (details.device.vendorId === 123 && details.device.productId === 345) {
|
||||
// Always allow this type of device (this allows skipping the call to `navigator.usb.requestDevice` first)
|
||||
return true
|
||||
}
|
||||
|
||||
// Search through the list of devices that have previously been granted permission
|
||||
return grantedDevices.some((grantedDevice) => {
|
||||
return grantedDevice.vendorId === details.device.vendorId &&
|
||||
grantedDevice.productId === details.device.productId &&
|
||||
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
|
||||
})
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
win.webContents.session.on('select-usb-device', (event, details, callback) => {
|
||||
event.preventDefault()
|
||||
const selectedDevice = details.deviceList.find((device) => {
|
||||
return device.vendorId === '9025' && device.productId === '67'
|
||||
})
|
||||
if (selectedDevice) {
|
||||
// Optionally, add this to the persisted devices (updateGrantedDevices needs to be implemented by developer to persist permissions)
|
||||
grantedDevices.push(selectedDevice)
|
||||
updateGrantedDevices(grantedDevices)
|
||||
}
|
||||
callback(selectedDevice?.deviceId)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
#### Event: 'usb-device-added'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `details` Object
|
||||
* `device` [USBDevice](latest/api/structures/usb-device.md)
|
||||
* `frame` [WebFrameMain](latest/api/web-frame-main.md)
|
||||
|
||||
Emitted after `navigator.usb.requestDevice` has been called and
|
||||
`select-usb-device` has fired if a new device becomes available before
|
||||
the callback from `select-usb-device` is called. This event is intended for
|
||||
use when using a UI to ask users to pick a device so that the UI can be updated
|
||||
with the newly added device.
|
||||
|
||||
#### Event: 'usb-device-removed'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `details` Object
|
||||
* `device` [USBDevice](latest/api/structures/usb-device.md)
|
||||
* `frame` [WebFrameMain](latest/api/web-frame-main.md)
|
||||
|
||||
Emitted after `navigator.usb.requestDevice` has been called and
|
||||
`select-usb-device` has fired if a device has been removed before the callback
|
||||
from `select-usb-device` is called. This event is intended for use when using
|
||||
a UI to ask users to pick a device so that the UI can be updated to remove the
|
||||
specified device.
|
||||
|
||||
#### Event: 'usb-device-revoked'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `details` Object
|
||||
* `device` [USBDevice[]](latest/api/structures/usb-device.md)
|
||||
* `origin` string (optional) - The origin that the device has been revoked from.
|
||||
|
||||
Emitted after `USBDevice.forget()` has been called. This event can be used
|
||||
to help maintain persistent storage of permissions when
|
||||
`setDevicePermissionHandler` is used.
|
||||
|
||||
### Instance Methods
|
||||
|
||||
The following methods are available on instances of `Session`:
|
||||
|
@ -460,7 +572,7 @@ Clears the session’s HTTP cache.
|
|||
`shadercache`, `websql`, `serviceworkers`, `cachestorage`. If not
|
||||
specified, clear all storage types.
|
||||
* `quotas` string[] (optional) - The types of quotas to clear, can contain:
|
||||
`temporary`, `persistent`, `syncable`. If not specified, clear all quotas.
|
||||
`temporary`, `syncable`. If not specified, clear all quotas.
|
||||
|
||||
Returns `Promise<void>` - resolves when the storage data has been cleared.
|
||||
|
||||
|
@ -689,7 +801,7 @@ win.webContents.session.setCertificateVerifyProc((request, callback) => {
|
|||
* `pointerLock` - Request to directly interpret mouse movements as an input method. Click [here](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API) to know more. These requests always appear to originate from the main frame.
|
||||
* `fullscreen` - Request for the app to enter fullscreen mode.
|
||||
* `openExternal` - Request to open links in external applications.
|
||||
* `window-placement` - Request access to enumerate screens using the [`getScreenDetails`](https://developer.chrome.com/en/articles/multi-screen-window-placement/) API.
|
||||
* `window-management` - Request access to enumerate screens using the [`getScreenDetails`](https://developer.chrome.com/en/articles/multi-screen-window-placement/) API.
|
||||
* `unknown` - An unrecognized permission request
|
||||
* `callback` Function
|
||||
* `permissionGranted` boolean - Allow or deny the permission.
|
||||
|
@ -722,7 +834,7 @@ session.fromPartition('some-partition').setPermissionRequestHandler((webContents
|
|||
|
||||
* `handler` Function<boolean> | null
|
||||
* `webContents` ([WebContents](latest/api/web-contents.md) | null) - WebContents checking the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. All cross origin sub frames making permission checks will pass a `null` webContents to this handler, while certain other permission checks such as `notifications` checks will always pass `null`. You should use `embeddingOrigin` and `requestingOrigin` to determine what origin the owning frame and the requesting frame are on respectively.
|
||||
* `permission` string - Type of permission check. Valid values are `midiSysex`, `notifications`, `geolocation`, `media`,`mediaKeySystem`,`midi`, `pointerLock`, `fullscreen`, `openExternal`, `hid`, or `serial`.
|
||||
* `permission` string - Type of permission check. Valid values are `midiSysex`, `notifications`, `geolocation`, `media`,`mediaKeySystem`,`midi`, `pointerLock`, `fullscreen`, `openExternal`, `hid`, `serial`, or `usb`.
|
||||
* `requestingOrigin` string - The origin URL of the permission check
|
||||
* `details` Object - Some properties are only available on certain permission types.
|
||||
* `embeddingOrigin` string (optional) - The origin of the frame embedding the frame that made the permission check. Only set for cross-origin sub frames making permission checks.
|
||||
|
@ -808,7 +920,7 @@ Passing `null` instead of a function resets the handler to its default state.
|
|||
|
||||
* `handler` Function<boolean> | null
|
||||
* `details` Object
|
||||
* `deviceType` string - The type of device that permission is being requested on, can be `hid` or `serial`.
|
||||
* `deviceType` string - The type of device that permission is being requested on, can be `hid`, `serial`, or `usb`.
|
||||
* `origin` string - The origin URL of the device permission check.
|
||||
* `device` [HIDDevice](latest/api/structures/hid-device.md) | [SerialPort](latest/api/structures/serial-port.md)- the device that permission is being requested for.
|
||||
|
||||
|
@ -836,6 +948,8 @@ app.whenReady().then(() => {
|
|||
return true
|
||||
} else if (permission === 'serial') {
|
||||
// Add logic here to determine if permission should be given to allow serial port selection
|
||||
} else if (permission === 'usb') {
|
||||
// Add logic here to determine if permission should be given to allow USB device selection
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
|
|
@ -0,0 +1,24 @@
|
|||
---
|
||||
title: "USBDevice Object"
|
||||
description: ""
|
||||
slug: usb-device
|
||||
hide_title: false
|
||||
---
|
||||
|
||||
# USBDevice Object
|
||||
|
||||
* `deviceId` string - Unique identifier for the device.
|
||||
* `vendorId` Integer - The USB vendor ID.
|
||||
* `productId` Integer - The USB product ID.
|
||||
* `productName` string (optional) - Name of the device.
|
||||
* `serialNumber` string (optional) - The USB device serial number.
|
||||
* `manufacturerName` string (optional) - The manufacturer name of the device.
|
||||
* `usbVersionMajor` Integer - The USB protocol major version supported by the device
|
||||
* `usbVersionMinor` Integer - The USB protocol minor version supported by the device
|
||||
* `usbVersionSubminor` Integer - The USB protocol subminor version supported by the device
|
||||
* `deviceClass` Integer - The device class for the communication interface supported by the device
|
||||
* `deviceSubclass` Integer - The device subclass for the communication interface supported by the device
|
||||
* `deviceProtocol` Integer - The device protocol for the communication interface supported by the device
|
||||
* `deviceVersionMajor` Integer - The major version number of the device as defined by the device manufacturer.
|
||||
* `deviceVersionMinor` Integer - The minor version number of the device as defined by the device manufacturer.
|
||||
* `deviceVersionSubminor` Integer - The subminor version number of the device as defined by the device manufacturer.
|
|
@ -1348,39 +1348,24 @@ const requestId = webContents.findInPage('api')
|
|||
console.log(requestId)
|
||||
```
|
||||
|
||||
#### `contents.capturePage([rect])`
|
||||
#### `contents.capturePage([rect, opts])`
|
||||
|
||||
* `rect` [Rectangle](latest/api/structures/rectangle.md) (optional) - The area of the page to be captured.
|
||||
* `opts` Object (optional)
|
||||
* `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`.
|
||||
* `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`.
|
||||
|
||||
Returns `Promise<NativeImage>` - Resolves with a [NativeImage](latest/api/native-image.md)
|
||||
|
||||
Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page.
|
||||
The page is considered visible when its browser window is hidden and the capturer count is non-zero.
|
||||
If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true.
|
||||
|
||||
#### `contents.isBeingCaptured()`
|
||||
|
||||
Returns `boolean` - Whether this page is being captured. It returns true when the capturer count
|
||||
is large then 0.
|
||||
|
||||
#### `contents.incrementCapturerCount([size, stayHidden, stayAwake])`
|
||||
|
||||
* `size` [Size](latest/api/structures/size.md) (optional) - The preferred size for the capturer.
|
||||
* `stayHidden` boolean (optional) - Keep the page hidden instead of visible.
|
||||
* `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep.
|
||||
|
||||
Increase the capturer count by one. The page is considered visible when its browser window is
|
||||
hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true.
|
||||
|
||||
This also affects the Page Visibility API.
|
||||
|
||||
#### `contents.decrementCapturerCount([stayHidden, stayAwake])`
|
||||
|
||||
* `stayHidden` boolean (optional) - Keep the page in hidden state instead of visible.
|
||||
* `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep.
|
||||
|
||||
Decrease the capturer count by one. The page will be set to hidden or occluded state when its
|
||||
browser window is hidden or occluded and the capturer count reaches zero. If you want to
|
||||
decrease the hidden capturer count instead you should set `stayHidden` to true.
|
||||
|
||||
#### `contents.getPrinters()` _Deprecated_
|
||||
|
||||
Get the system printer list.
|
||||
|
|
|
@ -21,6 +21,12 @@ This document uses the following convention to categorize breaking changes:
|
|||
|
||||
## Planned Breaking API Changes (23.0)
|
||||
|
||||
### Removed: Windows 7 / 8 / 8.1 support
|
||||
|
||||
[Windows 7, Windows 8, and Windows 8.1 are no longer supported](https://www.electronjs.org/blog/windows-7-to-8-1-deprecation-notice). Electron follows the planned Chromium deprecation policy, which will [deprecate Windows 7 support beginning in Chromium 109](https://support.google.com/chrome/thread/185534985/sunsetting-support-for-windows-7-8-8-1-in-early-2023?hl=en).
|
||||
|
||||
Older versions of Electron will continue to run on these operating systems, but Windows 10 or later will be required to run Electron v23.0.0 and higher.
|
||||
|
||||
### Removed: BrowserWindow `scroll-touch-*` events
|
||||
|
||||
The deprecated `scroll-touch-begin`, `scroll-touch-end` and `scroll-touch-edge`
|
||||
|
@ -45,14 +51,98 @@ win.webContents.on('input-event', (_, event) => {
|
|||
})
|
||||
```
|
||||
|
||||
### Removed: `webContents.incrementCapturerCount(stayHidden, stayAwake)`
|
||||
|
||||
The `webContents.incrementCapturerCount(stayHidden, stayAwake)` function has been removed.
|
||||
It is now automatically handled by `webContents.capturePage` when a page capture completes.
|
||||
|
||||
```js
|
||||
const w = new BrowserWindow({ show: false })
|
||||
|
||||
// Removed in Electron 23
|
||||
w.webContents.incrementCapturerCount()
|
||||
w.capturePage().then(image => {
|
||||
console.log(image.toDataURL())
|
||||
w.webContents.decrementCapturerCount()
|
||||
})
|
||||
|
||||
// Replace with
|
||||
w.capturePage().then(image => {
|
||||
console.log(image.toDataURL())
|
||||
})
|
||||
```
|
||||
|
||||
### Removed: `webContents.decrementCapturerCount(stayHidden, stayAwake)`
|
||||
|
||||
The `webContents.decrementCapturerCount(stayHidden, stayAwake)` function has been removed.
|
||||
It is now automatically handled by `webContents.capturePage` when a page capture completes.
|
||||
|
||||
```js
|
||||
const w = new BrowserWindow({ show: false })
|
||||
|
||||
// Removed in Electron 23
|
||||
w.webContents.incrementCapturerCount()
|
||||
w.capturePage().then(image => {
|
||||
console.log(image.toDataURL())
|
||||
w.webContents.decrementCapturerCount()
|
||||
})
|
||||
|
||||
// Replace with
|
||||
w.capturePage().then(image => {
|
||||
console.log(image.toDataURL())
|
||||
})
|
||||
```
|
||||
|
||||
## Planned Breaking API Changes (22.0)
|
||||
|
||||
### Deprecated: `webContents.incrementCapturerCount(stayHidden, stayAwake)`
|
||||
|
||||
`webContents.incrementCapturerCount(stayHidden, stayAwake)` has been deprecated.
|
||||
It is now automatically handled by `webContents.capturePage` when a page capture completes.
|
||||
|
||||
```js
|
||||
const w = new BrowserWindow({ show: false })
|
||||
|
||||
// Removed in Electron 23
|
||||
w.webContents.incrementCapturerCount()
|
||||
w.capturePage().then(image => {
|
||||
console.log(image.toDataURL())
|
||||
w.webContents.decrementCapturerCount()
|
||||
})
|
||||
|
||||
// Replace with
|
||||
w.capturePage().then(image => {
|
||||
console.log(image.toDataURL())
|
||||
})
|
||||
```
|
||||
|
||||
### Deprecated: `webContents.decrementCapturerCount(stayHidden, stayAwake)`
|
||||
|
||||
`webContents.decrementCapturerCount(stayHidden, stayAwake)` has been deprecated.
|
||||
It is now automatically handled by `webContents.capturePage` when a page capture completes.
|
||||
|
||||
```js
|
||||
const w = new BrowserWindow({ show: false })
|
||||
|
||||
// Removed in Electron 23
|
||||
w.webContents.incrementCapturerCount()
|
||||
w.capturePage().then(image => {
|
||||
console.log(image.toDataURL())
|
||||
w.webContents.decrementCapturerCount()
|
||||
})
|
||||
|
||||
// Replace with
|
||||
w.capturePage().then(image => {
|
||||
console.log(image.toDataURL())
|
||||
})
|
||||
```
|
||||
|
||||
### Removed: WebContents `new-window` event
|
||||
|
||||
The `new-window` event of WebContents has been removed. It is replaced by [`webContents.setWindowOpenHandler()`](latest/api/web-contents.md#contentssetwindowopenhandlerhandler).
|
||||
|
||||
```js
|
||||
// Removed in Electron 21
|
||||
// Removed in Electron 22
|
||||
webContents.on('new-window', (event) => {
|
||||
event.preventDefault()
|
||||
})
|
||||
|
|
|
@ -153,7 +153,7 @@ $ ninja -C out/Release electron
|
|||
```
|
||||
|
||||
This will build all of what was previously 'libchromiumcontent' (i.e. the
|
||||
`content/` directory of `chromium` and its dependencies, incl. WebKit and V8),
|
||||
`content/` directory of `chromium` and its dependencies, incl. Blink and V8),
|
||||
so it will take a while.
|
||||
|
||||
The built executable will be under `./out/Testing`:
|
||||
|
|
|
@ -122,10 +122,6 @@ $ git config --system core.longpaths true
|
|||
|
||||
This can happen during build, when Debugging Tools for Windows has been installed with Windows Driver Kit. Uninstall Windows Driver Kit and install Debugging Tools with steps described above.
|
||||
|
||||
### ImportError: No module named win32file
|
||||
|
||||
Make sure you have installed `pywin32` with `pip install pywin32`.
|
||||
|
||||
### Build Scripts Hang Until Keypress
|
||||
|
||||
This bug is a "feature" of Windows' command prompt. It happens when clicking inside the prompt window with
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
|
||||
<title>WebUSB API</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>WebUSB API</h1>
|
||||
|
||||
<button id="clickme">Test WebUSB</button>
|
||||
|
||||
<h3>USB devices automatically granted access via <i>setDevicePermissionHandler</i></h3>
|
||||
<div id="granted-devices"></div>
|
||||
|
||||
<h3>USB devices automatically granted access via <i>select-usb-device</i></h3>
|
||||
<div id="granted-devices2"></div>
|
||||
|
||||
<script src="./renderer.js"></script>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,72 @@
|
|||
const {app, BrowserWindow} = require('electron')
|
||||
const e = require('express')
|
||||
const path = require('path')
|
||||
|
||||
function createWindow () {
|
||||
const mainWindow = new BrowserWindow({
|
||||
width: 800,
|
||||
height: 600
|
||||
})
|
||||
|
||||
let grantedDeviceThroughPermHandler
|
||||
|
||||
mainWindow.webContents.session.on('select-usb-device', (event, details, callback) => {
|
||||
//Add events to handle devices being added or removed before the callback on
|
||||
//`select-usb-device` is called.
|
||||
mainWindow.webContents.session.on('usb-device-added', (event, device) => {
|
||||
console.log('usb-device-added FIRED WITH', device)
|
||||
//Optionally update details.deviceList
|
||||
})
|
||||
|
||||
mainWindow.webContents.session.on('usb-device-removed', (event, device) => {
|
||||
console.log('usb-device-removed FIRED WITH', device)
|
||||
//Optionally update details.deviceList
|
||||
})
|
||||
|
||||
event.preventDefault()
|
||||
if (details.deviceList && details.deviceList.length > 0) {
|
||||
const deviceToReturn = details.deviceList.find((device) => {
|
||||
if (!grantedDeviceThroughPermHandler || (device.deviceId != grantedDeviceThroughPermHandler.deviceId)) {
|
||||
return true
|
||||
}
|
||||
})
|
||||
if (deviceToReturn) {
|
||||
callback(deviceToReturn.deviceId)
|
||||
} else {
|
||||
callback()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
mainWindow.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
|
||||
if (permission === 'usb' && details.securityOrigin === 'file:///') {
|
||||
return true
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
mainWindow.webContents.session.setDevicePermissionHandler((details) => {
|
||||
if (details.deviceType === 'usb' && details.origin === 'file://') {
|
||||
if (!grantedDeviceThroughPermHandler) {
|
||||
grantedDeviceThroughPermHandler = details.device
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
mainWindow.loadFile('index.html')
|
||||
}
|
||||
|
||||
app.whenReady().then(() => {
|
||||
createWindow()
|
||||
|
||||
app.on('activate', function () {
|
||||
if (BrowserWindow.getAllWindows().length === 0) createWindow()
|
||||
})
|
||||
})
|
||||
|
||||
app.on('window-all-closed', function () {
|
||||
if (process.platform !== 'darwin') app.quit()
|
||||
})
|
|
@ -0,0 +1,33 @@
|
|||
function getDeviceDetails(device) {
|
||||
return grantedDevice.productName || `Unknown device ${grantedDevice.deviceId}`
|
||||
}
|
||||
|
||||
async function testIt() {
|
||||
const noDevicesFoundMsg = 'No devices found'
|
||||
const grantedDevices = await navigator.usb.getDevices()
|
||||
let grantedDeviceList = ''
|
||||
if (grantedDevices.length > 0) {
|
||||
grantedDevices.forEach(device => {
|
||||
grantedDeviceList += `<hr>${getDeviceDetails(device)}</hr>`
|
||||
})
|
||||
} else {
|
||||
grantedDeviceList = noDevicesFoundMsg
|
||||
}
|
||||
document.getElementById('granted-devices').innerHTML = grantedDeviceList
|
||||
|
||||
grantedDeviceList = ''
|
||||
try {
|
||||
const grantedDevice = await navigator.usb.requestDevice({
|
||||
filters: []
|
||||
})
|
||||
grantedDeviceList += `<hr>${getDeviceDetails(device)}</hr>`
|
||||
|
||||
} catch (ex) {
|
||||
if (ex.name === 'NotFoundError') {
|
||||
grantedDeviceList = noDevicesFoundMsg
|
||||
}
|
||||
}
|
||||
document.getElementById('granted-devices2').innerHTML = grantedDeviceList
|
||||
}
|
||||
|
||||
document.getElementById('clickme').addEventListener('click',testIt)
|
|
@ -122,3 +122,41 @@ when the `Test Web Serial` button is clicked.
|
|||
```fiddle docs/latest/fiddles/features/web-serial
|
||||
|
||||
```
|
||||
|
||||
## WebUSB API
|
||||
|
||||
The [WebUSB API](https://web.dev/usb/) can be used to access USB devices.
|
||||
Electron provides several APIs for working with the WebUSB API:
|
||||
|
||||
* The [`select-usb-device` event on the Session](latest/api/session.md#event-select-usb-device)
|
||||
can be used to select a USB device when a call to
|
||||
`navigator.usb.requestDevice` is made. Additionally the [`usb-device-added`](latest/api/session.md#event-usb-device-added)
|
||||
and [`usb-device-removed`](latest/api/session.md#event-usb-device-removed) events
|
||||
on the Session can be used to handle devices being plugged in or unplugged
|
||||
when handling the `select-usb-device` event.
|
||||
**Note:** These two events only fire until the callback from `select-usb-device`
|
||||
is called. They are not intended to be used as a generic usb device listener.
|
||||
* The [`usb-device-revoked' event on the Session](latest/api/session.md#event-usb-device-revoked) can
|
||||
be used to respond when [device.forget()](https://developer.chrome.com/articles/usb/#revoke-access)
|
||||
is called on a USB device.
|
||||
* [`ses.setDevicePermissionHandler(handler)`](latest/api/session.md#sessetdevicepermissionhandlerhandler)
|
||||
can be used to provide default permissioning to devices without first calling
|
||||
for permission to devices via `navigator.usb.requestDevice`. Additionally,
|
||||
the default behavior of Electron is to store granted device permission through
|
||||
the lifetime of the corresponding WebContents. If longer term storage is
|
||||
needed, a developer can store granted device permissions (eg when handling
|
||||
the `select-usb-device` event) and then read from that storage with
|
||||
`setDevicePermissionHandler`.
|
||||
* [`ses.setPermissionCheckHandler(handler)`](latest/api/session.md#sessetpermissioncheckhandlerhandler)
|
||||
can be used to disable USB access for specific origins.
|
||||
|
||||
### Example
|
||||
|
||||
This example demonstrates an Electron application that automatically selects
|
||||
USB devices (if they are attached) through [`ses.setDevicePermissionHandler(handler)`](latest/api/session.md#sessetdevicepermissionhandlerhandler)
|
||||
and through [`select-usb-device` event on the Session](latest/api/session.md#event-select-usb-device)
|
||||
when the `Test WebUSB` button is clicked.
|
||||
|
||||
```fiddle docs/latest/fiddles/features/web-usb
|
||||
|
||||
```
|
||||
|
|
|
@ -187,19 +187,16 @@ app.whenReady().then(async () => {
|
|||
|
||||
// We can't use ipcMain.handle() here, because the reply needs to transfer a
|
||||
// MessagePort.
|
||||
ipcMain.on('request-worker-channel', (event) => {
|
||||
// For security reasons, let's make sure only the frames we expect can
|
||||
// access the worker.
|
||||
if (event.senderFrame === mainWindow.webContents.mainFrame) {
|
||||
// Create a new channel ...
|
||||
const { port1, port2 } = new MessageChannelMain()
|
||||
// ... send one end to the worker ...
|
||||
worker.webContents.postMessage('new-client', null, [port1])
|
||||
// ... and the other end to the main window.
|
||||
event.senderFrame.postMessage('provide-worker-channel', null, [port2])
|
||||
// Now the main window and the worker can communicate with each other
|
||||
// without going through the main process!
|
||||
}
|
||||
// Listen for message sent from the top-level frame
|
||||
mainWindow.webContents.mainFrame.on('request-worker-channel', (event) => {
|
||||
// Create a new channel ...
|
||||
const { port1, port2 } = new MessageChannelMain()
|
||||
// ... send one end to the worker ...
|
||||
worker.webContents.postMessage('new-client', null, [port1])
|
||||
// ... and the other end to the main window.
|
||||
event.senderFrame.postMessage('provide-worker-channel', null, [port2])
|
||||
// Now the main window and the worker can communicate with each other
|
||||
// without going through the main process!
|
||||
})
|
||||
})
|
||||
```
|
||||
|
|
|
@ -86,11 +86,6 @@ Start Menu. This can be overkill during development, so adding
|
|||
trick. Navigate to the file in Explorer, right-click and 'Pin to Start Menu'.
|
||||
You will then need to add the line `app.setAppUserModelId(process.execPath)` to
|
||||
your main process to see notifications.
|
||||
* On Windows 8.1 and Windows 8, a shortcut to your app with an [Application User
|
||||
Model ID][app-user-model-id] must be installed to the Start screen. Note,
|
||||
however, that it does not need to be pinned to the Start screen.
|
||||
* On Windows 7, notifications work via a custom implementation which visually
|
||||
resembles the native one on newer systems.
|
||||
|
||||
Electron attempts to automate the work around the Application User Model ID. When
|
||||
Electron is used together with the installation and update framework Squirrel,
|
||||
|
@ -99,12 +94,6 @@ Electron will detect that Squirrel was used and will automatically call
|
|||
`app.setAppUserModelId()` with the correct value. During development, you may have
|
||||
to call [`app.setAppUserModelId()`][set-app-user-model-id] yourself.
|
||||
|
||||
Furthermore, in Windows 8, the maximum length for the notification body is 250
|
||||
characters, with the Windows team recommending that notifications should be kept
|
||||
to 200 characters. That said, that limitation has been removed in Windows 10, with
|
||||
the Windows team asking developers to be reasonable. Attempting to send gigantic
|
||||
amounts of text to the API (thousands of characters) might result in instability.
|
||||
|
||||
#### Advanced Notifications
|
||||
|
||||
Later versions of Windows allow for advanced notifications, with custom templates,
|
||||
|
|
|
@ -202,7 +202,7 @@ Then, set up your `handle` listener in the main process. We do this _before_
|
|||
loading the HTML file so that the handler is guaranteed to be ready before
|
||||
you send out the `invoke` call from the renderer.
|
||||
|
||||
```js {1,11} title="main.js"
|
||||
```js {1,12} title="main.js"
|
||||
const { app, BrowserWindow, ipcMain } = require('electron')
|
||||
const path = require('path')
|
||||
|
||||
|
|
|
@ -418,6 +418,7 @@ module.exports = {
|
|||
'latest/api/structures/payment-discount',
|
||||
'latest/api/structures/product-discount',
|
||||
'latest/api/structures/product-subscription-period',
|
||||
'latest/api/structures/usb-device',
|
||||
],
|
||||
},
|
||||
{
|
||||
|
|
Загрузка…
Ссылка в новой задаче