chore: extend linting of code blocks in the docs (#40245)

* chore: extend linting of code blocks in the docs

* chore: combine lint:markdownlint and lint:markdown scripts
This commit is contained in:
David Sanders 2023-11-20 23:50:08 -08:00 committed by GitHub
parent d6bb9b40b0
commit 3d2a754531
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
71 changed files with 510 additions and 286 deletions

View file

@ -15,7 +15,7 @@ Shortcuts are registered with the [`globalShortcut`](global-shortcut.md) module
using the [`register`](global-shortcut.md#globalshortcutregisteraccelerator-callback)
method, i.e.
```javascript
```js
const { app, globalShortcut } = require('electron')
app.whenReady().then(() => {

View file

@ -16,7 +16,7 @@ module is emitted.
### Example
```javascript
```js
// In the main process.
const { app, BrowserView, BrowserWindow } = require('electron')

View file

@ -7,7 +7,7 @@ Process: [Main](../glossary.md#main-process)
This module cannot be used until the `ready` event of the `app`
module is emitted.
```javascript
```js
// In the main process.
const { BrowserWindow } = require('electron')
@ -38,7 +38,7 @@ While loading the page, the `ready-to-show` event will be emitted when the rende
process has rendered the page for the first time if the window has not been shown yet. Showing
the window after this event will have no visual flash:
```javascript
```js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ show: false })
win.once('ready-to-show', () => {
@ -59,7 +59,7 @@ For a complex app, the `ready-to-show` event could be emitted too late, making
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
```js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ backgroundColor: '#2e2c29' })
@ -85,7 +85,7 @@ For more information about these color types see valid options in [win.setBackgr
By using `parent` option, you can create child windows:
```javascript
```js
const { BrowserWindow } = require('electron')
const top = new BrowserWindow()
@ -101,7 +101,7 @@ The `child` window will always show on top of the `top` window.
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
```js
const { BrowserWindow } = require('electron')
const top = new BrowserWindow()
@ -188,7 +188,7 @@ window should be closed, which will also be called when the window is
reloaded. In Electron, returning any value other than `undefined` would cancel the
close. For example:
```javascript
```js
window.onbeforeunload = (e) => {
console.log('I do not want to be closed')
@ -351,7 +351,7 @@ Commands are lowercased, underscores are replaced with hyphens, and the
`APPCOMMAND_` prefix is stripped off.
e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`.
```javascript
```js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.on('app-command', (e, cmd) => {
@ -456,7 +456,7 @@ Returns `BrowserWindow | null` - The window with the given `id`.
Objects created with `new BrowserWindow` have the following properties:
```javascript
```js
const { BrowserWindow } = require('electron')
// In this example `win` is our instance
const win = new BrowserWindow({ width: 800, height: 600 })
@ -780,7 +780,7 @@ Closes the currently open [Quick Look][quick-look] panel.
Resizes and moves the window to the supplied bounds. Any properties that are not supplied will default to their current values.
```javascript
```js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
@ -1035,7 +1035,7 @@ 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
```js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
@ -1178,7 +1178,7 @@ To ensure that file URLs are properly formatted, it is recommended to use
Node's [`url.format`](https://nodejs.org/api/url.html#url_url_format_urlobject)
method:
```javascript
```js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
@ -1194,7 +1194,7 @@ win.loadURL(url)
You can load a URL using a `POST` request with URL-encoded data by doing
the following:
```javascript
```js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()

View file

@ -65,7 +65,7 @@ strictly follow the Node.js model as described in the
For instance, we could have created the same request to 'github.com' as follows:
```javascript
```js
const request = net.request({
method: 'GET',
protocol: 'https:',
@ -104,7 +104,7 @@ The `callback` function is expected to be called back with user credentials:
* `username` string
* `password` string
```javascript @ts-type={request:Electron.ClientRequest}
```js @ts-type={request:Electron.ClientRequest}
request.on('login', (authInfo, callback) => {
callback('username', 'password')
})
@ -113,7 +113,7 @@ request.on('login', (authInfo, callback) => {
Providing empty credentials will cancel the request and report an authentication
error on the response object:
```javascript @ts-type={request:Electron.ClientRequest}
```js @ts-type={request:Electron.ClientRequest}
request.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`)
response.on('error', (error) => {

View file

@ -7,7 +7,7 @@ Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer
On Linux, there is also a `selection` clipboard. To manipulate it
you need to pass `selection` to each method:
```javascript
```js
const { clipboard } = require('electron')
clipboard.writeText('Example string', 'selection')

View file

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

View file

@ -7,7 +7,7 @@ _This class is not exported from the `'electron'` module. It is only available a
The following example shows how to check if the `--disable-gpu` flag is set.
```javascript
```js
const { app } = require('electron')
app.commandLine.hasSwitch('disable-gpu')
```

View file

@ -10,7 +10,7 @@ This module does not include a web interface. To view recorded traces, use
**Note:** You should not use this module until the `ready` event of the app
module is emitted.
```javascript
```js
const { app, contentTracing } = require('electron')
app.whenReady().then(() => {

View file

@ -6,7 +6,7 @@ Process: [Renderer](../glossary.md#renderer-process)
An example of exposing an API to a renderer from an isolated preload script is given below:
```javascript
```js
// Preload (Isolated World)
const { contextBridge, ipcRenderer } = require('electron')
@ -18,7 +18,7 @@ contextBridge.exposeInMainWorld(
)
```
```javascript @ts-nocheck
```js @ts-nocheck
// Renderer (Main World)
window.electron.doThing()
@ -64,7 +64,7 @@ the API become immutable and updates on either side of the bridge do not result
An example of a complex API is shown below:
```javascript
```js
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld(
@ -92,7 +92,7 @@ contextBridge.exposeInMainWorld(
An example of `exposeInIsolatedWorld` is shown below:
```javascript
```js
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInIsolatedWorld(
@ -104,7 +104,7 @@ contextBridge.exposeInIsolatedWorld(
)
```
```javascript @ts-nocheck
```js @ts-nocheck
// Renderer (In isolated world id1004)
window.electron.doThing()
@ -145,7 +145,7 @@ The table of supported types described above also applies to Node APIs that you
Please note that many Node APIs grant access to local system resources.
Be very cautious about which globals and APIs you expose to untrusted remote content.
```javascript
```js
const { contextBridge } = require('electron')
const crypto = require('node:crypto')
contextBridge.exposeInMainWorld('nodeCrypto', {

View file

@ -10,7 +10,7 @@ a `Session`.
For example:
```javascript
```js
const { session } = require('electron')
// Query all cookies.

View file

@ -7,7 +7,7 @@ Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer
The following is an example of setting up Electron to automatically submit
crash reports to a remote server:
```javascript
```js
const { crashReporter } = require('electron')
crashReporter.start({ submitURL: 'https://your-domain.com/url-to-submit' })

View file

@ -8,7 +8,7 @@ _This class is not exported from the `'electron'` module. It is only available a
Chrome Developer Tools has a [special binding][rdp] available at JavaScript
runtime that allows interacting with pages and instrumenting them.
```javascript
```js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()

View file

@ -8,7 +8,7 @@ Process: [Main](../glossary.md#main-process)
The following example shows how to capture video from a desktop window whose
title is `Electron`:
```javascript
```js
// In the main process.
const { BrowserWindow, desktopCapturer } = require('electron')
@ -24,7 +24,7 @@ desktopCapturer.getSources({ types: ['window', 'screen'] }).then(async sources =
})
```
```javascript @ts-nocheck
```js @ts-nocheck
// In the preload script.
const { ipcRenderer } = require('electron')
@ -68,7 +68,7 @@ To capture both audio and video from the entire desktop the constraints passed
to [`navigator.mediaDevices.getUserMedia`][] must include `chromeMediaSource: 'desktop'`,
for both `audio` and `video`, but should not include a `chromeMediaSourceId` constraint.
```javascript
```js
const constraints = {
audio: {
mandatory: {

View file

@ -6,7 +6,7 @@ Process: [Main](../glossary.md#main-process)
An example of showing a dialog to select multiple files:
```javascript
```js
const { dialog } = require('electron')
console.log(dialog.showOpenDialog({ properties: ['openFile', 'multiSelections'] }))
```
@ -52,7 +52,7 @@ The `browserWindow` argument allows the dialog to attach itself to a parent wind
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
```js
{
filters: [
{ name: 'Images', extensions: ['jpg', 'png', 'gif'] },
@ -119,7 +119,7 @@ The `browserWindow` argument allows the dialog to attach itself to a parent wind
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
```js
{
filters: [
{ name: 'Images', extensions: ['jpg', 'png', 'gif'] },

View file

@ -7,7 +7,7 @@ _This class is not exported from the `'electron'` module. It is only available a
The following example shows how to bounce your icon on the dock.
```javascript
```js
const { app } = require('electron')
app.dock.bounce()
```

View file

@ -9,7 +9,7 @@ _This class is not exported from the `'electron'` module. It is only available a
It is used in `will-download` event of `Session` class, and allows users to
control the download item.
```javascript
```js
// In the main process.
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()

View file

@ -59,7 +59,7 @@ geolocation webservice. To enable this feature, acquire a
and place the following code in your main process file, before opening any
browser windows that will make geolocation requests:
```javascript
```js
process.env.GOOGLE_API_KEY = 'YOUR_KEY_HERE'
```

View file

@ -12,7 +12,7 @@ shortcuts.
not have the keyboard focus. This module cannot be used before the `ready`
event of the app module is emitted.
```javascript
```js
const { app, globalShortcut } = require('electron')
app.whenReady().then(() => {

View file

@ -89,7 +89,7 @@ tuples. So, the even-numbered offsets are key values, and the odd-numbered
offsets are the associated values. Header names are not lowercased, and
duplicates are not merged.
```javascript @ts-type={response:Electron.IncomingMessage}
```js @ts-type={response:Electron.IncomingMessage}
// Prints something like:
//
// [ 'user-agent',

View file

@ -120,7 +120,7 @@ The main process should listen for `channel` with
For example:
```javascript @ts-type={someArgument:unknown} @ts-type={doSomeWork:(arg:unknown)=>Promise<unknown>}
```js @ts-type={someArgument:unknown} @ts-type={doSomeWork:(arg:unknown)=>Promise<unknown>}
// Renderer process
ipcRenderer.invoke('some-name', someArgument).then((result) => {
// ...

View file

@ -151,7 +151,7 @@ can have a submenu.
An example of creating the application menu with the simple template API:
```javascript @ts-expect-error=[107]
```js @ts-expect-error=[107]
const { app, Menu } = require('electron')
const isMac = process.platform === 'darwin'
@ -353,7 +353,7 @@ By default, items will be inserted in the order they exist in the template unles
Template:
```javascript
```js
[
{ id: '1', label: 'one' },
{ id: '2', label: 'two' },
@ -373,7 +373,7 @@ Menu:
Template:
```javascript
```js
[
{ id: '1', label: 'one' },
{ type: 'separator' },
@ -397,7 +397,7 @@ Menu:
Template:
```javascript
```js
[
{ id: '1', label: 'one', after: ['3'] },
{ id: '2', label: 'two', before: ['1'] },

View file

@ -10,7 +10,7 @@ In Electron, for the APIs that take images, you can pass either file paths or
For example, when creating a tray or setting a window's icon, you can pass an
image file path as a `string`:
```javascript
```js
const { BrowserWindow, Tray } = require('electron')
const appIcon = new Tray('/Users/somebody/images/icon.png')
@ -20,7 +20,7 @@ console.log(appIcon, win)
Or read the image from the clipboard, which returns a `NativeImage`:
```javascript
```js
const { clipboard, Tray } = require('electron')
const image = clipboard.readImage()
const appIcon = new Tray(image)
@ -71,7 +71,7 @@ images/
└── icon@3x.png
```
```javascript
```js
const { Tray } = require('electron')
const appIcon = new Tray('/Users/somebody/images/icon.png')
console.log(appIcon)
@ -138,7 +138,7 @@ Creates a new `NativeImage` instance from a file located at `path`. This method
returns an empty image if the `path` does not exist, cannot be read, or is not
a valid image.
```javascript
```js
const nativeImage = require('electron').nativeImage
const image = nativeImage.createFromPath('/Users/somebody/images/icon.png')

View file

@ -4,7 +4,7 @@
Process: [Main](../glossary.md#main-process)
```javascript
```js
const { app, netLog } = require('electron')
app.whenReady().then(async () => {

View file

@ -26,7 +26,7 @@ Node.js.
Example usage:
```javascript
```js
const { app } = require('electron')
app.whenReady().then(() => {
const { net } = require('electron')

View file

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

View file

@ -7,7 +7,7 @@ Process: [Main](../glossary.md#main-process)
An example of implementing a protocol that has the same effect as the
`file://` protocol:
```javascript
```js
const { app, protocol, net } = require('electron')
app.whenReady().then(() => {
@ -31,7 +31,7 @@ a different session and your custom protocol will not work if you just use
To have your custom protocol work in combination with a custom session, you need
to register it to that session explicitly.
```javascript
```js
const { app, BrowserWindow, net, protocol, session } = require('electron')
const path = require('node:path')
const url = require('url')
@ -67,7 +67,7 @@ video/audio. Specify a privilege with the value of `true` to enable the capabili
An example of registering a privileged scheme, that bypasses Content Security
Policy:
```javascript
```js
const { protocol } = require('electron')
protocol.registerSchemesAsPrivileged([
{ scheme: 'foo', privileges: { bypassCSP: true } }
@ -222,7 +222,7 @@ property.
Example:
```javascript
```js
protocol.registerBufferProtocol('atom', (request, callback) => {
callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') })
})
@ -277,7 +277,7 @@ has the `data` property.
Example:
```javascript
```js
const { protocol } = require('electron')
const { PassThrough } = require('stream')
@ -302,7 +302,7 @@ protocol.registerStreamProtocol('atom', (request, callback) => {
It is possible to pass any object that implements the readable stream API (emits
`data`/`end`/`error` events). For example, here's how a file could be returned:
```javascript
```js
protocol.registerStreamProtocol('atom', (request, callback) => {
callback(fs.createReadStream('index.html'))
})

View file

@ -6,7 +6,7 @@ Process: [Main](../glossary.md#main-process)
For example, when registering for push notifications via Apple push notification services (APNS):
```javascript
```js
const { pushNotifications, Notification } = require('electron')
pushNotifications.registerForAPNSNotifications().then((token) => {

View file

@ -14,20 +14,29 @@ property, so writing `let { screen } = require('electron')` will not work.
An example of creating a window that fills the whole screen:
```javascript fiddle='docs/fiddles/screen/fit-screen'
const { app, BrowserWindow, screen } = require('electron')
```fiddle docs/fiddles/screen/fit-screen
// Retrieve information about screen size, displays, cursor position, etc.
//
// For more info, see:
// https://www.electronjs.org/docs/latest/api/screen
const { app, BrowserWindow, screen } = require('electron/main')
let mainWindow = null
let win
app.whenReady().then(() => {
const { width, height } = screen.getPrimaryDisplay().workAreaSize
win = new BrowserWindow({ width, height })
win.loadURL('https://github.com')
// Create a window that fills the screen's available work area.
const primaryDisplay = screen.getPrimaryDisplay()
const { width, height } = primaryDisplay.workAreaSize
mainWindow = new BrowserWindow({ width, height })
mainWindow.loadURL('https://electronjs.org')
})
```
Another example of creating a window in the external display:
```javascript
```js
const { app, BrowserWindow, screen } = require('electron')
let win

View file

@ -10,7 +10,7 @@ a `Session`.
For example:
```javascript
```js
const { session } = require('electron')
// Get all service workers.

View file

@ -9,7 +9,7 @@ The `session` module can be used to create new `Session` objects.
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
```js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
@ -75,7 +75,7 @@ _This class is not exported from the `'electron'` module. It is only available a
You can create a `Session` object in the `session` module:
```javascript
```js
const { session } = require('electron')
const ses = session.fromPartition('persist:name')
console.log(ses.getUserAgent())
@ -98,7 +98,7 @@ Emitted when Electron is about to download `item` in `webContents`.
Calling `event.preventDefault()` will cancel the download and `item` will not be
available from next tick of the process.
```javascript @ts-expect-error=[4]
```js @ts-expect-error=[4]
const { session } = require('electron')
session.defaultSession.on('will-download', (event, item, webContents) => {
event.preventDefault()
@ -214,7 +214,7 @@ cancel the request. Additionally, permissioning on `navigator.hid` can
be further managed by using [`ses.setPermissionCheckHandler(handler)`](#sessetpermissioncheckhandlerhandler)
and [`ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler).
```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)}
```js @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)}
const { app, BrowserWindow } = require('electron')
let win = null
@ -320,7 +320,7 @@ cancel the request. Additionally, permissioning on `navigator.serial` can
be managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler)
with the `serial` permission.
```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)}
```js @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)}
const { app, BrowserWindow } = require('electron')
let win = null
@ -463,7 +463,7 @@ cancel the request. Additionally, permissioning on `navigator.usb` can
be further managed by using [`ses.setPermissionCheckHandler(handler)`](#sessetpermissioncheckhandlerhandler)
and [`ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler).
```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} @ts-type={updateGrantedDevices:(devices:Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)=>void}
```js @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} @ts-type={updateGrantedDevices:(devices:Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)=>void}
const { app, BrowserWindow } = require('electron')
let win = null
@ -754,7 +754,7 @@ Sets download saving directory. By default, the download directory will be the
Emulates network with the given configuration for the `session`.
```javascript
```js
const win = new BrowserWindow()
// To emulate a GPRS connection with 50kbps throughput and 500 ms latency.
@ -868,7 +868,7 @@ calling `callback(-2)` rejects it.
Calling `setCertificateVerifyProc(null)` will revert back to default certificate
verify proc.
```javascript
```js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
@ -921,7 +921,7 @@ To clear the handler, call `setPermissionRequestHandler(null)`. Please note tha
you must also implement `setPermissionCheckHandler` to get complete permission handling.
Most web APIs do a permission check and then make a permission request if the check is denied.
```javascript
```js
const { session } = require('electron')
session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => {
if (webContents.getURL() === 'some-host' && permission === 'notifications') {
@ -967,7 +967,7 @@ you must also implement `setPermissionRequestHandler` to get complete permission
Most web APIs do a permission check and then make a permission request if the check is denied.
To clear the handler, call `setPermissionCheckHandler(null)`.
```javascript
```js
const { session } = require('electron')
const url = require('url')
session.fromPartition('some-partition').setPermissionCheckHandler((webContents, permission, requestingOrigin) => {
@ -1012,7 +1012,7 @@ via the `navigator.mediaDevices.getDisplayMedia` API. Use the
[desktopCapturer](desktop-capturer.md) API to choose which stream(s) to grant
access to.
```javascript
```js
const { session, desktopCapturer } = require('electron')
session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
@ -1026,7 +1026,7 @@ session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
Passing a [WebFrameMain](web-frame-main.md) object as a video or audio stream
will capture the video or audio stream from that frame.
```javascript
```js
const { session } = require('electron')
session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
@ -1055,7 +1055,7 @@ Additionally, the default behavior of Electron is to store granted device permis
If longer term storage is needed, a developer can store granted device
permissions (eg when handling the `select-hid-device` event) and then read from that storage with `setDevicePermissionHandler`.
```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)}
```js @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)}
const { app, BrowserWindow } = require('electron')
let win = null
@ -1137,7 +1137,7 @@ The return value for the handler is a string array of USB classes which should b
Returning an empty string array from the handler will allow all USB classes; returning the passed in array will maintain the default list of protected USB classes (this is also the default behavior if a handler is not defined).
To clear the handler, call `setUSBProtectedClassesHandler(null)`.
```javascript
```js
const { app, BrowserWindow } = require('electron')
let win = null
@ -1192,7 +1192,7 @@ that requires additional validation will be automatically cancelled.
macOS does not require a handler because macOS handles the pairing
automatically. To clear the handler, call `setBluetoothPairingHandler(null)`.
```javascript
```js
const { app, BrowserWindow, session } = require('electron')
const path = require('node:path')
@ -1238,7 +1238,7 @@ Clears the host resolver cache.
Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate
authentication.
```javascript
```js
const { session } = require('electron')
// consider any url ending with `example.com`, `foobar.com`, `baz`
// for integrated authentication.
@ -1543,7 +1543,7 @@ A [`WebRequest`](web-request.md) object for this session.
A [`Protocol`](protocol.md) object for this session.
```javascript
```js
const { app, session } = require('electron')
const path = require('node:path')
@ -1562,7 +1562,7 @@ app.whenReady().then(() => {
A [`NetLog`](net-log.md) object for this session.
```javascript
```js
const { app, session } = require('electron')
app.whenReady().then(async () => {

View file

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

View file

@ -14,7 +14,7 @@ The number represented by `status` means different things on different platforms
Below is an example of some of the additional options that may be set which
may be different on each platform.
```javascript
```js
{
name: 'Austin_4th_Floor_Printer___C02XK13BJHD4',
displayName: 'Austin 4th Floor Printer @ C02XK13BJHD4',

View file

@ -4,7 +4,7 @@
Process: [Main](../glossary.md#main-process)
```javascript
```js
const { systemPreferences } = require('electron')
console.log(systemPreferences.isAeroGlassEnabled())
```
@ -189,7 +189,7 @@ enabled, and `false` otherwise.
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
```js
const { BrowserWindow, systemPreferences } = require('electron')
const browserOptions = { width: 1000, height: 800 }
@ -348,7 +348,7 @@ Returns `boolean` - whether or not this device has the ability to use Touch ID.
Returns `Promise<void>` - resolves if the user has successfully authenticated with Touch ID.
```javascript
```js
const { systemPreferences } = require('electron')
systemPreferences.promptTouchID('To get consent for a Security-Gated Thing').then(success => {

View file

@ -79,7 +79,7 @@ immediately updates the escape item in the touch bar.
Below is an example of a simple slot machine touch bar game with a button
and some labels.
```javascript
```js
const { app, BrowserWindow, TouchBar } = require('electron')
const { TouchBarLabel, TouchBarButton, TouchBarSpacer } = TouchBar

View file

@ -8,7 +8,7 @@ Process: [Main](../glossary.md#main-process)
`Tray` is an [EventEmitter][event-emitter].
```javascript
```js
const { app, Menu, Tray } = require('electron')
let tray = null
@ -39,7 +39,7 @@ app.whenReady().then(() => {
* In order for changes made to individual `MenuItem`s to take effect,
you have to call `setContextMenu` again. For example:
```javascript
```js
const { app, Menu, Tray } = require('electron')
let appIcon = null

View file

@ -9,7 +9,7 @@ It is responsible for rendering and controlling a web page and is a property of
the [`BrowserWindow`](browser-window.md) object. An example of accessing the
`webContents` object:
```javascript
```js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 1500 })
@ -53,7 +53,7 @@ If you want to also observe navigations in `<iframe>`s, use [`will-frame-navigat
These methods can be accessed from the `webContents` module:
```javascript
```js
const { webContents } = require('electron')
console.log(webContents)
```
@ -439,7 +439,7 @@ Emitted when a `beforeunload` event handler is attempting to cancel a page unloa
Calling `event.preventDefault()` will ignore the `beforeunload` event handler
and allow the page to be unloaded.
```javascript
```js
const { BrowserWindow, dialog } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('will-prevent-unload', (event) => {
@ -527,7 +527,7 @@ and the menu shortcuts.
To only prevent the menu shortcuts, use
[`setIgnoreMenuShortcuts`](#contentssetignoremenushortcutsignore):
```javascript
```js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
@ -837,7 +837,7 @@ Due to the nature of bluetooth, scanning for devices when
`select-bluetooth-device` to fire multiple times until `callback` is called
with either a device id or an empty string to cancel the request.
```javascript title='main.js'
```js title='main.js'
const { app, BrowserWindow } = require('electron')
let win = null
@ -872,7 +872,7 @@ Returns:
Emitted when a new frame is generated. Only the dirty area is passed in the
buffer.
```javascript
```js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ webPreferences: { offscreen: true } })
@ -1004,7 +1004,7 @@ Loads the `url` in the window. The `url` must contain the protocol prefix,
e.g. the `http://` or `file://`. If the load should bypass http cache then
use the `pragma` header to achieve it.
```javascript
```js
const win = new BrowserWindow()
const options = { extraHeaders: 'pragma: no-cache\n' }
win.webContents.loadURL('https://github.com', options)
@ -1054,7 +1054,7 @@ Initiates a download of the resource at `url` without navigating. The
Returns `string` - The URL of the current web page.
```javascript
```js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com').then(() => {
@ -1503,7 +1503,7 @@ can be obtained by subscribing to [`found-in-page`](web-contents.md#event-found-
Stops any `findInPage` request for the `webContents` with the provided `action`.
```javascript
```js
const win = new BrowserWindow()
win.webContents.on('found-in-page', (event, result) => {
if (result.finalUpdate) win.webContents.stopFindInPage('clearSelection')
@ -1623,7 +1623,7 @@ The `landscape` will be ignored if `@page` CSS at-rule is used in the web page.
An example of `webContents.printToPDF`:
```javascript
```js
const { BrowserWindow } = require('electron')
const fs = require('node:fs')
const path = require('node:path')
@ -1655,7 +1655,7 @@ See [Page.printToPdf](https://chromedevtools.github.io/devtools-protocol/tot/Pag
Adds the specified path to DevTools workspace. Must be used after DevTools
creation:
```javascript
```js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.webContents.on('devtools-opened', () => {
@ -1978,7 +1978,7 @@ the cursor when dragging.
Returns `Promise<void>` - resolves if the page is saved.
```javascript
```js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()

View file

@ -8,7 +8,7 @@ The `webFrameMain` module can be used to lookup frames across existing
[`WebContents`](web-contents.md) instances. Navigation events are the common
use case.
```javascript
```js
const { BrowserWindow, webFrameMain } = require('electron')
const win = new BrowserWindow({ width: 800, height: 1500 })
@ -29,7 +29,7 @@ win.webContents.on(
You can also access frames of existing pages by using the `mainFrame` property
of [`WebContents`](web-contents.md).
```javascript
```js
const { BrowserWindow } = require('electron')
async function main () {

View file

@ -10,7 +10,7 @@ certain properties and methods (e.g. `webFrame.firstChild`).
An example of zooming current page to 200%.
```javascript
```js
const { webFrame } = require('electron')
webFrame.setZoomFactor(2)
@ -96,7 +96,7 @@ with an array of misspelt words when complete.
An example of using [node-spellchecker][spellchecker] as provider:
```javascript @ts-expect-error=[2,6]
```js @ts-expect-error=[2,6]
const { webFrame } = require('electron')
const spellChecker = require('spellchecker')
webFrame.setSpellCheckProvider('en-US', {
@ -205,14 +205,14 @@ Returns `Object`:
Returns an object describing usage information of Blink's internal memory
caches.
```javascript
```js
const { webFrame } = require('electron')
console.log(webFrame.getResourceUsage())
```
This will generate:
```javascript
```js
{
images: {
count: 22,

View file

@ -23,7 +23,7 @@ called with a `response` object when `listener` has done its work.
An example of adding `User-Agent` header for requests:
```javascript
```js
const { session } = require('electron')
// Modify the user agent for all requests to the following urls.

View file

@ -255,7 +255,7 @@ The `webview` tag has the following methods:
**Example**
```javascript @ts-expect-error=[3]
```js @ts-expect-error=[3]
const webview = document.querySelector('webview')
webview.addEventListener('dom-ready', () => {
webview.openDevTools()
@ -802,7 +802,7 @@ Fired when the guest window logs a console message.
The following example code forwards all log messages to the embedder's console
without regard for log level or other properties.
```javascript @ts-expect-error=[3]
```js @ts-expect-error=[3]
const webview = document.querySelector('webview')
webview.addEventListener('console-message', (e) => {
console.log('Guest page logged a message:', e.message)
@ -823,7 +823,7 @@ Returns:
Fired when a result is available for
[`webview.findInPage`](#webviewfindinpagetext-options) request.
```javascript @ts-expect-error=[3,6]
```js @ts-expect-error=[3,6]
const webview = document.querySelector('webview')
webview.addEventListener('found-in-page', (e) => {
webview.stopFindInPage('keepSelection')
@ -948,7 +948,7 @@ Fired when the guest page attempts to close itself.
The following example code navigates the `webview` to `about:blank` when the
guest attempts to close itself.
```javascript @ts-expect-error=[3]
```js @ts-expect-error=[3]
const webview = document.querySelector('webview')
webview.addEventListener('close', () => {
webview.src = 'about:blank'
@ -968,7 +968,7 @@ Fired when the guest page has sent an asynchronous message to embedder page.
With `sendToHost` method and `ipc-message` event you can communicate
between guest page and embedder page:
```javascript @ts-expect-error=[4,7]
```js @ts-expect-error=[4,7]
// In embedder page.
const webview = document.querySelector('webview')
webview.addEventListener('ipc-message', (event) => {
@ -978,7 +978,7 @@ webview.addEventListener('ipc-message', (event) => {
webview.send('ping')
```
```javascript
```js
// In guest page.
const { ipcRenderer } = require('electron')
ipcRenderer.on('ping', () => {

View file

@ -80,7 +80,7 @@ window will not close when the opener window closes. The default value is `false
### Native `Window` example
```javascript
```js
// main.js
const mainWindow = new BrowserWindow()
@ -104,7 +104,7 @@ mainWindow.webContents.setWindowOpenHandler(({ url }) => {
})
```
```javascript
```js
// renderer process (mainWindow)
const childWindow = window.open('', 'modal')
childWindow.document.write('<h1>Hello</h1>')