├── .gitignore ├── .npmignore ├── test ├── fixtures │ ├── electron │ │ └── docs │ │ │ └── api │ │ │ ├── structures │ │ │ ├── crash-report.md │ │ │ ├── file-filter.md │ │ │ ├── bluetooth-device.md │ │ │ ├── memory-usage-details.md │ │ │ ├── upload-blob.md │ │ │ ├── upload-raw-data.md │ │ │ ├── mime-typed-buffer.md │ │ │ ├── rectangle.md │ │ │ ├── remove-client-certificate.md │ │ │ ├── upload-data.md │ │ │ ├── certificate-principal.md │ │ │ ├── upload-file.md │ │ │ ├── upload-file-system.md │ │ │ ├── certificate.md │ │ │ ├── event.md │ │ │ ├── remove-password.md │ │ │ ├── cookie.md │ │ │ ├── display.md │ │ │ ├── shortcut-details.md │ │ │ ├── task.md │ │ │ ├── desktop-capturer-source.md │ │ │ ├── thumbar-button.md │ │ │ ├── jump-list-category.md │ │ │ └── jump-list-item.md │ │ │ ├── touch-bar-group.md │ │ │ ├── power-monitor.md │ │ │ ├── file-object.md │ │ │ ├── browser-window-proxy.md │ │ │ ├── window-open.md │ │ │ ├── power-save-blocker.md │ │ │ ├── accelerator.md │ │ │ ├── incoming-message.md │ │ │ ├── global-shortcut.md │ │ │ ├── debugger.md │ │ │ ├── shell.md │ │ │ ├── desktop-capturer.md │ │ │ ├── ipc-renderer.md │ │ │ ├── net.md │ │ │ ├── synopsis.md │ │ │ ├── environment-variables.md │ │ │ ├── ipc-main.md │ │ │ ├── screen.md │ │ │ ├── touch-bar.md │ │ │ ├── process.md │ │ │ ├── locales.md │ │ │ ├── cookies.md │ │ │ ├── menu-item.md │ │ │ ├── clipboard.md │ │ │ ├── download-item.md │ │ │ ├── frameless-window.md │ │ │ ├── content-tracing.md │ │ │ ├── auto-updater.md │ │ │ ├── web-frame.md │ │ │ ├── chrome-command-line-switches.md │ │ │ ├── crash-reporter.md │ │ │ ├── remote.md │ │ │ ├── web-request.md │ │ │ ├── tray.md │ │ │ ├── client-request.md │ │ │ ├── native-image.md │ │ │ ├── system-preferences.md │ │ │ └── dialog.md │ └── malformed │ │ ├── some-module.md │ │ ├── some-class.md │ │ ├── some-class-without-process.md │ │ ├── some-class-without-description.md │ │ ├── structures │ │ └── some-structure.md │ │ ├── some-class-with-bad-instance-methods.md │ │ └── some-class-with-bad-instance-properties.md └── cli.js ├── .travis.yml ├── lib ├── attribute.js ├── event.js ├── property.js ├── collection.js ├── collection-item.js ├── method.js ├── schemata.js └── api.js ├── contributing.md ├── bin └── fetch-docs.js ├── package.json ├── cli.js ├── index.js └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | electron.json 3 | .npmrc -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .gitmodules 2 | .npmignore 3 | .travis.yml 4 | /test 5 | /vendor 6 | .npmrc -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/crash-report.md: -------------------------------------------------------------------------------- 1 | # CrashReport Object 2 | 3 | * `date` String 4 | * `ID` Integer -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/file-filter.md: -------------------------------------------------------------------------------- 1 | # FileFilter Object 2 | 3 | * `name` String 4 | * `extensions` String[] 5 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/bluetooth-device.md: -------------------------------------------------------------------------------- 1 | # BluetoothDevice Object 2 | 3 | * `deviceName` String 4 | * `deviceId` String 5 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/memory-usage-details.md: -------------------------------------------------------------------------------- 1 | # MemoryUsageDetails Object 2 | 3 | * `count` Number 4 | * `size` Number 5 | * `liveSize` Number 6 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/upload-blob.md: -------------------------------------------------------------------------------- 1 | # UploadBlob Object 2 | 3 | * `type` String - `blob`. 4 | * `blobUUID` String - UUID of blob data to upload. 5 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/upload-raw-data.md: -------------------------------------------------------------------------------- 1 | # UploadRawData Object 2 | 3 | * `type` String - `rawData`. 4 | * `bytes` Buffer - Data to be uploaded. 5 | -------------------------------------------------------------------------------- /test/fixtures/malformed/some-module.md: -------------------------------------------------------------------------------- 1 | # someModule 2 | 3 | > A pretend module that is properly documented 4 | 5 | Process: [Main](../tutorial/quick-start.md#main-process) 6 | -------------------------------------------------------------------------------- /test/fixtures/malformed/some-class.md: -------------------------------------------------------------------------------- 1 | ## Class: SomeClass 2 | 3 | > A pretend class that is properly documented 4 | 5 | Process: [Main](../tutorial/quick-start.md#main-process) 6 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/mime-typed-buffer.md: -------------------------------------------------------------------------------- 1 | # MimeTypedBuffer Object 2 | 3 | * `mimeType` String - The mimeType of the Buffer that you are sending 4 | * `buffer` Buffer - The actual Buffer content 5 | -------------------------------------------------------------------------------- /test/fixtures/malformed/some-class-without-process.md: -------------------------------------------------------------------------------- 1 | ## Class: SomeClassWithoutProcess 2 | 3 | > A pretend class that is missing a process annotation 4 | 5 | Process: [Main](../tutorial/quick-start.md#main-process) 6 | -------------------------------------------------------------------------------- /test/fixtures/malformed/some-class-without-description.md: -------------------------------------------------------------------------------- 1 | ## Class: SomeClassWithoutDescription 2 | 3 | 4 | 5 | Process: [Main](../tutorial/quick-start.md#main-process) 6 | -------------------------------------------------------------------------------- /test/fixtures/malformed/structures/some-structure.md: -------------------------------------------------------------------------------- 1 | # SomeStructure Object 2 | 3 | 4 | 5 | * `data` String - some data 6 | * `serialNumber` String - Hex value 7 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/rectangle.md: -------------------------------------------------------------------------------- 1 | # Rectangle Object 2 | 3 | * `x` Number - The x coordinate of the origin of the rectangle 4 | * `y` Number - The y coordinate of the origin of the rectangle 5 | * `width` Number 6 | * `height` Number 7 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/remove-client-certificate.md: -------------------------------------------------------------------------------- 1 | # RemoveClientCertificate Object 2 | 3 | * `type` String - `clientCertificate`. 4 | * `origin` String - Origin of the server whose associated client certificate 5 | must be removed from the cache. 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | cache: 3 | directories: 4 | - ~/.npm 5 | notifications: 6 | email: false 7 | node_js: 8 | - '9' 9 | - '8' 10 | - '6' 11 | after_success: 12 | - npm run semantic-release 13 | branches: 14 | except: 15 | - /^v\d+\.\d+\.\d+$/ 16 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/upload-data.md: -------------------------------------------------------------------------------- 1 | # UploadData Object 2 | 3 | * `bytes` Buffer - Content being sent. 4 | * `file` String - Path of file being uploaded. 5 | * `blobUUID` String - UUID of blob data. Use [ses.getBlobData](../session.md#sesgetblobdataidentifier-callback) method 6 | to retrieve the data. 7 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/touch-bar-group.md: -------------------------------------------------------------------------------- 1 | ## Class: TouchBarGroup 2 | 3 | > Create a group in the touch bar for native macOS applications 4 | 5 | Process: [Main](../tutorial/quick-start.md#main-process) 6 | 7 | ### `new TouchBarGroup(options)` 8 | 9 | * `options` Object 10 | * `items` TouchBar - Items to display as a group. 11 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/certificate-principal.md: -------------------------------------------------------------------------------- 1 | # CertificatePrincipal Object 2 | 3 | * `commonName` String - Common Name 4 | * `organizations` String[] - Organization names 5 | * `organizationUnits` String[] - Organization Unit names 6 | * `locality` String - Locality 7 | * `state` String - State or province 8 | * `country` String - Country or region 9 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/upload-file.md: -------------------------------------------------------------------------------- 1 | # UploadFile Object 2 | 3 | * `type` String - `file`. 4 | * `filePath` String - Path of file to be uploaded. 5 | * `offset` Integer - Defaults to `0`. 6 | * `length` Integer - Number of bytes to read from `offset`. 7 | Defaults to `0`. 8 | * `modificationTime` Double - Last Modification time in 9 | number of seconds sine the UNIX epoch. 10 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/upload-file-system.md: -------------------------------------------------------------------------------- 1 | # UploadFileSystem Object 2 | 3 | * `type` String - `fileSystem`. 4 | * `filsSystemURL` String - FileSystem url to read data for upload. 5 | * `offset` Integer - Defaults to `0`. 6 | * `length` Integer - Number of bytes to read from `offset`. 7 | Defaults to `0`. 8 | * `modificationTime` Double - Last Modification time in 9 | number of seconds sine the UNIX epoch. 10 | -------------------------------------------------------------------------------- /test/fixtures/malformed/some-class-with-bad-instance-methods.md: -------------------------------------------------------------------------------- 1 | ## Class: SomeClassWithBadInstanceMethods 2 | 3 | > A pretend class that has some messed up instanceMethods docs 4 | 5 | Process: [Main](../tutorial/quick-start.md#main-process) 6 | 7 | ### Instance Methods 8 | 9 | Here comes the list of methods: 10 | 11 | #### `klass.methodA()` 12 | 13 | This one is good. 14 | 15 | #### klass.methodB() 16 | 17 | This one is busted because there are no code blocks 18 | 19 | #### `klass.methodC()` 20 | 21 | This one is good. 22 | -------------------------------------------------------------------------------- /lib/attribute.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const CollectionItem = require('./collection-item') 4 | const pattern = /(.*)<\/code>/ 5 | const props = ['name', 'description', 'platforms'] 6 | 7 | module.exports = class Attribute extends CollectionItem { 8 | constructor (api, el) { 9 | super(api, el, pattern, props) 10 | 11 | if (this.match) { 12 | this.name = this.match[1] 13 | this.description = this.getDescription() 14 | this.platforms = this.getPlatforms() 15 | } 16 | 17 | return this 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /lib/event.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const CollectionItem = require('./collection-item') 4 | const pattern = /Event: '(.*)'/ 5 | const props = ['name', 'description', 'platforms', 'returns'] 6 | 7 | module.exports = class Event extends CollectionItem { 8 | constructor (api, el) { 9 | super(api, el, pattern, props) 10 | 11 | if (this.match) { 12 | this.name = this.match[1] 13 | this.description = this.getDescription() 14 | this.platforms = this.getPlatforms() 15 | this.returns = this.getParameters() 16 | } 17 | 18 | return this 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /test/fixtures/malformed/some-class-with-bad-instance-properties.md: -------------------------------------------------------------------------------- 1 | ## Class: SomeClassWithBadInstanceProperties 2 | 3 | > A pretend class that has some messed up instanceProperties docs 4 | 5 | Process: [Main](../tutorial/quick-start.md#main-process) 6 | 7 | ### Instance Properties 8 | 9 | Here comes the list of methods: 10 | 11 | #### `klass.propA` 12 | 13 | This one is good. 14 | 15 | #### klass.propB 16 | 17 | This one is busted because there are no code blocks 18 | 19 | #### `klass.propC` 20 | 21 | This one is good. 22 | 23 | #### `klass.propD` 24 | 25 | This one is good. 26 | 27 | 28 | ### Instance Methods 29 | 30 | Here comes the list of methods: 31 | 32 | #### `klass.methodX()` 33 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/certificate.md: -------------------------------------------------------------------------------- 1 | # Certificate Object 2 | 3 | * `data` String - PEM encoded data 4 | * `issuer` [CertificatePrincipal](certificate-principal.md) - Issuer principal 5 | * `issuerName` String - Issuer's Common Name 6 | * `issuerCert` Certificate - Issuer certificate (if not self-signed) 7 | * `subject` [CertificatePrincipal](certificate-principal.md) - Subject principal 8 | * `subjectName` String - Subject's Common Name 9 | * `serialNumber` String - Hex value represented string 10 | * `validStart` Number - Start date of the certificate being valid in seconds 11 | * `validExpiry` Number - End date of the certificate being valid in seconds 12 | * `fingerprint` String - Fingerprint of the certificate 13 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/event.md: -------------------------------------------------------------------------------- 1 | # Event Object extends `GlobalEvent` 2 | 3 | * `preventDefault` Function 4 | * `sender` WebContents 5 | * `returnValue` any 6 | * `ctrlKey` Boolean (optional) - whether the Control key was used in an accelerator to trigger the Event 7 | * `metaKey` Boolean (optional) - whether a meta key was used in an accelerator to trigger the Event 8 | * `shiftKey` Boolean (optional) - whether a Shift key was used in an accelerator to trigger the Event 9 | * `altKey` Boolean (optional) - whether an Alt key was used in an accelerator to trigger the Event 10 | * `triggeredByAccelerator` Boolean (optional) - whether an accelerator was used to trigger the event as opposed to another user gesture like mouse click 11 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | :+1::tada: First off, thanks for taking the time to contribute! :tada::+1: 4 | 5 | The following is a set of guidelines for contributing to electron-docs-linter 6 | on GitHub. These are just guidelines, not rules, so use your best judgment 7 | and feel free to propose changes to this document in a pull request. 8 | 9 | ## Development 10 | 11 | Install dependencies and run the tests: 12 | 13 | ```sh 14 | npm i && npm t 15 | ``` 16 | 17 | To fetch the latest docs from electron/electron's master branch: 18 | 19 | ```sh 20 | npm run fetch-docs 21 | ``` 22 | 23 | Sometimes it's useful to test against another branch or commit: 24 | 25 | ```sh 26 | npm run fetch-docs -- some-other-branch 27 | # or 28 | npm run fetch-docs -- 75b010ce6314c56ec083adfa1a9835e3cfa348ea 29 | ``` 30 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/remove-password.md: -------------------------------------------------------------------------------- 1 | # RemovePassword Object 2 | 3 | * `type` String - `password`. 4 | * `origin` String (optional) - When provided, the authentication info 5 | related to the origin will only be removed otherwise the entire cache 6 | will be cleared. 7 | * `scheme` String (optional) - Scheme of the authentication. 8 | Can be `basic`, `digest`, `ntlm`, `negotiate`. Must be provided if 9 | removing by `origin`. 10 | * `realm` String (optional) - Realm of the authentication. Must be provided if 11 | removing by `origin`. 12 | * `username` String (optional) - Credentials of the authentication. Must be 13 | provided if removing by `origin`. 14 | * `password` String (optional) - Credentials of the authentication. Must be 15 | provided if removing by `origin`. 16 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/cookie.md: -------------------------------------------------------------------------------- 1 | # Cookie Object 2 | 3 | * `name` String - The name of the cookie. 4 | * `value` String - The value of the cookie. 5 | * `domain` String (optional) - The domain of the cookie. 6 | * `hostOnly` Boolean (optional) - Whether the cookie is a host-only cookie. 7 | * `path` String (optional) - The path of the cookie. 8 | * `secure` Boolean (optional) - Whether the cookie is marked as secure. 9 | * `httpOnly` Boolean (optional) - Whether the cookie is marked as HTTP only. 10 | * `session` Boolean (optional) - Whether the cookie is a session cookie or a persistent 11 | cookie with an expiration date. 12 | * `expirationDate` Double (optional) - The expiration date of the cookie as 13 | the number of seconds since the UNIX epoch. Not provided for session 14 | cookies. 15 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/display.md: -------------------------------------------------------------------------------- 1 | # Display Object 2 | 3 | * `id` Number - Unique identifier associated with the display. 4 | * `rotation` Number - Can be 0, 90, 180, 270, represents screen rotation in 5 | clock-wise degrees. 6 | * `scaleFactor` Number - Output device's pixel scale factor. 7 | * `touchSupport` String - Can be `available`, `unavailable`, `unknown`. 8 | * `bounds` [Rectangle](rectangle.md) 9 | * `size` Object 10 | * `height` Number 11 | * `width` Number 12 | * `workArea` [Rectangle](rectangle.md) 13 | * `workAreaSize` Object 14 | * `height` Number 15 | * `width` Number 16 | 17 | The `Display` object represents a physical display connected to the system. A 18 | fake `Display` may exist on a headless system, or a `Display` may correspond to 19 | a remote, virtual display. 20 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/shortcut-details.md: -------------------------------------------------------------------------------- 1 | # ShortcutDetails Object 2 | 3 | * `target` String - The target to launch from this shortcut. 4 | * `cwd` String (optional) - The working directory. Default is empty. 5 | * `args` String (optional) - The arguments to be applied to `target` when 6 | launching from this shortcut. Default is empty. 7 | * `description` String (optional) - The description of the shortcut. Default 8 | is empty. 9 | * `icon` String (optional) - The path to the icon, can be a DLL or EXE. `icon` 10 | and `iconIndex` have to be set together. Default is empty, which uses the 11 | target's icon. 12 | * `iconIndex` Number (optional) - The resource ID of icon when `icon` is a 13 | DLL or EXE. Default is 0. 14 | * `appUserModelId` String (optional) - The Application User Model ID. Default 15 | is empty. 16 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/task.md: -------------------------------------------------------------------------------- 1 | # Task Object 2 | 3 | * `program` String - Path of the program to execute, usually you should 4 | specify `process.execPath` which opens the current program. 5 | * `arguments` String - The command line arguments when `program` is 6 | executed. 7 | * `title` String - The string to be displayed in a JumpList. 8 | * `description` String - Description of this task. 9 | * `iconPath` String - The absolute path to an icon to be displayed in a 10 | JumpList, which can be an arbitrary resource file that contains an icon. You 11 | can usually specify `process.execPath` to show the icon of the program. 12 | * `iconIndex` Number - The icon index in the icon file. If an icon file 13 | consists of two or more icons, set this value to identify the icon. If an 14 | icon file consists of one icon, this value is 0. 15 | -------------------------------------------------------------------------------- /bin/fetch-docs.js: -------------------------------------------------------------------------------- 1 | const electronDocs = require('electron-docs') 2 | const fs = require('fs') 3 | const path = require('path') 4 | const rm = require('rimraf').sync 5 | const mkdirp = require('mkdirp').sync 6 | const fixturePath = path.join(__dirname, '../test/fixtures/electron/docs/api/') 7 | var version = process.argv[2] 8 | 9 | console.log('removing any existing fixtures') 10 | rm(fixturePath) 11 | 12 | if (!version) { 13 | version = 'master' 14 | console.log('defaulting to master branch') 15 | } else { 16 | console.log(`fetching docs from ${version}`) 17 | } 18 | 19 | electronDocs(version).then(docs => { 20 | docs.forEach(doc => { 21 | const filename = path.join(fixturePath, doc.filename) 22 | console.log(path.relative(__dirname, filename)) 23 | mkdirp(path.dirname(filename)) 24 | fs.writeFileSync(filename, doc.markdown_content) 25 | }) 26 | }) 27 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/desktop-capturer-source.md: -------------------------------------------------------------------------------- 1 | # DesktopCapturerSource Object 2 | 3 | * `id` String - The identifier of a window or screen that can be used as a 4 | `chromeMediaSourceId` constraint when calling 5 | [`navigator.webkitGetUserMedia`]. The format of the identifier will be 6 | `window:XX` or `screen:XX`, where `XX` is a random generated number. 7 | * `name` String - A screen source will be named either `Entire Screen` or 8 | `Screen `, while the name of a window source will match the window 9 | title. 10 | * `thumbnail` [NativeImage](../native-image.md) - A thumbnail image. **Note:** 11 | There is no guarantee that the size of the thumbnail is the same as the 12 | `thumbnailSize` specified in the `options` passed to 13 | `desktopCapturer.getSources`. The actual size depends on the scale of the 14 | screen or window. 15 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/power-monitor.md: -------------------------------------------------------------------------------- 1 | # powerMonitor 2 | 3 | > Monitor power state changes. 4 | 5 | Process: [Main](../glossary.md#main-process) 6 | 7 | You cannot require or use this module until the `ready` event of the `app` 8 | module is emitted. 9 | 10 | For example: 11 | 12 | ```javascript 13 | const electron = require('electron') 14 | const {app} = electron 15 | 16 | app.on('ready', () => { 17 | electron.powerMonitor.on('suspend', () => { 18 | console.log('The system is going to sleep') 19 | }) 20 | }) 21 | ``` 22 | 23 | ## Events 24 | 25 | The `powerMonitor` module emits the following events: 26 | 27 | ### Event: 'suspend' 28 | 29 | Emitted when the system is suspending. 30 | 31 | ### Event: 'resume' 32 | 33 | Emitted when system is resuming. 34 | 35 | ### Event: 'on-ac' _Windows_ 36 | 37 | Emitted when the system changes to AC power. 38 | 39 | ### Event: 'on-battery' _Windows_ 40 | 41 | Emitted when system changes to battery power. 42 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/file-object.md: -------------------------------------------------------------------------------- 1 | # `File` Object 2 | 3 | > Use the HTML5 `File` API to work natively with files on the filesystem. 4 | 5 | The DOM's File interface provides abstraction around native files in order to 6 | let users work on native files directly with the HTML5 file API. Electron has 7 | added a `path` attribute to the `File` interface which exposes the file's real 8 | path on filesystem. 9 | 10 | Example of getting a real path from a dragged-onto-the-app file: 11 | 12 | ```html 13 |
14 | Drag your file here 15 |
16 | 17 | 33 | ``` 34 | -------------------------------------------------------------------------------- /lib/property.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const CollectionItem = require('./collection-item') 4 | const parsers = require('./parsers') 5 | 6 | const pattern = /.*?\.(?:(\w+)\.)?(\w+)<\/code>/ 7 | const typePattern = /An? ([a-zA-Z]+(?:<[a-zA-Z[\]]+>)?(?:\[])?) ?/ 8 | const props = ['name', 'description', 'type', 'innerType', 'collection', '_superObject'] 9 | 10 | module.exports = class Property extends CollectionItem { 11 | constructor (api, el) { 12 | super(api, el, pattern, props) 13 | 14 | if (this.match) { 15 | this.name = this.match[2] 16 | if (this.match[1]) this._superObject = this.match[1] 17 | this.description = this.getDescription() 18 | this.type = null 19 | const typeMatch = typePattern.exec(this.description) 20 | if (typeMatch) { 21 | const typeInfo = parsers.getInnerType(parsers.stripArrTags(typeMatch[1])) 22 | this.type = typeInfo.outer 23 | this.innerType = typeInfo.inner 24 | this.collection = typeMatch[1].endsWith('[]') 25 | } 26 | } 27 | 28 | return this 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/thumbar-button.md: -------------------------------------------------------------------------------- 1 | # ThumbarButton Object 2 | 3 | * `icon` [NativeImage](../native-image.md) - The icon showing in thumbnail 4 | toolbar. 5 | * `click` Function 6 | * `tooltip` String (optional) - The text of the button's tooltip. 7 | * `flags` String[] (optional) - Control specific states and behaviors of the 8 | button. By default, it is `['enabled']`. 9 | 10 | The `flags` is an array that can include following `String`s: 11 | 12 | * `enabled` - The button is active and available to the user. 13 | * `disabled` - The button is disabled. It is present, but has a visual state 14 | indicating it will not respond to user action. 15 | * `dismissonclick` - When the button is clicked, the thumbnail window closes 16 | immediately. 17 | * `nobackground` - Do not draw a button border, use only the image. 18 | * `hidden` - The button is not shown to the user. 19 | * `noninteractive` - The button is enabled but not interactive; no pressed 20 | button state is drawn. This value is intended for instances where the button 21 | is used in a notification. 22 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/jump-list-category.md: -------------------------------------------------------------------------------- 1 | # JumpListCategory Object 2 | 3 | * `type` String (optional) - One of the following: 4 | * `tasks` - Items in this category will be placed into the standard `Tasks` 5 | category. There can be only one such category, and it will always be 6 | displayed at the bottom of the Jump List. 7 | * `frequent` - Displays a list of files frequently opened by the app, the 8 | name of the category and its items are set by Windows. 9 | * `recent` - Displays a list of files recently opened by the app, the name 10 | of the category and its items are set by Windows. Items may be added to 11 | this category indirectly using `app.addRecentDocument(path)`. 12 | * `custom` - Displays tasks or file links, `name` must be set by the app. 13 | * `name` String (optional) - Must be set if `type` is `custom`, otherwise it should be 14 | omitted. 15 | * `items` JumpListItem[] (optional) - Array of [`JumpListItem`](jump-list-item.md) objects if `type` is `tasks` or 16 | `custom`, otherwise it should be omitted. 17 | 18 | **Note:** If a `JumpListCategory` object has neither the `type` nor the `name` 19 | property set then its `type` is assumed to be `tasks`. If the `name` property 20 | is set but the `type` property is omitted then the `type` is assumed to be 21 | `custom`. 22 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/browser-window-proxy.md: -------------------------------------------------------------------------------- 1 | ## Class: BrowserWindowProxy 2 | 3 | > Manipulate the child browser window 4 | 5 | Process: [Renderer](../glossary.md#renderer-process) 6 | 7 | The `BrowserWindowProxy` object is returned from `window.open` and provides 8 | limited functionality with the child window. 9 | 10 | ### Instance Methods 11 | 12 | The `BrowserWindowProxy` object has the following instance methods: 13 | 14 | #### `win.blur()` 15 | 16 | Removes focus from the child window. 17 | 18 | #### `win.close()` 19 | 20 | Forcefully closes the child window without calling its unload event. 21 | 22 | #### `win.eval(code)` 23 | 24 | * `code` String 25 | 26 | Evaluates the code in the child window. 27 | 28 | #### `win.focus()` 29 | 30 | Focuses the child window (brings the window to front). 31 | 32 | #### `win.print()` 33 | 34 | Invokes the print dialog on the child window. 35 | 36 | #### `win.postMessage(message, targetOrigin)` 37 | 38 | * `message` String 39 | * `targetOrigin` String 40 | 41 | Sends a message to the child window with the specified origin or `*` for no 42 | origin preference. 43 | 44 | In addition to these methods, the child window implements `window.opener` object 45 | with no properties and a single method. 46 | 47 | ### Instance Properties 48 | 49 | The `BrowserWindowProxy` object has the following instance properties: 50 | 51 | #### `win.closed` 52 | 53 | A Boolean that is set to true after the child window gets closed. 54 | -------------------------------------------------------------------------------- /lib/collection.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const decamelize = require('decamelize') 4 | const CollectionItemTypes = { 5 | Event: require('./event'), 6 | Method: require('./method'), 7 | Property: require('./property'), 8 | Attribute: require('./attribute') 9 | } 10 | 11 | class Collection { 12 | // new Collection('Event', api, '#events', 2) 13 | // new Collection('Method', api, '#methods', 2) 14 | // new Collection('Event', api, `h3#class-${api.name}-instance-events`, 3) 15 | constructor (type, api, selector, headingLevel) { 16 | const list = api.$(selector) 17 | .nextUntil(`h${headingLevel}`) 18 | .filter((i, el) => api.$(el).get(0).tagName === `h${headingLevel + 1}`) 19 | 20 | // Count how many headings are present in this swath. This count will 21 | // later be used to verify all items in the Collection were properly parsed 22 | api.expectedCounts = api.expectedCounts || {} 23 | Collection.types.forEach(collectionType => { 24 | const selectorPattern = new RegExp(`${decamelize(collectionType, '-')}$`) 25 | if (selector.match(selectorPattern)) { 26 | api.expectedCounts[collectionType] = list.length 27 | } 28 | }) 29 | 30 | return list 31 | .map((i, el) => new CollectionItemTypes[type](api, el)) 32 | .get() 33 | .filter(item => item.valid) 34 | } 35 | } 36 | 37 | Collection.types = [ 38 | 'instanceEvents', 39 | 'instanceMethods', 40 | 'instanceProperties', 41 | 'staticMethods', 42 | 'staticProperties', 43 | 'attributes' 44 | ] 45 | 46 | module.exports = Collection 47 | -------------------------------------------------------------------------------- /lib/collection-item.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const cleanDeep = require('clean-deep') 4 | const pick = require('lodash.pick') 5 | const parsers = require('./parsers') 6 | const assert = require('assert') 7 | 8 | module.exports = class CollectionItem { 9 | constructor (api, openingHeadingElement, pattern, props) { 10 | assert(api, 'api is required') 11 | assert(openingHeadingElement, 'openingHeadingElement is required') 12 | assert(props, 'props are required') 13 | assert(pattern, 'pattern is required') 14 | 15 | this.props = props 16 | this.pattern = pattern 17 | this.$ = api.$ 18 | this.api = api 19 | this.$openingHeadingElement = this.$(openingHeadingElement) 20 | } 21 | 22 | get match () { 23 | return this.$openingHeadingElement.html().match(this.pattern) 24 | } 25 | 26 | get valid () { 27 | return this.name && this.name.length 28 | } 29 | 30 | inspect () { 31 | return this.toJSON() 32 | } 33 | 34 | // When stringifying, only include the properties that are explicitly 35 | // specified in this.props 36 | toJSON () { 37 | return cleanDeep(pick(this, this.props)) 38 | } 39 | 40 | getDescription () { 41 | return parsers.description(this.$, this.$openingHeadingElement) 42 | } 43 | 44 | getPlatforms () { 45 | return parsers.platforms(this.$, this.$openingHeadingElement) 46 | } 47 | 48 | getParameters () { 49 | return parsers.parameters(this.$, this.$openingHeadingElement, this.api) 50 | } 51 | 52 | getReturns () { 53 | return parsers.returns(this.$, this.$openingHeadingElement, this.api) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /test/cli.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | const exec = require('child_process').exec 3 | const chai = require('chai') 4 | const dirtyChai = require('dirty-chai') 5 | const rimraf = require('rimraf').sync 6 | const keyedArray = require('keyed-array') 7 | 8 | const expect = chai.expect 9 | chai.use(dirtyChai) 10 | 11 | describe('CLI', function () { 12 | this.timeout(10 * 1000) 13 | 14 | it('produces a JSON file', function () { 15 | rimraf(path.join(__dirname, 'electron.json')) 16 | exec('node ' + path.join(__dirname, '../cli.js test/fixtures/electron/docs/api --version=1.2.3 --outfile=test/electron.json'), function (err, stdout, stderr) { 17 | expect(err).to.eq(null) 18 | const apis = keyedArray(require('./electron.json')) 19 | 20 | expect(apis).to.be.an('array') 21 | expect(apis.length).to.be.above(10) 22 | 23 | // check for instanceName property on all classes 24 | var classes = apis.filter(api => api.type === 'Class') 25 | expect(classes.length).to.be.above(10) 26 | expect(classes.every(api => api.instanceName.length > 0)).to.equal(true) 27 | 28 | // clean up 29 | rimraf(path.join(__dirname, 'electron.json')) 30 | }) 31 | }) 32 | 33 | it('prints errors to STDERR', function (done) { 34 | exec('node ' + path.join(__dirname, '../cli.js test/fixtures/malformed'), function (err, stdout, stderr) { 35 | expect(err).to.exist() 36 | expect(stderr).to.include('expected 3 instanceMethods but only found 2') 37 | expect(stderr).to.include('expected 4 instanceProperties but only found 3') 38 | expect(stderr).to.include('description must not be empty') 39 | done() 40 | }) 41 | }) 42 | }) 43 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/window-open.md: -------------------------------------------------------------------------------- 1 | # `window.open` Function 2 | 3 | > Open a new window and load a URL. 4 | 5 | When `window.open` is called to create a new window in a web page, a new instance 6 | of `BrowserWindow` will be created for the `url` and a proxy will be returned 7 | to `window.open` to let the page have limited control over it. 8 | 9 | The proxy has limited standard functionality implemented to be 10 | compatible with traditional web pages. For full control of the new window 11 | you should create a `BrowserWindow` directly. 12 | 13 | The newly created `BrowserWindow` will inherit the parent window's options by 14 | default. To override inherited options you can set them in the `features` 15 | string. 16 | 17 | ### `window.open(url[, frameName][, features])` 18 | 19 | * `url` String 20 | * `frameName` String (optional) 21 | * `features` String (optional) 22 | 23 | Returns [`BrowserWindowProxy`](browser-window-proxy.md) - Creates a new window 24 | and returns an instance of `BrowserWindowProxy` class. 25 | 26 | The `features` string follows the format of standard browser, but each feature 27 | has to be a field of `BrowserWindow`'s options. 28 | 29 | **Notes:** 30 | 31 | * Node integration will always be disabled in the opened `window` if it is 32 | disabled on the parent window. 33 | * Non-standard features (that are not handled by Chromium or Electron) given in 34 | `features` will be passed to any registered `webContent`'s `new-window` event 35 | handler in the `additionalFeatures` argument. 36 | 37 | ### `window.opener.postMessage(message, targetOrigin)` 38 | 39 | * `message` String 40 | * `targetOrigin` String 41 | 42 | Sends a message to the parent window with the specified origin or `*` for no 43 | origin preference. 44 | -------------------------------------------------------------------------------- /lib/method.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const CollectionItem = require('./collection-item') 4 | const pattern = /..*?\.((?:\w+\.?)+)(.*)<\/code>/ 5 | const props = ['name', 'signature', 'platforms', 'description', 'parameters', 'returns', '_superObject'] 6 | 7 | module.exports = class Method extends CollectionItem { 8 | constructor (api, el) { 9 | super(api, el, pattern, props) 10 | 11 | if (this.match) { 12 | this.name = this.match[1] 13 | this.signature = this.match[2] 14 | this.platforms = this.getPlatforms() 15 | this.description = this.getDescription() 16 | this.parameters = this.getParameters() 17 | this.returns = this.getReturns() 18 | 19 | const subProp = this.name.split('.') 20 | if (subProp.length === 2) { 21 | this.name = subProp[1] 22 | this._superObject = subProp[0] 23 | } else if (subProp.length > 2) { 24 | console.error('Problem parsing deep subproperty') 25 | console.error(`pattern: ${pattern}`) 26 | console.error(`el: ${el}`) 27 | } 28 | // derive an array of parameter names from the method signature; 29 | // used only in tests to verify that all parameters are documented 30 | // 31 | // "()" becomes [] 32 | // "(code[, userGesture])" becomes ['code', 'userGesture'] 33 | // (channel[, arg1][, arg2][, ...]) becomes ['channel'] 34 | if (this.signature === '()') { 35 | this.signatureParameters = [] 36 | } else { 37 | this.signatureParameters = this.signature 38 | .replace(/\[.*\.\.\.]/, '') 39 | .replace(/\W/g, ' ') 40 | .replace(/\s+/g, ' ') 41 | .trim() 42 | .split(' ') 43 | } 44 | } 45 | 46 | return this 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/structures/jump-list-item.md: -------------------------------------------------------------------------------- 1 | # JumpListItem Object 2 | 3 | * `type` String (optional) - One of the following: 4 | * `task` - A task will launch an app with specific arguments. 5 | * `separator` - Can be used to separate items in the standard `Tasks` 6 | category. 7 | * `file` - A file link will open a file using the app that created the 8 | Jump List, for this to work the app must be registered as a handler for 9 | the file type (though it doesn't have to be the default handler). 10 | * `path` String (optional) - Path of the file to open, should only be set if `type` is 11 | `file`. 12 | * `program` String (optional) - Path of the program to execute, usually you should 13 | specify `process.execPath` which opens the current program. Should only be 14 | set if `type` is `task`. 15 | * `args` String (optional) - The command line arguments when `program` is executed. Should 16 | only be set if `type` is `task`. 17 | * `title` String (optional) - The text to be displayed for the item in the Jump List. 18 | Should only be set if `type` is `task`. 19 | * `description` String (optional) - Description of the task (displayed in a tooltip). 20 | Should only be set if `type` is `task`. 21 | * `iconPath` String (optional) - The absolute path to an icon to be displayed in a 22 | Jump List, which can be an arbitrary resource file that contains an icon 23 | (e.g. `.ico`, `.exe`, `.dll`). You can usually specify `process.execPath` to 24 | show the program icon. 25 | * `iconIndex` Number (optional) - The index of the icon in the resource file. If a 26 | resource file contains multiple icons this value can be used to specify the 27 | zero-based index of the icon that should be displayed for this task. If a 28 | resource file contains only one icon, this property should be set to zero. 29 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "electron-docs-linter", 3 | "description": "A JSON object describing Electron's APIs", 4 | "version": "0.0.0-development", 5 | "author": "Zeke Sikelianos (http://zeke.sikelianos.com)", 6 | "bin": "cli.js", 7 | "dependencies": { 8 | "cheerio": "^1.0.0-rc.2", 9 | "clean-deep": "^2.0.1", 10 | "decamelize": "^2.0.0", 11 | "dedent": "^0.7.0", 12 | "electron-docs": "^3.0.2", 13 | "entities": "^1.1.2", 14 | "keyed-array": "^2.1.2", 15 | "lodash.merge": "^4.6.0", 16 | "lodash.pick": "^4.2.1", 17 | "marky-markdown-lite": "^1.2.0", 18 | "minimist": "^1.2.0", 19 | "ora": "^3.0.0", 20 | "path-exists": "^3.0.0", 21 | "pify": "^4.0.1", 22 | "revalidator": "^0.3.1", 23 | "semver": "^5.6.0" 24 | }, 25 | "devDependencies": { 26 | "chai": "^4.2.0", 27 | "check-for-leaks": "^1.2.0", 28 | "dirty-chai": "^2.0.1", 29 | "husky": "^1.1.2", 30 | "mkdirp": "^0.5.1", 31 | "mocha": "^5.2.0", 32 | "rimraf": "^2.5.4", 33 | "semantic-release": "^17.2.3", 34 | "standard": "^12.0.1" 35 | }, 36 | "homepage": "https://github.com/electron/electron-docs-linter#readme", 37 | "keywords": [ 38 | "api", 39 | "documentation", 40 | "electron", 41 | "json", 42 | "markdown", 43 | "node", 44 | "schema" 45 | ], 46 | "license": "MIT", 47 | "main": "index.js", 48 | "repository": "https://github.com/electron/electron-docs-linter", 49 | "scripts": { 50 | "fetch-docs": "node bin/fetch-docs.js master", 51 | "generate": "node cli.js test/fixtures/electron --version=1.4.1 --outfile=electron.json && open electron.json", 52 | "test": "mocha test/*.js && standard", 53 | "prepack": "check-for-leaks", 54 | "prepush": "check-for-leaks", 55 | "semantic-release": "semantic-release pre && npm publish && semantic-release post" 56 | }, 57 | "standard": { 58 | "env": { 59 | "mocha": true 60 | } 61 | }, 62 | "engines": { 63 | "node": ">=6" 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /lib/schemata.js: -------------------------------------------------------------------------------- 1 | const merge = require('lodash.merge') 2 | 3 | const commonSchema = { 4 | properties: { 5 | name: { 6 | type: 'string', 7 | required: true, 8 | allowEmpty: false 9 | }, 10 | type: { 11 | type: 'string', 12 | required: true, 13 | enum: ['Class', 'Module', 'Structure', 'Element'] 14 | } 15 | } 16 | } 17 | 18 | const apiSchema = { 19 | properties: { 20 | description: { 21 | type: 'string', 22 | required: true, 23 | allowEmpty: false 24 | }, 25 | process: { 26 | type: 'object' 27 | }, 28 | websiteUrl: { 29 | format: 'url', 30 | required: true 31 | }, 32 | repoUrl: { 33 | format: 'url', 34 | required: true 35 | } 36 | } 37 | } 38 | 39 | const moduleSchema = { 40 | properties: { 41 | events: { 42 | type: 'array', 43 | allowEmpty: false 44 | }, 45 | methods: { 46 | type: 'array', 47 | allowEmpty: false 48 | } 49 | } 50 | } 51 | 52 | const classSchema = { 53 | properties: { 54 | instanceEvents: { 55 | type: 'array', 56 | allowEmpty: false 57 | }, 58 | instanceMethods: { 59 | type: 'array', 60 | allowEmpty: false 61 | }, 62 | instanceProperties: { 63 | type: 'array', 64 | allowEmpty: false 65 | }, 66 | staticMethods: { 67 | type: 'array', 68 | allowEmpty: false 69 | }, 70 | instanceName: { 71 | type: 'string', 72 | required: true, 73 | allowEmpty: false 74 | } 75 | } 76 | } 77 | 78 | const elementSchema = { 79 | properties: { 80 | methods: { 81 | type: 'array' 82 | }, 83 | attributes: { 84 | type: 'array', 85 | allowEmpty: false 86 | } 87 | } 88 | } 89 | 90 | module.exports = { 91 | Structure: merge({}, commonSchema), 92 | Module: merge({}, commonSchema, apiSchema, moduleSchema), 93 | Class: merge({}, commonSchema, apiSchema, classSchema), 94 | Element: merge({}, commonSchema, apiSchema, elementSchema) 95 | } 96 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/power-save-blocker.md: -------------------------------------------------------------------------------- 1 | # powerSaveBlocker 2 | 3 | > Block the system from entering low-power (sleep) mode. 4 | 5 | Process: [Main](../glossary.md#main-process) 6 | 7 | For example: 8 | 9 | ```javascript 10 | const {powerSaveBlocker} = require('electron') 11 | 12 | const id = powerSaveBlocker.start('prevent-display-sleep') 13 | console.log(powerSaveBlocker.isStarted(id)) 14 | 15 | powerSaveBlocker.stop(id) 16 | ``` 17 | 18 | ## Methods 19 | 20 | The `powerSaveBlocker` module has the following methods: 21 | 22 | ### `powerSaveBlocker.start(type)` 23 | 24 | * `type` String - Power save blocker type. 25 | * `prevent-app-suspension` - Prevent the application from being suspended. 26 | Keeps system active but allows screen to be turned off. Example use cases: 27 | downloading a file or playing audio. 28 | * `prevent-display-sleep` - Prevent the display from going to sleep. Keeps 29 | system and screen active. Example use case: playing video. 30 | 31 | Returns `Integer` - The blocker ID that is assigned to this power blocker 32 | 33 | Starts preventing the system from entering lower-power mode. Returns an integer 34 | identifying the power save blocker. 35 | 36 | **Note:** `prevent-display-sleep` has higher precedence over 37 | `prevent-app-suspension`. Only the highest precedence type takes effect. In 38 | other words, `prevent-display-sleep` always takes precedence over 39 | `prevent-app-suspension`. 40 | 41 | For example, an API calling A requests for `prevent-app-suspension`, and 42 | another calling B requests for `prevent-display-sleep`. `prevent-display-sleep` 43 | will be used until B stops its request. After that, `prevent-app-suspension` 44 | is used. 45 | 46 | ### `powerSaveBlocker.stop(id)` 47 | 48 | * `id` Integer - The power save blocker id returned by `powerSaveBlocker.start`. 49 | 50 | Stops the specified power save blocker. 51 | 52 | ### `powerSaveBlocker.isStarted(id)` 53 | 54 | * `id` Integer - The power save blocker id returned by `powerSaveBlocker.start`. 55 | 56 | Returns `Boolean` - Whether the corresponding `powerSaveBlocker` has started. 57 | -------------------------------------------------------------------------------- /cli.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const fs = require('fs') 4 | const path = require('path') 5 | const dedent = require('dedent') 6 | const lint = require('.') 7 | const args = require('minimist')(process.argv.slice(2)) 8 | 9 | var docsPath = args._[0] || 'docs/api' 10 | var version = args.version || process.env.npm_package_version 11 | var outfile = args.outfile 12 | 13 | // docsPath is required 14 | if (!docsPath) usage('specify a pathname, .e.g ~/my/electron/electron') 15 | 16 | // docsPath is relative to current working directory 17 | docsPath = path.join(process.cwd(), docsPath) 18 | 19 | // outfile is relative to current working directory 20 | if (outfile) outfile = path.join(process.cwd(), outfile) 21 | 22 | // version is required if writing to a file 23 | if (outfile && !version) usage('`version` is required if `outfile` is specified') 24 | 25 | // Use a placeholder version if not writing to a file 26 | if (!version) version = '0.0.0' 27 | 28 | const spinner = require('ora')('Parsing electron documentation').start() 29 | 30 | lint(docsPath, version).then(function (apis) { 31 | spinner.stop().clear() 32 | 33 | apis.forEach(api => console.error(api.report())) 34 | 35 | if (apis.some(api => !api.valid)) process.exit(1) 36 | 37 | if (outfile) { 38 | fs.writeFileSync(outfile, JSON.stringify(apis, null, 2)) 39 | console.log(dedent` 40 | Created ${path.relative(process.cwd(), outfile)} 41 | `) 42 | } else { 43 | console.log(dedent` 44 | Docs are good to go!\n 45 | To write the docs schema to a file, specify \`version\` and \`outfile\`:\n 46 | electron-docs-linter ${path.relative(process.cwd(), docsPath)} --version=1.2.3 --outfile=electron.json 47 | `) 48 | } 49 | 50 | process.exit() 51 | }).catch(error => { 52 | console.error(error) 53 | process.exit(1) 54 | }) 55 | 56 | function usage (reason) { 57 | if (reason) console.error(`Error: ${reason}`) 58 | 59 | console.error(dedent` 60 | Usage: electron-docs-linter \n 61 | To save the parsed JSON schema:\n 62 | electron-docs-linter --version=1.2.3 --outfile=electron.json\n`) 63 | process.exit(1) 64 | } 65 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/accelerator.md: -------------------------------------------------------------------------------- 1 | # Accelerator 2 | 3 | > Define keyboard shortcuts. 4 | 5 | Accelerators are Strings that can contain multiple modifiers and key codes, 6 | combined by the `+` character, and are used to define keyboard shortcuts 7 | throughout your application. 8 | 9 | Examples: 10 | 11 | * `CommandOrControl+A` 12 | * `CommandOrControl+Shift+Z` 13 | 14 | Shortcuts are registered with the [`globalShortcut`](global-shortcut.md) module 15 | using the [`register`](global-shortcut.md#globalshortcutregisteraccelerator-callback) 16 | method, i.e. 17 | 18 | ```javascript 19 | const {app, globalShortcut} = require('electron') 20 | 21 | app.on('ready', () => { 22 | // Register a 'CommandOrControl+Y' shortcut listener. 23 | globalShortcut.register('CommandOrControl+Y', () => { 24 | // Do stuff when Y and either Command/Control is pressed. 25 | }) 26 | }) 27 | ``` 28 | 29 | ## Platform notice 30 | 31 | On Linux and Windows, the `Command` key does not have any effect so 32 | use `CommandOrControl` which represents `Command` on macOS and `Control` on 33 | Linux and Windows to define some accelerators. 34 | 35 | Use `Alt` instead of `Option`. The `Option` key only exists on macOS, whereas 36 | the `Alt` key is available on all platforms. 37 | 38 | The `Super` key is mapped to the `Windows` key on Windows and Linux and 39 | `Cmd` on macOS. 40 | 41 | ## Available modifiers 42 | 43 | * `Command` (or `Cmd` for short) 44 | * `Control` (or `Ctrl` for short) 45 | * `CommandOrControl` (or `CmdOrCtrl` for short) 46 | * `Alt` 47 | * `Option` 48 | * `AltGr` 49 | * `Shift` 50 | * `Super` 51 | 52 | ## Available key codes 53 | 54 | * `0` to `9` 55 | * `A` to `Z` 56 | * `F1` to `F24` 57 | * Punctuations like `~`, `!`, `@`, `#`, `$`, etc. 58 | * `Plus` 59 | * `Space` 60 | * `Tab` 61 | * `Backspace` 62 | * `Delete` 63 | * `Insert` 64 | * `Return` (or `Enter` as alias) 65 | * `Up`, `Down`, `Left` and `Right` 66 | * `Home` and `End` 67 | * `PageUp` and `PageDown` 68 | * `Escape` (or `Esc` for short) 69 | * `VolumeUp`, `VolumeDown` and `VolumeMute` 70 | * `MediaNextTrack`, `MediaPreviousTrack`, `MediaStop` and `MediaPlayPause` 71 | * `PrintScreen` 72 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/incoming-message.md: -------------------------------------------------------------------------------- 1 | ## Class: IncomingMessage 2 | 3 | > Handle responses to HTTP/HTTPS requests. 4 | 5 | Process: [Main](../glossary.md#main-process) 6 | 7 | `IncomingMessage` implements the [Readable Stream](https://nodejs.org/api/stream.html#stream_readable_streams) 8 | interface and is therefore an [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter). 9 | 10 | ### Instance Events 11 | 12 | #### Event: 'data' 13 | 14 | Returns: 15 | 16 | * `chunk` Buffer - A chunk of response body's data. 17 | 18 | The `data` event is the usual method of transferring response data into 19 | applicative code. 20 | 21 | #### Event: 'end' 22 | 23 | Indicates that response body has ended. 24 | 25 | #### Event: 'aborted' 26 | 27 | Emitted when a request has been canceled during an ongoing HTTP transaction. 28 | 29 | #### Event: 'error' 30 | 31 | Returns: 32 | 33 | `error` Error - Typically holds an error string identifying failure root cause. 34 | 35 | Emitted when an error was encountered while streaming response data events. For 36 | instance, if the server closes the underlying while the response is still 37 | streaming, an `error` event will be emitted on the response object and a `close` 38 | event will subsequently follow on the request object. 39 | 40 | ### Instance Properties 41 | 42 | An `IncomingMessage` instance has the following readable properties: 43 | 44 | #### `response.statusCode` 45 | 46 | An Integer indicating the HTTP response status code. 47 | 48 | #### `response.statusMessage` 49 | 50 | A String representing the HTTP status message. 51 | 52 | #### `response.headers` 53 | 54 | An Object representing the response HTTP headers. The `headers` object is 55 | formatted as follows: 56 | 57 | * All header names are lowercased. 58 | * Each header name produces an array-valued property on the headers object. 59 | * Each header value is pushed into the array associated with its header name. 60 | 61 | #### `response.httpVersion` 62 | 63 | A String indicating the HTTP protocol version number. Typical values are '1.0' 64 | or '1.1'. Additionally `httpVersionMajor` and `httpVersionMinor` are two 65 | Integer-valued readable properties that return respectively the HTTP major and 66 | minor version numbers. 67 | 68 | #### `response.httpVersionMajor` 69 | 70 | An Integer indicating the HTTP protocol major version number. 71 | 72 | #### `response.httpVersionMinor` 73 | 74 | An Integer indicating the HTTP protocol minor version number. 75 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/global-shortcut.md: -------------------------------------------------------------------------------- 1 | # globalShortcut 2 | 3 | > Detect keyboard events when the application does not have keyboard focus. 4 | 5 | Process: [Main](../glossary.md#main-process) 6 | 7 | The `globalShortcut` module can register/unregister a global keyboard shortcut 8 | with the operating system so that you can customize the operations for various 9 | shortcuts. 10 | 11 | **Note:** The shortcut is global; it will work even if the app does 12 | not have the keyboard focus. You should not use this module until the `ready` 13 | event of the app module is emitted. 14 | 15 | ```javascript 16 | const {app, globalShortcut} = require('electron') 17 | 18 | app.on('ready', () => { 19 | // Register a 'CommandOrControl+X' shortcut listener. 20 | const ret = globalShortcut.register('CommandOrControl+X', () => { 21 | console.log('CommandOrControl+X is pressed') 22 | }) 23 | 24 | if (!ret) { 25 | console.log('registration failed') 26 | } 27 | 28 | // Check whether a shortcut is registered. 29 | console.log(globalShortcut.isRegistered('CommandOrControl+X')) 30 | }) 31 | 32 | app.on('will-quit', () => { 33 | // Unregister a shortcut. 34 | globalShortcut.unregister('CommandOrControl+X') 35 | 36 | // Unregister all shortcuts. 37 | globalShortcut.unregisterAll() 38 | }) 39 | ``` 40 | 41 | ## Methods 42 | 43 | The `globalShortcut` module has the following methods: 44 | 45 | ### `globalShortcut.register(accelerator, callback)` 46 | 47 | * `accelerator` [Accelerator](accelerator.md) 48 | * `callback` Function 49 | 50 | Registers a global shortcut of `accelerator`. The `callback` is called when 51 | the registered shortcut is pressed by the user. 52 | 53 | When the accelerator is already taken by other applications, this call will 54 | silently fail. This behavior is intended by operating systems, since they don't 55 | want applications to fight for global shortcuts. 56 | 57 | ### `globalShortcut.isRegistered(accelerator)` 58 | 59 | * `accelerator` [Accelerator](accelerator.md) 60 | 61 | Returns `Boolean` - Whether this application has registered `accelerator`. 62 | 63 | When the accelerator is already taken by other applications, this call will 64 | still return `false`. This behavior is intended by operating systems, since they 65 | don't want applications to fight for global shortcuts. 66 | 67 | ### `globalShortcut.unregister(accelerator)` 68 | 69 | * `accelerator` [Accelerator](accelerator.md) 70 | 71 | Unregisters the global shortcut of `accelerator`. 72 | 73 | ### `globalShortcut.unregisterAll()` 74 | 75 | Unregisters all of the global shortcuts. 76 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/debugger.md: -------------------------------------------------------------------------------- 1 | ## Class: Debugger 2 | 3 | > An alternate transport for Chrome's remote debugging protocol. 4 | 5 | Process: [Main](../glossary.md#main-process) 6 | 7 | Chrome Developer Tools has a [special binding][rdp] available at JavaScript 8 | runtime that allows interacting with pages and instrumenting them. 9 | 10 | ```javascript 11 | const {BrowserWindow} = require('electron') 12 | let win = new BrowserWindow() 13 | 14 | try { 15 | win.webContents.debugger.attach('1.1') 16 | } catch (err) { 17 | console.log('Debugger attach failed : ', err) 18 | } 19 | 20 | win.webContents.debugger.on('detach', (event, reason) => { 21 | console.log('Debugger detached due to : ', reason) 22 | }) 23 | 24 | win.webContents.debugger.on('message', (event, method, params) => { 25 | if (method === 'Network.requestWillBeSent') { 26 | if (params.request.url === 'https://www.github.com') { 27 | win.webContents.debugger.detach() 28 | } 29 | } 30 | }) 31 | 32 | win.webContents.debugger.sendCommand('Network.enable') 33 | ``` 34 | 35 | ### Instance Methods 36 | 37 | #### `debugger.attach([protocolVersion])` 38 | 39 | * `protocolVersion` String (optional) - Requested debugging protocol version. 40 | 41 | Attaches the debugger to the `webContents`. 42 | 43 | #### `debugger.isAttached()` 44 | 45 | Returns `Boolean` - Whether a debugger is attached to the `webContents`. 46 | 47 | #### `debugger.detach()` 48 | 49 | Detaches the debugger from the `webContents`. 50 | 51 | #### `debugger.sendCommand(method[, commandParams, callback])` 52 | 53 | * `method` String - Method name, should be one of the methods defined by the 54 | remote debugging protocol. 55 | * `commandParams` Object (optional) - JSON object with request parameters. 56 | * `callback` Function (optional) - Response 57 | * `error` Object - Error message indicating the failure of the command. 58 | * `result` Any - Response defined by the 'returns' attribute of 59 | the command description in the remote debugging protocol. 60 | 61 | Send given command to the debugging target. 62 | 63 | ### Instance Events 64 | 65 | #### Event: 'detach' 66 | 67 | * `event` Event 68 | * `reason` String - Reason for detaching debugger. 69 | 70 | Emitted when debugging session is terminated. This happens either when 71 | `webContents` is closed or devtools is invoked for the attached `webContents`. 72 | 73 | #### Event: 'message' 74 | 75 | * `event` Event 76 | * `method` String - Method name. 77 | * `params` Object - Event parameters defined by the 'parameters' 78 | attribute in the remote debugging protocol. 79 | 80 | Emitted whenever debugging target issues instrumentation event. 81 | 82 | [rdp]: https://developer.chrome.com/devtools/docs/debugger-protocol 83 | [`webContents.findInPage`]: web-contents.md#contentsfindinpagetext-options 84 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/shell.md: -------------------------------------------------------------------------------- 1 | # shell 2 | 3 | > Manage files and URLs using their default applications. 4 | 5 | Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-process) 6 | 7 | The `shell` module provides functions related to desktop integration. 8 | 9 | An example of opening a URL in the user's default browser: 10 | 11 | ```javascript 12 | const {shell} = require('electron') 13 | 14 | shell.openExternal('https://github.com') 15 | ``` 16 | 17 | ## Methods 18 | 19 | The `shell` module has the following methods: 20 | 21 | ### `shell.showItemInFolder(fullPath)` 22 | 23 | * `fullPath` String 24 | 25 | Returns `Boolean` - Whether the item was successfully shown 26 | 27 | Show the given file in a file manager. If possible, select the file. 28 | 29 | ### `shell.openItem(fullPath)` 30 | 31 | * `fullPath` String 32 | 33 | Returns `Boolean` - Whether the item was successfully opened. 34 | 35 | Open the given file in the desktop's default manner. 36 | 37 | ### `shell.openExternal(url[, options, callback])` 38 | 39 | * `url` String 40 | * `options` Object (optional) _macOS_ 41 | * `activate` Boolean - `true` to bring the opened application to the 42 | foreground. The default is `true`. 43 | * `callback` Function (optional) - If specified will perform the open asynchronously. _macOS_ 44 | * `error` Error 45 | 46 | Returns `Boolean` - Whether an application was available to open the URL. 47 | If callback is specified, always returns true. 48 | 49 | Open the given external protocol URL in the desktop's default manner. (For 50 | example, mailto: URLs in the user's default mail agent). 51 | 52 | ### `shell.moveItemToTrash(fullPath)` 53 | 54 | * `fullPath` String 55 | 56 | Returns `Boolean` - Whether the item was successfully moved to the trash 57 | 58 | Move the given file to trash and returns a boolean status for the operation. 59 | 60 | ### `shell.beep()` 61 | 62 | Play the beep sound. 63 | 64 | ### `shell.writeShortcutLink(shortcutPath[, operation], options)` _Windows_ 65 | 66 | * `shortcutPath` String 67 | * `operation` String (optional) - Default is `create`, can be one of following: 68 | * `create` - Creates a new shortcut, overwriting if necessary. 69 | * `update` - Updates specified properties only on an existing shortcut. 70 | * `replace` - Overwrites an existing shortcut, fails if the shortcut doesn't 71 | exist. 72 | * `options` [ShortcutDetails](structures/shortcut-details.md) 73 | 74 | Returns `Boolean` - Whether the shortcut was created successfully 75 | 76 | Creates or updates a shortcut link at `shortcutPath`. 77 | 78 | ### `shell.readShortcutLink(shortcutPath)` _Windows_ 79 | 80 | * `shortcutPath` String 81 | 82 | Returns [`ShortcutDetails`](structures/shortcut-details.md) 83 | 84 | Resolves the shortcut link at `shortcutPath`. 85 | 86 | An exception will be thrown when any error happens. 87 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/desktop-capturer.md: -------------------------------------------------------------------------------- 1 | # desktopCapturer 2 | 3 | > Access information about media sources that can be used to capture audio and 4 | > video from the desktop using the [`navigator.webkitGetUserMedia`] API. 5 | 6 | Process: [Renderer](../glossary.md#renderer-process) 7 | 8 | The following example shows how to capture video from a desktop window whose 9 | title is `Electron`: 10 | 11 | ```javascript 12 | // In the renderer process. 13 | const {desktopCapturer} = require('electron') 14 | 15 | desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => { 16 | if (error) throw error 17 | for (let i = 0; i < sources.length; ++i) { 18 | if (sources[i].name === 'Electron') { 19 | navigator.webkitGetUserMedia({ 20 | audio: false, 21 | video: { 22 | mandatory: { 23 | chromeMediaSource: 'desktop', 24 | chromeMediaSourceId: sources[i].id, 25 | minWidth: 1280, 26 | maxWidth: 1280, 27 | minHeight: 720, 28 | maxHeight: 720 29 | } 30 | } 31 | }, handleStream, handleError) 32 | return 33 | } 34 | } 35 | }) 36 | 37 | function handleStream (stream) { 38 | document.querySelector('video').src = URL.createObjectURL(stream) 39 | } 40 | 41 | function handleError (e) { 42 | console.log(e) 43 | } 44 | ``` 45 | 46 | To capture video from a source provided by `desktopCapturer` the constraints 47 | passed to [`navigator.webkitGetUserMedia`] must include 48 | `chromeMediaSource: 'desktop'`, and `audio: false`. 49 | 50 | To capture both audio and video from the entire desktop the constraints passed 51 | to [`navigator.webkitGetUserMedia`] must include `chromeMediaSource: 'screen'`, 52 | and `audio: true`, but should not include a `chromeMediaSourceId` constraint. 53 | 54 | ## Methods 55 | 56 | The `desktopCapturer` module has the following methods: 57 | 58 | ### `desktopCapturer.getSources(options, callback)` 59 | 60 | * `options` Object 61 | * `types` String[] - An array of Strings that lists the types of desktop sources 62 | to be captured, available types are `screen` and `window`. 63 | * `thumbnailSize` Object (optional) - The suggested size that the media source 64 | thumbnail should be scaled to, defaults to `{width: 150, height: 150}`. 65 | * `callback` Function 66 | * `error` Error 67 | * `sources` [DesktopCapturerSource[]](structures/desktop-capturer-source.md) 68 | 69 | Starts gathering information about all available desktop media sources, 70 | and calls `callback(error, sources)` when finished. 71 | 72 | `sources` is an array of [`DesktopCapturerSource`](structures/desktop-capturer-source.md) 73 | objects, each `DesktopCapturerSource` represents a screen or an individual window that can be 74 | captured. 75 | 76 | [`navigator.webkitGetUserMedia`]: https://developer.mozilla.org/en/docs/Web/API/Navigator/getUserMedia 77 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/ipc-renderer.md: -------------------------------------------------------------------------------- 1 | # ipcRenderer 2 | 3 | > Communicate asynchronously from a renderer process to the main process. 4 | 5 | Process: [Renderer](../glossary.md#renderer-process) 6 | 7 | The `ipcRenderer` module is an instance of the 8 | [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) class. It provides a few 9 | methods so you can send synchronous and asynchronous messages from the render 10 | process (web page) to the main process. You can also receive replies from the 11 | main process. 12 | 13 | See [ipcMain](ipc-main.md) for code examples. 14 | 15 | ## Methods 16 | 17 | The `ipcRenderer` module has the following method to listen for events and send messages: 18 | 19 | ### `ipcRenderer.on(channel, listener)` 20 | 21 | * `channel` String 22 | * `listener` Function 23 | 24 | Listens to `channel`, when a new message arrives `listener` would be called with 25 | `listener(event, args...)`. 26 | 27 | ### `ipcRenderer.once(channel, listener)` 28 | 29 | * `channel` String 30 | * `listener` Function 31 | 32 | Adds a one time `listener` function for the event. This `listener` is invoked 33 | only the next time a message is sent to `channel`, after which it is removed. 34 | 35 | ### `ipcRenderer.removeListener(channel, listener)` 36 | 37 | * `channel` String 38 | * `listener` Function 39 | 40 | Removes the specified `listener` from the listener array for the specified 41 | `channel`. 42 | 43 | ### `ipcRenderer.removeAllListeners([channel])` 44 | 45 | * `channel` String (optional) 46 | 47 | Removes all listeners, or those of the specified `channel`. 48 | 49 | ### `ipcRenderer.send(channel[, arg1][, arg2][, ...])` 50 | 51 | * `channel` String 52 | * `...args` any[] 53 | 54 | Send a message to the main process asynchronously via `channel`, you can also 55 | send arbitrary arguments. Arguments will be serialized in JSON internally and 56 | hence no functions or prototype chain will be included. 57 | 58 | The main process handles it by listening for `channel` with `ipcMain` module. 59 | 60 | ### `ipcRenderer.sendSync(channel[, arg1][, arg2][, ...])` 61 | 62 | * `channel` String 63 | * `...args` any[] 64 | 65 | Send a message to the main process synchronously via `channel`, you can also 66 | send arbitrary arguments. Arguments will be serialized in JSON internally and 67 | hence no functions or prototype chain will be included. 68 | 69 | The main process handles it by listening for `channel` with `ipcMain` module, 70 | and replies by setting `event.returnValue`. 71 | 72 | **Note:** Sending a synchronous message will block the whole renderer process, 73 | unless you know what you are doing you should never use it. 74 | 75 | ### `ipcRenderer.sendToHost(channel[, arg1][, arg2][, ...])` 76 | 77 | * `channel` String 78 | * `...args` any[] 79 | 80 | Like `ipcRenderer.send` but the event will be sent to the `` element in 81 | the host page instead of the main process. 82 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/net.md: -------------------------------------------------------------------------------- 1 | # net 2 | 3 | > Issue HTTP/HTTPS requests using Chromium's native networking library 4 | 5 | Process: [Main](../glossary.md#main-process) 6 | 7 | The `net` module is a client-side API for issuing HTTP(S) requests. It is 8 | similar to the [HTTP](https://nodejs.org/api/http.html) and 9 | [HTTPS](https://nodejs.org/api/https.html) modules of Node.js but uses 10 | Chromium's native networking library instead of the Node.js implementation, 11 | offering better support for web proxies. 12 | 13 | The following is a non-exhaustive list of why you may consider using the `net` 14 | module instead of the native Node.js modules: 15 | 16 | * Automatic management of system proxy configuration, support of the wpad 17 | protocol and proxy pac configuration files. 18 | * Automatic tunneling of HTTPS requests. 19 | * Support for authenticating proxies using basic, digest, NTLM, Kerberos or 20 | negotiate authentication schemes. 21 | * Support for traffic monitoring proxies: Fiddler-like proxies used for access 22 | control and monitoring. 23 | 24 | The `net` module API has been specifically designed to mimic, as closely as 25 | possible, the familiar Node.js API. The API components including classes, 26 | methods, properties and event names are similar to those commonly used in 27 | Node.js. 28 | 29 | For instance, the following example quickly shows how the `net` API might be 30 | used: 31 | 32 | ```javascript 33 | const {app} = require('electron') 34 | app.on('ready', () => { 35 | const {net} = require('electron') 36 | const request = net.request('https://github.com') 37 | request.on('response', (response) => { 38 | console.log(`STATUS: ${response.statusCode}`) 39 | console.log(`HEADERS: ${JSON.stringify(response.headers)}`) 40 | response.on('data', (chunk) => { 41 | console.log(`BODY: ${chunk}`) 42 | }) 43 | response.on('end', () => { 44 | console.log('No more data in response.') 45 | }) 46 | }) 47 | request.end() 48 | }) 49 | ``` 50 | 51 | By the way, it is almost identical to how you would normally use the 52 | [HTTP](https://nodejs.org/api/http.html)/[HTTPS](https://nodejs.org/api/https.html) 53 | modules of Node.js 54 | 55 | The `net` API can be used only after the application emits the `ready` event. 56 | Trying to use the module before the `ready` event will throw an error. 57 | 58 | ## Methods 59 | 60 | The `net` module has the following methods: 61 | 62 | ### `net.request(options)` 63 | 64 | * `options` (Object | String) - The `ClientRequest` constructor options. 65 | 66 | Returns [`ClientRequest`](./client-request.md) 67 | 68 | Creates a [`ClientRequest`](./client-request.md) instance using the provided 69 | `options` which are directly forwarded to the `ClientRequest` constructor. 70 | The `net.request` method would be used to issue both secure and insecure HTTP 71 | requests according to the specified protocol scheme in the `options` object. 72 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/synopsis.md: -------------------------------------------------------------------------------- 1 | # Synopsis 2 | 3 | > How to use Node.js and Electron APIs. 4 | 5 | All of [Node.js's built-in modules](https://nodejs.org/api/) are available in 6 | Electron and third-party node modules also fully supported as well (including 7 | the [native modules](../tutorial/using-native-node-modules.md)). 8 | 9 | Electron also provides some extra built-in modules for developing native 10 | desktop applications. Some modules are only available in the main process, some 11 | are only available in the renderer process (web page), and some can be used in 12 | both processes. 13 | 14 | The basic rule is: if a module is [GUI][gui] or low-level system related, then 15 | it should be only available in the main process. You need to be familiar with 16 | the concept of [main process vs. renderer process](../tutorial/quick-start.md#main-process) 17 | scripts to be able to use those modules. 18 | 19 | The main process script is just like a normal Node.js script: 20 | 21 | ```javascript 22 | const {app, BrowserWindow} = require('electron') 23 | let win = null 24 | 25 | app.on('ready', () => { 26 | win = new BrowserWindow({width: 800, height: 600}) 27 | win.loadURL('https://github.com') 28 | }) 29 | ``` 30 | 31 | The renderer process is no different than a normal web page, except for the 32 | extra ability to use node modules: 33 | 34 | ```html 35 | 36 | 37 | 38 | 42 | 43 | 44 | ``` 45 | 46 | To run your app, read [Run your app](../tutorial/quick-start.md#run-your-app). 47 | 48 | ## Destructuring assignment 49 | 50 | As of 0.37, you can use 51 | [destructuring assignment][destructuring-assignment] to make it easier to use 52 | built-in modules. 53 | 54 | ```javascript 55 | const {app, BrowserWindow} = require('electron') 56 | 57 | let win 58 | 59 | app.on('ready', () => { 60 | win = new BrowserWindow() 61 | win.loadURL('https://github.com') 62 | }) 63 | ``` 64 | 65 | If you need the entire `electron` module, you can require it and then using 66 | destructuring to access the individual modules from `electron`. 67 | 68 | ```javascript 69 | const electron = require('electron') 70 | const {app, BrowserWindow} = electron 71 | 72 | let win 73 | 74 | app.on('ready', () => { 75 | win = new BrowserWindow() 76 | win.loadURL('https://github.com') 77 | }) 78 | ``` 79 | 80 | This is equivalent to the following code: 81 | 82 | ```javascript 83 | const electron = require('electron') 84 | const app = electron.app 85 | const BrowserWindow = electron.BrowserWindow 86 | let win 87 | 88 | app.on('ready', () => { 89 | win = new BrowserWindow() 90 | win.loadURL('https://github.com') 91 | }) 92 | ``` 93 | 94 | [gui]: https://en.wikipedia.org/wiki/Graphical_user_interface 95 | [destructuring-assignment]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment 96 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/environment-variables.md: -------------------------------------------------------------------------------- 1 | # Environment Variables 2 | 3 | > Control application configuration and behavior without changing code. 4 | 5 | Certain Electron behaviors are controlled by environment variables because they 6 | are initialized earlier than the command line flags and the app's code. 7 | 8 | POSIX shell example: 9 | 10 | ```bash 11 | $ export ELECTRON_ENABLE_LOGGING=true 12 | $ electron 13 | ``` 14 | 15 | Windows console example: 16 | 17 | ```powershell 18 | > set ELECTRON_ENABLE_LOGGING=true 19 | > electron 20 | ``` 21 | 22 | ## Production Variables 23 | 24 | The following environment variables are intended primarily for use at runtime 25 | in packaged Electron applications. 26 | 27 | ### `GOOGLE_API_KEY` 28 | 29 | Electron includes a hardcoded API key for making requests to Google's geocoding 30 | webservice. Because this API key is included in every version of Electron, it 31 | often exceeds its usage quota. To work around this, you can supply your own 32 | Google API key in the environment. Place the following code in your main process 33 | file, before opening any browser windows that will make geocoding requests: 34 | 35 | ```javascript 36 | process.env.GOOGLE_API_KEY = 'YOUR_KEY_HERE' 37 | ``` 38 | 39 | For instructions on how to acquire a Google API key, visit [this page](https://www.chromium.org/developers/how-tos/api-keys). 40 | 41 | By default, a newly generated Google API key may not be allowed to make 42 | geocoding requests. To enable geocoding requests, visit [this page](https://console.developers.google.com/apis/api/geolocation/overview). 43 | 44 | ### `ELECTRON_NO_ASAR` 45 | 46 | Disables ASAR support. This variable is only supported in forked child processes 47 | and spawned child processes that set `ELECTRON_RUN_AS_NODE`. 48 | 49 | ### `ELECTRON_RUN_AS_NODE` 50 | 51 | Starts the process as a normal Node.js process. 52 | 53 | ### `ELECTRON_NO_ATTACH_CONSOLE` _Windows_ 54 | 55 | Don't attach to the current console session. 56 | 57 | ### `ELECTRON_FORCE_WINDOW_MENU_BAR` _Linux_ 58 | 59 | Don't use the global menu bar on Linux. 60 | 61 | ## Development Variables 62 | 63 | The following environment variables are intended primarily for development and 64 | debugging purposes. 65 | 66 | 67 | ### `ELECTRON_ENABLE_LOGGING` 68 | 69 | Prints Chrome's internal logging to the console. 70 | 71 | ### `ELECTRON_LOG_ASAR_READS` 72 | 73 | When Electron reads from an ASAR file, log the read offset and file path to 74 | the system `tmpdir`. The resulting file can be provided to the ASAR module 75 | to optimize file ordering. 76 | 77 | ### `ELECTRON_ENABLE_STACK_DUMPING` 78 | 79 | Prints the stack trace to the console when Electron crashes. 80 | 81 | This environment variable will not work if the `crashReporter` is started. 82 | 83 | ### `ELECTRON_DEFAULT_ERROR_MODE` _Windows_ 84 | 85 | Shows the Windows's crash dialog when Electron crashes. 86 | 87 | This environment variable will not work if the `crashReporter` is started. 88 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/ipc-main.md: -------------------------------------------------------------------------------- 1 | # ipcMain 2 | 3 | > Communicate asynchronously from the main process to renderer processes. 4 | 5 | Process: [Main](../glossary.md#main-process) 6 | 7 | The `ipcMain` module is an instance of the 8 | [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) class. When used in the main 9 | process, it handles asynchronous and synchronous messages sent from a renderer 10 | process (web page). Messages sent from a renderer will be emitted to this 11 | module. 12 | 13 | ## Sending Messages 14 | 15 | It is also possible to send messages from the main process to the renderer 16 | process, see [webContents.send][web-contents-send] for more information. 17 | 18 | * When sending a message, the event name is the `channel`. 19 | * To reply a synchronous message, you need to set `event.returnValue`. 20 | * To send an asynchronous back to the sender, you can use 21 | `event.sender.send(...)`. 22 | 23 | An example of sending and handling messages between the render and main 24 | processes: 25 | 26 | ```javascript 27 | // In main process. 28 | const {ipcMain} = require('electron') 29 | ipcMain.on('asynchronous-message', (event, arg) => { 30 | console.log(arg) // prints "ping" 31 | event.sender.send('asynchronous-reply', 'pong') 32 | }) 33 | 34 | ipcMain.on('synchronous-message', (event, arg) => { 35 | console.log(arg) // prints "ping" 36 | event.returnValue = 'pong' 37 | }) 38 | ``` 39 | 40 | ```javascript 41 | // In renderer process (web page). 42 | const {ipcRenderer} = require('electron') 43 | console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // prints "pong" 44 | 45 | ipcRenderer.on('asynchronous-reply', (event, arg) => { 46 | console.log(arg) // prints "pong" 47 | }) 48 | ipcRenderer.send('asynchronous-message', 'ping') 49 | ``` 50 | 51 | ## Methods 52 | 53 | The `ipcMain` module has the following method to listen for events: 54 | 55 | ### `ipcMain.on(channel, listener)` 56 | 57 | * `channel` String 58 | * `listener` Function 59 | 60 | Listens to `channel`, when a new message arrives `listener` would be called with 61 | `listener(event, args...)`. 62 | 63 | ### `ipcMain.once(channel, listener)` 64 | 65 | * `channel` String 66 | * `listener` Function 67 | 68 | Adds a one time `listener` function for the event. This `listener` is invoked 69 | only the next time a message is sent to `channel`, after which it is removed. 70 | 71 | ### `ipcMain.removeListener(channel, listener)` 72 | 73 | * `channel` String 74 | * `listener` Function 75 | 76 | Removes the specified `listener` from the listener array for the specified 77 | `channel`. 78 | 79 | ### `ipcMain.removeAllListeners([channel])` 80 | 81 | * `channel` String (optional) 82 | 83 | Removes all listeners, or those of the specified `channel`. 84 | 85 | ## Event object 86 | 87 | The `event` object passed to the `callback` has the following methods: 88 | 89 | ### `event.returnValue` 90 | 91 | Set this to the value to be returned in a synchronous message. 92 | 93 | ### `event.sender` 94 | 95 | Returns the `webContents` that sent the message, you can call 96 | `event.sender.send` to reply to the asynchronous message, see 97 | [webContents.send][web-contents-send] for more information. 98 | 99 | [web-contents-send]: web-contents.md#webcontentssendchannel-arg1-arg2- 100 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/screen.md: -------------------------------------------------------------------------------- 1 | # screen 2 | 3 | > Retrieve information about screen size, displays, cursor position, etc. 4 | 5 | Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-process) 6 | 7 | You cannot require or use this module until the `ready` event of the `app` 8 | module is emitted. 9 | 10 | `screen` is an [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter). 11 | 12 | **Note:** In the renderer / DevTools, `window.screen` is a reserved DOM 13 | property, so writing `let {screen} = require('electron')` will not work. 14 | 15 | An example of creating a window that fills the whole screen: 16 | 17 | ```javascript 18 | const electron = require('electron') 19 | const {app, BrowserWindow} = electron 20 | 21 | let win 22 | 23 | app.on('ready', () => { 24 | const {width, height} = electron.screen.getPrimaryDisplay().workAreaSize 25 | win = new BrowserWindow({width, height}) 26 | win.loadURL('https://github.com') 27 | }) 28 | ``` 29 | 30 | Another example of creating a window in the external display: 31 | 32 | ```javascript 33 | const electron = require('electron') 34 | const {app, BrowserWindow} = require('electron') 35 | 36 | let win 37 | 38 | app.on('ready', () => { 39 | let displays = electron.screen.getAllDisplays() 40 | let externalDisplay = displays.find((display) => { 41 | return display.bounds.x !== 0 || display.bounds.y !== 0 42 | }) 43 | 44 | if (externalDisplay) { 45 | win = new BrowserWindow({ 46 | x: externalDisplay.bounds.x + 50, 47 | y: externalDisplay.bounds.y + 50 48 | }) 49 | win.loadURL('https://github.com') 50 | } 51 | }) 52 | ``` 53 | 54 | ## Events 55 | 56 | The `screen` module emits the following events: 57 | 58 | ### Event: 'display-added' 59 | 60 | Returns: 61 | 62 | * `event` Event 63 | * `newDisplay` [Display](structures/display.md) 64 | 65 | Emitted when `newDisplay` has been added. 66 | 67 | ### Event: 'display-removed' 68 | 69 | Returns: 70 | 71 | * `event` Event 72 | * `oldDisplay` [Display](structures/display.md) 73 | 74 | Emitted when `oldDisplay` has been removed. 75 | 76 | ### Event: 'display-metrics-changed' 77 | 78 | Returns: 79 | 80 | * `event` Event 81 | * `display` [Display](structures/display.md) 82 | * `changedMetrics` String[] 83 | 84 | Emitted when one or more metrics change in a `display`. The `changedMetrics` is 85 | an array of strings that describe the changes. Possible changes are `bounds`, 86 | `workArea`, `scaleFactor` and `rotation`. 87 | 88 | ## Methods 89 | 90 | The `screen` module has the following methods: 91 | 92 | ### `screen.getCursorScreenPoint()` 93 | 94 | Returns `Object`: 95 | 96 | * `x` Promise 97 | * `y` Integer 98 | 99 | The current absolute position of the mouse pointer. 100 | 101 | ### `screen.getPrimaryDisplay()` 102 | 103 | Returns [`Display`](structures/display.md) - The primary display. 104 | 105 | ### `screen.getAllDisplays()` 106 | 107 | Returns [`Display[]`](structures/display.md) - An array of displays that are currently available. 108 | 109 | ### `screen.getDisplayNearestPoint(point)` 110 | 111 | * `point` Object 112 | * `x` Integer 113 | * `y` Integer 114 | 115 | Returns [`Display`](structures/display.md) - The display nearest the specified point. 116 | 117 | ### `screen.getDisplayMatching(rect)` 118 | 119 | * `rect` [Rectangle](structures/rectangle.md) 120 | 121 | Returns [`Display`](structures/display.md) - The display that most closely 122 | intersects the provided bounds. 123 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/touch-bar.md: -------------------------------------------------------------------------------- 1 | ## Class: TouchBar 2 | 3 | > Create TouchBar layouts for native macOS applications 4 | 5 | Process: [Main](../tutorial/quick-start.md#main-process) 6 | 7 | ### `new TouchBar(items)` _Experimental_ 8 | 9 | * `items` ([TouchBarButton](touch-bar-button.md) | [TouchBarColorPicker](touch-bar-color-picker.md) | [TouchBarGroup](touch-bar-group.md) | [TouchBarLabel](touch-bar-label.md) | [TouchBarPopover](touch-bar-popover.md) | [TouchBarSlider](touch-bar-slider.md) | [TouchBarSpacer](touch-bar-spacer.md))[] 10 | 11 | Creates a new touch bar with the specified items. Use 12 | `BrowserWindow.setTouchBar` to add the `TouchBar` to a window. 13 | 14 | **Note:** The TouchBar API is currently experimental and may change or be 15 | removed in future Electron releases. 16 | 17 | ## Examples 18 | 19 | Below is an example of a simple slot machine touch bar game with a button 20 | and some labels. 21 | 22 | ```javascript 23 | const {app, BrowserWindow, TouchBar} = require('electron') 24 | 25 | const {TouchBarLabel, TouchBarButton, TouchBarSpacer} = TouchBar 26 | 27 | let spinning = false 28 | 29 | // Reel labels 30 | const reel1 = new TouchBarLabel() 31 | const reel2 = new TouchBarLabel() 32 | const reel3 = new TouchBarLabel() 33 | 34 | // Spin result label 35 | const result = new TouchBarLabel() 36 | 37 | // Spin button 38 | const spin = new TouchBarButton({ 39 | label: '🎰 Spin', 40 | backgroundColor: '#7851A9', 41 | click: () => { 42 | // Ignore clicks if already spinning 43 | if (spinning) { 44 | return 45 | } 46 | 47 | spinning = true 48 | result.label = '' 49 | 50 | let timeout = 10 51 | const spinLength = 4 * 1000 // 4 seconds 52 | const startTime = Date.now() 53 | 54 | const spinReels = () => { 55 | updateReels() 56 | 57 | if ((Date.now() - startTime) >= spinLength) { 58 | finishSpin() 59 | } else { 60 | // Slow down a bit on each spin 61 | timeout *= 1.1 62 | setTimeout(spinReels, timeout) 63 | } 64 | } 65 | 66 | spinReels() 67 | } 68 | }) 69 | 70 | const getRandomValue = () => { 71 | const values = ['🍒', '💎', '7️⃣', '🍊', '🔔', '⭐', '🍇', '🍀'] 72 | return values[Math.floor(Math.random() * values.length)] 73 | } 74 | 75 | const updateReels = () => { 76 | reel1.label = getRandomValue() 77 | reel2.label = getRandomValue() 78 | reel3.label = getRandomValue() 79 | } 80 | 81 | const finishSpin = () => { 82 | const uniqueValues = new Set([reel1.label, reel2.label, reel3.label]).size 83 | if (uniqueValues === 1) { 84 | // All 3 values are the same 85 | result.label = '💰 Jackpot!' 86 | result.textColor = '#FDFF00' 87 | } else if (uniqueValues === 2) { 88 | // 2 values are the same 89 | result.label = '😍 Winner!' 90 | result.textColor = '#FDFF00' 91 | } else { 92 | // No values are the same 93 | result.label = '🙁 Spin Again' 94 | result.textColor = null 95 | } 96 | spinning = false 97 | } 98 | 99 | const touchBar = new TouchBar([ 100 | spin, 101 | new TouchBarSpacer({size: 'large'}), 102 | reel1, 103 | new TouchBarSpacer({size: 'small'}), 104 | reel2, 105 | new TouchBarSpacer({size: 'small'}), 106 | reel3, 107 | new TouchBarSpacer({size: 'large'}), 108 | result 109 | ]) 110 | 111 | let window 112 | 113 | app.once('ready', () => { 114 | window = new BrowserWindow({ 115 | frame: false, 116 | titleBarStyle: 'hidden-inset', 117 | width: 200, 118 | height: 200, 119 | backgroundColor: '#000' 120 | }) 121 | window.loadURL('about:blank') 122 | window.setTouchBar(touchBar) 123 | }) 124 | ``` 125 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/process.md: -------------------------------------------------------------------------------- 1 | # process 2 | 3 | > Extensions to process object. 4 | 5 | Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-process) 6 | 7 | Electron's `process` object is extended from the 8 | [Node.js `process` object](https://nodejs.org/api/process.html). 9 | It adds the following events, properties, and methods: 10 | 11 | ## Events 12 | 13 | ### Event: 'loaded' 14 | 15 | Emitted when Electron has loaded its internal initialization script and is 16 | beginning to load the web page or the main script. 17 | 18 | It can be used by the preload script to add removed Node global symbols back to 19 | the global scope when node integration is turned off: 20 | 21 | ```javascript 22 | // preload.js 23 | const _setImmediate = setImmediate 24 | const _clearImmediate = clearImmediate 25 | process.once('loaded', () => { 26 | global.setImmediate = _setImmediate 27 | global.clearImmediate = _clearImmediate 28 | }) 29 | ``` 30 | 31 | ## Properties 32 | 33 | ### `process.noAsar` 34 | 35 | Setting this to `true` can disable the support for `asar` archives in Node's 36 | built-in modules. 37 | 38 | ### `process.type` 39 | 40 | Current process's type, can be `"browser"` (i.e. main process) or `"renderer"`. 41 | 42 | ### `process.versions.electron` 43 | 44 | Electron's version string. 45 | 46 | ### `process.versions.chrome` 47 | 48 | Chrome's version string. 49 | 50 | ### `process.resourcesPath` 51 | 52 | Path to the resources directory. 53 | 54 | ### `process.mas` 55 | 56 | For Mac App Store build, this property is `true`, for other builds it is 57 | `undefined`. 58 | 59 | ### `process.windowsStore` 60 | 61 | If the app is running as a Windows Store app (appx), this property is `true`, 62 | for otherwise it is `undefined`. 63 | 64 | ### `process.defaultApp` 65 | 66 | When app is started by being passed as parameter to the default app, this 67 | property is `true` in the main process, otherwise it is `undefined`. 68 | 69 | ## Methods 70 | 71 | The `process` object has the following method: 72 | 73 | ### `process.crash()` 74 | 75 | Causes the main thread of the current process crash. 76 | 77 | ### `process.hang()` 78 | 79 | Causes the main thread of the current process hang. 80 | 81 | ### `process.setFdLimit(maxDescriptors)` _macOS_ _Linux_ 82 | 83 | * `maxDescriptors` Integer 84 | 85 | Sets the file descriptor soft limit to `maxDescriptors` or the OS hard 86 | limit, whichever is lower for the current process. 87 | 88 | ### `process.getProcessMemoryInfo()` 89 | 90 | Returns `Object`: 91 | 92 | * `workingSetSize` Integer - The amount of memory currently pinned to actual physical 93 | RAM. 94 | * `peakWorkingSetSize` Integer - The maximum amount of memory that has ever been pinned 95 | to actual physical RAM. 96 | * `privateBytes` Integer - The amount of memory not shared by other processes, such as 97 | JS heap or HTML content. 98 | * `sharedBytes` Integer - The amount of memory shared between processes, typically 99 | memory consumed by the Electron code itself 100 | 101 | Returns an object giving memory usage statistics about the current process. Note 102 | that all statistics are reported in Kilobytes. 103 | 104 | ### `process.getSystemMemoryInfo()` 105 | 106 | Returns `Object`: 107 | 108 | * `total` Integer - The total amount of physical memory in Kilobytes available to the 109 | system. 110 | * `free` Integer - The total amount of memory not being used by applications or disk 111 | cache. 112 | * `swapTotal` Integer - The total amount of swap memory in Kilobytes available to the 113 | system. _Windows_ _Linux_ 114 | * `swapFree` Integer - The free amount of swap memory in Kilobytes available to the 115 | system. _Windows_ _Linux_ 116 | 117 | Returns an object giving memory usage statistics about the entire system. Note 118 | that all statistics are reported in Kilobytes. 119 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/locales.md: -------------------------------------------------------------------------------- 1 | # Locales 2 | 3 | > Locale values returned by `app.getLocale()`. 4 | 5 | Electron uses Chromium's `l10n_util` library to fetch the locale. Possible 6 | values are listed below: 7 | 8 | | Language Code | Language Name | 9 | |---------------|---------------| 10 | | af | Afrikaans | 11 | | an | Aragonese | 12 | | ar-AE | Arabic (U.A.E.) | 13 | | ar-IQ | Arabic (Iraq) | 14 | | ar | Arabic (Standard) | 15 | | ar-BH | Arabic (Bahrain) | 16 | | ar-DZ | Arabic (Algeria) | 17 | | ar-EG | Arabic (Egypt) | 18 | | ar-JO | Arabic (Jordan) | 19 | | ar-KW | Arabic (Kuwait) | 20 | | ar-LB | Arabic (Lebanon) | 21 | | ar-LY | Arabic (Libya) | 22 | | ar-MA | Arabic (Morocco) | 23 | | ar-OM | Arabic (Oman) | 24 | | ar-QA | Arabic (Qatar) | 25 | | ar-SA | Arabic (Saudi Arabia) | 26 | | ar-SY | Arabic (Syria) | 27 | | ar-TN | Arabic (Tunisia) | 28 | | ar-YE | Arabic (Yemen) | 29 | | as | Assamese | 30 | | ast | Asturian | 31 | | az | Azerbaijani | 32 | | be | Belarusian | 33 | | bg | Bulgarian | 34 | | bg | Bulgarian | 35 | | bn | Bengali | 36 | | br | Breton | 37 | | bs | Bosnian | 38 | | ca | Catalan | 39 | | ce | Chechen | 40 | | ch | Chamorro | 41 | | co | Corsican | 42 | | cr | Cree | 43 | | cs | Czech | 44 | | cv | Chuvash | 45 | | da | Danish | 46 | | de | German (Standard) | 47 | | de-AT | German (Austria) | 48 | | de-CH | German (Switzerland) | 49 | | de-DE | German (Germany) | 50 | | de-LI | German (Liechtenstein) | 51 | | de-LU | German (Luxembourg) | 52 | | el | Greek | 53 | | en-AU | English (Australia) | 54 | | en-BZ | English (Belize) | 55 | | en | English | 56 | | en-CA | English (Canada) | 57 | | en-GB | English (United Kingdom) | 58 | | en-IE | English (Ireland) | 59 | | en-JM | English (Jamaica) | 60 | | en-NZ | English (New Zealand) | 61 | | en-PH | English (Philippines) | 62 | | en-TT | English (Trinidad & Tobago) | 63 | | en-US | English (United States) | 64 | | en-ZA | English (South Africa) | 65 | | en-ZW | English (Zimbabwe) | 66 | | eo | Esperanto | 67 | | et | Estonian | 68 | | eu | Basque | 69 | | fa | Persian | 70 | | fa | Farsi | 71 | | fa-IR | Persian/Iran | 72 | | fi | Finnish | 73 | | fj | Fijian | 74 | | fo | Faeroese | 75 | | fr-CH | French (Switzerland) | 76 | | fr-FR | French (France) | 77 | | fr-LU | French (Luxembourg) | 78 | | fr-MC | French (Monaco) | 79 | | fr | French (Standard) | 80 | | fr-BE | French (Belgium) | 81 | | fr-CA | French (Canada) | 82 | | fur | Friulian | 83 | | fy | Frisian | 84 | | ga | Irish | 85 | | gd-IE | Gaelic (Irish) | 86 | | gd | Gaelic (Scots) | 87 | | gl | Galacian | 88 | | gu | Gujurati | 89 | | he | Hebrew | 90 | | hi | Hindi | 91 | | hr | Croatian | 92 | | ht | Haitian | 93 | | hu | Hungarian | 94 | | hy | Armenian | 95 | | id | Indonesian | 96 | | is | Icelandic | 97 | | it-CH | Italian (Switzerland) | 98 | | it | Italian (Standard) | 99 | | iu | Inuktitut | 100 | | ja | Japanese | 101 | | ka | Georgian | 102 | | kk | Kazakh | 103 | | km | Khmer | 104 | | kn | Kannada | 105 | | ko | Korean | 106 | | ko-KP | Korean (North Korea) | 107 | | ko-KR | Korean (South Korea) | 108 | | ks | Kashmiri | 109 | | ky | Kirghiz | 110 | | la | Latin | 111 | | lb | Luxembourgish | 112 | | lt | Lithuanian | 113 | | lv | Latvian | 114 | | mi | Maori | 115 | | mk | FYRO Macedonian | 116 | | ml | Malayalam | 117 | | mo | Moldavian | 118 | | mr | Marathi | 119 | | ms | Malay | 120 | | mt | Maltese | 121 | | my | Burmese | 122 | | nb | Norwegian (Bokmal) | 123 | | ne | Nepali | 124 | | ng | Ndonga | 125 | | nl | Dutch (Standard) | 126 | | nl-BE | Dutch (Belgian) | 127 | | nn | Norwegian (Nynorsk) | 128 | | no | Norwegian | 129 | | nv | Navajo | 130 | | oc | Occitan | 131 | | om | Oromo | 132 | | or | Oriya | 133 | | sq | Albanian | 134 | | tlh | Klingon | 135 | | zh-TW | Chinese (Taiwan) | 136 | | zh | Chinese | 137 | | zh-CN | Chinese (PRC) | 138 | | zh-HK | Chinese (Hong Kong) | 139 | | zh-SG | Chinese (Singapore) | 140 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | const API = require('./lib/api') 3 | const fetchDocs = require('electron-docs') 4 | const promisify = require('pify') 5 | const semver = require('semver') 6 | const exists = require('path-exists').sync 7 | const keyedArray = require('keyed-array') 8 | 9 | function remapTouchBar (apis) { 10 | const newApis = [] 11 | const touchBarApis = [] 12 | var touchBarApi 13 | apis.forEach((api) => { 14 | if (api.name.substr(0, 8) === 'TouchBar' && api.name !== 'TouchBar') { 15 | touchBarApis.push(api) 16 | } else if (api.name === 'TouchBar') { 17 | touchBarApi = api 18 | newApis.push(touchBarApi) 19 | } else { 20 | newApis.push(api) 21 | } 22 | }) 23 | if (touchBarApi) touchBarApi.staticProperties = touchBarApis 24 | return newApis 25 | } 26 | 27 | function lint (docsPath, targetVersion, callback) { 28 | if (typeof callback !== 'function') { 29 | throw new TypeError('Expected a callback function as third argument') 30 | } 31 | 32 | if (!semver.valid(targetVersion)) { 33 | throw new TypeError(`\`targetVersion\` must be a valid version number. Got: ${targetVersion}`) 34 | } 35 | 36 | if (!exists(docsPath)) { 37 | throw new TypeError(`\`path\` must be an existing path on the filesystem. Got: ${docsPath}`) 38 | } 39 | 40 | // traverse into docs directory if given the electron repo path 41 | if (path.basename(docsPath) === 'electron') { 42 | docsPath = path.join(docsPath, 'docs') 43 | } 44 | 45 | return fetchDocs(docsPath) 46 | .then(function (docs) { 47 | const seeds = deriveSeeds(docs) 48 | var apis = seeds.map(seed => { 49 | seed.version = targetVersion 50 | return new API(seed, docs) 51 | }) 52 | 53 | apis = remapTouchBar(apis) 54 | 55 | // Attach named keys to collection arrays for easier access 56 | // apis.app.events.login 57 | // apis.app.methods.quit 58 | // apis.BrowserWindow.instanceMethods.isFocused 59 | apis = keyedArray(apis) 60 | 61 | return callback(null, apis) 62 | }) 63 | .catch(function (err) { 64 | console.error(err) 65 | return callback(err) 66 | }) 67 | } 68 | 69 | function deriveSeeds (docs) { 70 | const seeds = [] 71 | 72 | docs 73 | // Ignore files that aren't real APIs or data structures 74 | // TODO: remove this if we ever move the non-API files out of the api dir 75 | .filter(doc => doc.markdown_content.match(/^Process: \[/m) || doc.filename.match('structures')) 76 | .forEach(doc => { 77 | // H1 headings define modules and structures 78 | const moduleHeading = /^# (.*)/ 79 | const moduleHeadingMatch = doc.markdown_content.match(moduleHeading) 80 | if (moduleHeadingMatch) { 81 | var name = moduleHeadingMatch[1].replace(/ Object/, '').replace(/ extends .+/, '') 82 | 83 | // Special case for ' Tag' heading 84 | if (name.match(/webview/i)) name = 'webviewTag' 85 | 86 | seeds.push({ 87 | name: name, 88 | moduleLevelHeading: moduleHeadingMatch[1], 89 | structure: !!doc.filename.match('structures') 90 | }) 91 | } 92 | 93 | // H2 headings define classes 94 | // TODO: revise/simplify this if we ever change class headings from ## to # 95 | const classHeading = /^## Class: (.*)/m 96 | const classHeadingMatch = doc.markdown_content.match(classHeading) 97 | if (classHeadingMatch && !(moduleHeadingMatch && moduleHeadingMatch[1] === classHeadingMatch[1])) { 98 | // Only add seed if it's not a duplicate, 99 | // e.g. `web-contents` has `# WebContents` and `## Class: WebContents` 100 | seeds.push({ 101 | name: classHeadingMatch[1], 102 | structure: false 103 | }) 104 | } 105 | }) 106 | 107 | return seeds 108 | .sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase())) 109 | } 110 | 111 | module.exports = promisify(lint) 112 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/cookies.md: -------------------------------------------------------------------------------- 1 | ## Class: Cookies 2 | 3 | > Query and modify a session's cookies. 4 | 5 | Process: [Main](../glossary.md#main-process) 6 | 7 | Instances of the `Cookies` class are accessed by using `cookies` property of 8 | a `Session`. 9 | 10 | For example: 11 | 12 | ```javascript 13 | const {session} = require('electron') 14 | 15 | // Query all cookies. 16 | session.defaultSession.cookies.get({}, (error, cookies) => { 17 | console.log(error, cookies) 18 | }) 19 | 20 | // Query all cookies associated with a specific url. 21 | session.defaultSession.cookies.get({url: 'http://www.github.com'}, (error, cookies) => { 22 | console.log(error, cookies) 23 | }) 24 | 25 | // Set a cookie with the given cookie data; 26 | // may overwrite equivalent cookies if they exist. 27 | const cookie = {url: 'http://www.github.com', name: 'dummy_name', value: 'dummy'} 28 | session.defaultSession.cookies.set(cookie, (error) => { 29 | if (error) console.error(error) 30 | }) 31 | ``` 32 | 33 | ### Instance Events 34 | 35 | The following events are available on instances of `Cookies`: 36 | 37 | #### Event: 'changed' 38 | 39 | * `event` Event 40 | * `cookie` [Cookie](structures/cookie.md) - The cookie that was changed 41 | * `cause` String - The cause of the change with one of the following values: 42 | * `explicit` - The cookie was changed directly by a consumer's action. 43 | * `overwrite` - The cookie was automatically removed due to an insert 44 | operation that overwrote it. 45 | * `expired` - The cookie was automatically removed as it expired. 46 | * `evicted` - The cookie was automatically evicted during garbage collection. 47 | * `expired-overwrite` - The cookie was overwritten with an already-expired 48 | expiration date. 49 | * `removed` Boolean - `true` if the cookie was removed, `false` otherwise. 50 | 51 | Emitted when a cookie is changed because it was added, edited, removed, or 52 | expired. 53 | 54 | ### Instance Methods 55 | 56 | The following methods are available on instances of `Cookies`: 57 | 58 | #### `cookies.get(filter, callback)` 59 | 60 | * `filter` Object 61 | * `url` String (optional) - Retrieves cookies which are associated with 62 | `url`. Empty implies retrieving cookies of all urls. 63 | * `name` String (optional) - Filters cookies by name. 64 | * `domain` String (optional) - Retrieves cookies whose domains match or are 65 | subdomains of `domains` 66 | * `path` String (optional) - Retrieves cookies whose path matches `path`. 67 | * `secure` Boolean (optional) - Filters cookies by their Secure property. 68 | * `session` Boolean (optional) - Filters out session or persistent cookies. 69 | * `callback` Function 70 | * `error` Error 71 | * `cookies` Cookies[] 72 | 73 | Sends a request to get all cookies matching `details`, `callback` will be called 74 | with `callback(error, cookies)` on complete. 75 | 76 | `cookies` is an Array of [`cookie`](structures/cookie.md) objects. 77 | 78 | #### `cookies.set(details, callback)` 79 | 80 | * `details` Object 81 | * `url` String - The url to associate the cookie with. 82 | * `name` String (optional) - The name of the cookie. Empty by default if omitted. 83 | * `value` String (optional) - The value of the cookie. Empty by default if omitted. 84 | * `domain` String (optional) - The domain of the cookie. Empty by default if omitted. 85 | * `path` String (optional) - The path of the cookie. Empty by default if omitted. 86 | * `secure` Boolean (optional) - Whether the cookie should be marked as Secure. Defaults to 87 | false. 88 | * `httpOnly` Boolean (optional) - Whether the cookie should be marked as HTTP only. 89 | Defaults to false. 90 | * `expirationDate` Double (optional) - The expiration date of the cookie as the number of 91 | seconds since the UNIX epoch. If omitted then the cookie becomes a session 92 | cookie and will not be retained between sessions. 93 | * `callback` Function 94 | * `error` Error 95 | 96 | Sets a cookie with `details`, `callback` will be called with `callback(error)` 97 | on complete. 98 | 99 | #### `cookies.remove(url, name, callback)` 100 | 101 | * `url` String - The URL associated with the cookie. 102 | * `name` String - The name of cookie to remove. 103 | * `callback` Function 104 | 105 | Removes the cookies matching `url` and `name`, `callback` will called with 106 | `callback()` on complete. 107 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/menu-item.md: -------------------------------------------------------------------------------- 1 | ## Class: MenuItem 2 | 3 | > Add items to native application menus and context menus. 4 | 5 | Process: [Main](../glossary.md#main-process) 6 | 7 | See [`Menu`](menu.md) for examples. 8 | 9 | ### `new MenuItem(options)` 10 | 11 | * `options` Object 12 | * `click` Function (optional) - Will be called with 13 | `click(menuItem, browserWindow, event)` when the menu item is clicked. 14 | * `menuItem` MenuItem 15 | * `browserWindow` BrowserWindow 16 | * `event` Event 17 | * `role` String (optional) - Define the action of the menu item, when specified the 18 | `click` property will be ignored. 19 | * `type` String (optional) - Can be `normal`, `separator`, `submenu`, `checkbox` or 20 | `radio`. 21 | * `label` String - (optional) 22 | * `sublabel` String - (optional) 23 | * `accelerator` [Accelerator](accelerator.md) (optional) 24 | * `icon` ([NativeImage](native-image.md) | String) (optional) 25 | * `enabled` Boolean (optional) - If false, the menu item will be greyed out and 26 | unclickable. 27 | * `visible` Boolean (optional) - If false, the menu item will be entirely hidden. 28 | * `checked` Boolean (optional) - Should only be specified for `checkbox` or `radio` type 29 | menu items. 30 | * `submenu` (MenuItemConstructorOptions[] | Menu) (optional) - Should be specified for `submenu` type menu items. If 31 | `submenu` is specified, the `type: 'submenu'` can be omitted. If the value 32 | is not a `Menu` then it will be automatically converted to one using 33 | `Menu.buildFromTemplate`. 34 | * `id` String (optional) - Unique within a single menu. If defined then it can be used 35 | as a reference to this item by the position attribute. 36 | * `position` String (optional) - This field allows fine-grained definition of the 37 | specific location within a given menu. 38 | 39 | It is best to specify `role` for any menu item that matches a standard role, 40 | rather than trying to manually implement the behavior in a `click` function. 41 | The built-in `role` behavior will give the best native experience. 42 | 43 | The `label` and `accelerator` are optional when using a `role` and will default 44 | to appropriate values for each platform. 45 | 46 | The `role` property can have following values: 47 | 48 | * `undo` 49 | * `redo` 50 | * `cut` 51 | * `copy` 52 | * `paste` 53 | * `pasteandmatchstyle` 54 | * `selectall` 55 | * `delete` 56 | * `minimize` - Minimize current window 57 | * `close` - Close current window 58 | * `quit`- Quit the application 59 | * `reload` - Reload the current window 60 | * `forcereload` - Reload the current window ignoring the cache. 61 | * `toggledevtools` - Toggle developer tools in the current window 62 | * `togglefullscreen`- Toggle full screen mode on the current window 63 | * `resetzoom` - Reset the focused page's zoom level to the original size 64 | * `zoomin` - Zoom in the focused page by 10% 65 | * `zoomout` - Zoom out the focused page by 10% 66 | 67 | On macOS `role` can also have following additional values: 68 | 69 | * `about` - Map to the `orderFrontStandardAboutPanel` action 70 | * `hide` - Map to the `hide` action 71 | * `hideothers` - Map to the `hideOtherApplications` action 72 | * `unhide` - Map to the `unhideAllApplications` action 73 | * `startspeaking` - Map to the `startSpeaking` action 74 | * `stopspeaking` - Map to the `stopSpeaking` action 75 | * `front` - Map to the `arrangeInFront` action 76 | * `zoom` - Map to the `performZoom` action 77 | * `window` - The submenu is a "Window" menu 78 | * `help` - The submenu is a "Help" menu 79 | * `services` - The submenu is a "Services" menu 80 | 81 | When specifying `role` on macOS, `label` and `accelerator` are the only options 82 | that will affect the MenuItem. All other options will be ignored. 83 | 84 | ### Instance Properties 85 | 86 | The following properties are available on instances of `MenuItem`: 87 | 88 | #### `menuItem.enabled` 89 | 90 | A Boolean indicating whether the item is enabled, this property can be 91 | dynamically changed. 92 | 93 | #### `menuItem.visible` 94 | 95 | A Boolean indicating whether the item is visible, this property can be 96 | dynamically changed. 97 | 98 | #### `menuItem.checked` 99 | 100 | A Boolean indicating whether the item is checked, this property can be 101 | dynamically changed. 102 | 103 | A `checkbox` menu item will toggle the `checked` property on and off when 104 | selected. 105 | 106 | A `radio` menu item will turn on its `checked` property when clicked, and 107 | will turn off that property for all adjacent items in the same menu. 108 | 109 | You can add a `click` function for additional behavior. 110 | 111 | #### `menuItem.label` 112 | 113 | A String representing the menu items visible label 114 | 115 | #### `menuItem.click` 116 | 117 | A Function that is fired when the MenuItem receives a click event 118 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/clipboard.md: -------------------------------------------------------------------------------- 1 | # clipboard 2 | 3 | > Perform copy and paste operations on the system clipboard. 4 | 5 | Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-process) 6 | 7 | The following example shows how to write a string to the clipboard: 8 | 9 | ```javascript 10 | const {clipboard} = require('electron') 11 | clipboard.writeText('Example String') 12 | ``` 13 | 14 | On X Window systems, there is also a selection clipboard. To manipulate it 15 | you need to pass `selection` to each method: 16 | 17 | ```javascript 18 | const {clipboard} = require('electron') 19 | clipboard.writeText('Example String', 'selection') 20 | console.log(clipboard.readText('selection')) 21 | ``` 22 | 23 | ## Methods 24 | 25 | The `clipboard` module has the following methods: 26 | 27 | **Note:** Experimental APIs are marked as such and could be removed in future. 28 | 29 | ### `clipboard.readText([type])` 30 | 31 | * `type` String (optional) 32 | 33 | Returns `String` - The content in the clipboard as plain text. 34 | 35 | ### `clipboard.writeText(text[, type])` 36 | 37 | * `text` String 38 | * `type` String (optional) 39 | 40 | Writes the `text` into the clipboard as plain text. 41 | 42 | ### `clipboard.readHTML([type])` 43 | 44 | * `type` String (optional) 45 | 46 | Returns `String` - The content in the clipboard as markup. 47 | 48 | ### `clipboard.writeHTML(markup[, type])` 49 | 50 | * `markup` String 51 | * `type` String (optional) 52 | 53 | Writes `markup` to the clipboard. 54 | 55 | ### `clipboard.readImage([type])` 56 | 57 | * `type` String (optional) 58 | 59 | Returns [`NativeImage`](native-image.md) - The image content in the clipboard. 60 | 61 | ### `clipboard.writeImage(image[, type])` 62 | 63 | * `image` [NativeImage](native-image.md) 64 | * `type` String (optional) 65 | 66 | Writes `image` to the clipboard. 67 | 68 | ### `clipboard.readRTF([type])` 69 | 70 | * `type` String (optional) 71 | 72 | Returns `String` - The content in the clipboard as RTF. 73 | 74 | ### `clipboard.writeRTF(text[, type])` 75 | 76 | * `text` String 77 | * `type` String (optional) 78 | 79 | Writes the `text` into the clipboard in RTF. 80 | 81 | ### `clipboard.readBookmark()` _macOS_ _Windows_ 82 | 83 | Returns `Object`: 84 | 85 | * `title` String 86 | * `url` String 87 | 88 | Returns an Object containing `title` and `url` keys representing the bookmark in 89 | the clipboard. The `title` and `url` values will be empty strings when the 90 | bookmark is unavailable. 91 | 92 | ### `clipboard.writeBookmark(title, url[, type])` _macOS_ _Windows_ 93 | 94 | * `title` String 95 | * `url` String 96 | * `type` String (optional) 97 | 98 | Writes the `title` and `url` into the clipboard as a bookmark. 99 | 100 | **Note:** Most apps on Windows don't support pasting bookmarks into them so 101 | you can use `clipboard.write` to write both a bookmark and fallback text to the 102 | clipboard. 103 | 104 | ```js 105 | clipboard.write({ 106 | text: 'http://electronjs.org', 107 | bookmark: 'Electron Homepage' 108 | }) 109 | ``` 110 | 111 | ### `clipboard.readFindText()` _macOS_ 112 | 113 | Returns `String` - The text on the find pasteboard. This method uses synchronous 114 | IPC when called from the renderer process. The cached value is reread from the 115 | find pasteboard whenever the application is activated. 116 | 117 | ### `clipboard.writeFindText(text)` _macOS_ 118 | 119 | * `text` String 120 | 121 | Writes the `text` into the find pasteboard as plain text. This method uses 122 | synchronous IPC when called from the renderer process. 123 | 124 | ### `clipboard.clear([type])` 125 | 126 | * `type` String (optional) 127 | 128 | Clears the clipboard content. 129 | 130 | ### `clipboard.availableFormats([type])` 131 | 132 | * `type` String (optional) 133 | 134 | Returns `String[]` - An array of supported formats for the clipboard `type`. 135 | 136 | ### `clipboard.has(data[, type])` _Experimental_ 137 | 138 | * `data` String 139 | * `type` String (optional) 140 | 141 | Returns `Boolean` - Whether the clipboard supports the format of specified `data`. 142 | 143 | ```javascript 144 | const {clipboard} = require('electron') 145 | console.log(clipboard.has('

selection

')) 146 | ``` 147 | 148 | ### `clipboard.read(data[, type])` _Experimental_ 149 | 150 | * `data` String 151 | * `type` String (optional) 152 | 153 | Returns `String` - Reads `data` from the clipboard. 154 | 155 | ### `clipboard.write(data[, type])` 156 | 157 | * `data` Object 158 | * `text` String (optional) 159 | * `html` String (optional) 160 | * `image` [NativeImage](native-image.md) (optional) 161 | * `rtf` String (optional) 162 | * `bookmark` String (optional) - The title of the url at `text`. 163 | * `type` String (optional) 164 | 165 | ```javascript 166 | const {clipboard} = require('electron') 167 | clipboard.write({text: 'test', html: 'test'}) 168 | ``` 169 | Writes `data` to the clipboard. 170 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/download-item.md: -------------------------------------------------------------------------------- 1 | ## Class: DownloadItem 2 | 3 | > Control file downloads from remote sources. 4 | 5 | Process: [Main](../glossary.md#main-process) 6 | 7 | `DownloadItem` is an `EventEmitter` that represents a download item in Electron. 8 | It is used in `will-download` event of `Session` class, and allows users to 9 | control the download item. 10 | 11 | ```javascript 12 | // In the main process. 13 | const {BrowserWindow} = require('electron') 14 | let win = new BrowserWindow() 15 | win.webContents.session.on('will-download', (event, item, webContents) => { 16 | // Set the save path, making Electron not to prompt a save dialog. 17 | item.setSavePath('/tmp/save.pdf') 18 | 19 | item.on('updated', (event, state) => { 20 | if (state === 'interrupted') { 21 | console.log('Download is interrupted but can be resumed') 22 | } else if (state === 'progressing') { 23 | if (item.isPaused()) { 24 | console.log('Download is paused') 25 | } else { 26 | console.log(`Received bytes: ${item.getReceivedBytes()}`) 27 | } 28 | } 29 | }) 30 | item.once('done', (event, state) => { 31 | if (state === 'completed') { 32 | console.log('Download successfully') 33 | } else { 34 | console.log(`Download failed: ${state}`) 35 | } 36 | }) 37 | }) 38 | ``` 39 | 40 | ### Instance Events 41 | 42 | #### Event: 'updated' 43 | 44 | Returns: 45 | 46 | * `event` Event 47 | * `state` String 48 | 49 | Emitted when the download has been updated and is not done. 50 | 51 | The `state` can be one of following: 52 | 53 | * `progressing` - The download is in-progress. 54 | * `interrupted` - The download has interrupted and can be resumed. 55 | 56 | #### Event: 'done' 57 | 58 | Returns: 59 | 60 | * `event` Event 61 | * `state` String 62 | 63 | Emitted when the download is in a terminal state. This includes a completed 64 | download, a cancelled download (via `downloadItem.cancel()`), and interrupted 65 | download that can't be resumed. 66 | 67 | The `state` can be one of following: 68 | 69 | * `completed` - The download completed successfully. 70 | * `cancelled` - The download has been cancelled. 71 | * `interrupted` - The download has interrupted and can not resume. 72 | 73 | ### Instance Methods 74 | 75 | The `downloadItem` object has the following methods: 76 | 77 | #### `downloadItem.setSavePath(path)` 78 | 79 | * `path` String - Set the save file path of the download item. 80 | 81 | The API is only available in session's `will-download` callback function. 82 | If user doesn't set the save path via the API, Electron will use the original 83 | routine to determine the save path(Usually prompts a save dialog). 84 | 85 | #### `downloadItem.getSavePath()` 86 | 87 | Returns `String` - The save path of the download item. This will be either the path 88 | set via `downloadItem.setSavePath(path)` or the path selected from the shown 89 | save dialog. 90 | 91 | #### `downloadItem.pause()` 92 | 93 | Pauses the download. 94 | 95 | #### `downloadItem.isPaused()` 96 | 97 | Returns `Boolean` - Whether the download is paused. 98 | 99 | #### `downloadItem.resume()` 100 | 101 | Resumes the download that has been paused. 102 | 103 | #### `downloadItem.canResume()` 104 | 105 | Resumes `Boolean` - Whether the download can resume. 106 | 107 | #### `downloadItem.cancel()` 108 | 109 | Cancels the download operation. 110 | 111 | #### `downloadItem.getURL()` 112 | 113 | Returns `String` - The origin url where the item is downloaded from. 114 | 115 | #### `downloadItem.getMimeType()` 116 | 117 | Returns `String` - The files mime type. 118 | 119 | #### `downloadItem.hasUserGesture()` 120 | 121 | Returns `Boolean` - Whether the download has user gesture. 122 | 123 | #### `downloadItem.getFilename()` 124 | 125 | Returns `String` - The file name of the download item. 126 | 127 | **Note:** The file name is not always the same as the actual one saved in local 128 | disk. If user changes the file name in a prompted download saving dialog, the 129 | actual name of saved file will be different. 130 | 131 | #### `downloadItem.getTotalBytes()` 132 | 133 | Returns `Integer` - The total size in bytes of the download item. 134 | 135 | If the size is unknown, it returns 0. 136 | 137 | #### `downloadItem.getReceivedBytes()` 138 | 139 | Returns `Integer` - The received bytes of the download item. 140 | 141 | #### `downloadItem.getContentDisposition()` 142 | 143 | Returns `String` - The Content-Disposition field from the response 144 | header. 145 | 146 | #### `downloadItem.getState()` 147 | 148 | Returns `String` - The current state. Can be `progressing`, `completed`, `cancelled` or `interrupted`. 149 | 150 | **Note:** The following methods are useful specifically to resume a 151 | `cancelled` item when session is restarted. 152 | 153 | #### `downloadItem.getURLChain()` 154 | 155 | Returns `String[]` - The complete url chain of the item including any redirects. 156 | 157 | #### `downloadItem.getLastModifiedTime()` 158 | 159 | Returns `String` - Last-Modified header value. 160 | 161 | #### `downloadItem.getETag()` 162 | 163 | Returns `String` - ETag header value. 164 | 165 | #### `downloadItem.getStartTime()` 166 | 167 | Returns `Double` - Number of seconds since the UNIX epoch when the download was 168 | started. 169 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/frameless-window.md: -------------------------------------------------------------------------------- 1 | # Frameless Window 2 | 3 | > Open a window without toolbars, borders, or other graphical "chrome". 4 | 5 | A frameless window is a window that has no 6 | [chrome](https://developer.mozilla.org/en-US/docs/Glossary/Chrome), the parts of 7 | the window, like toolbars, that are not a part of the web page. These are 8 | options on the [`BrowserWindow`](browser-window.md) class. 9 | 10 | ## Create a frameless window 11 | 12 | To create a frameless window, you need to set `frame` to `false` in 13 | [BrowserWindow](browser-window.md)'s `options`: 14 | 15 | 16 | ```javascript 17 | const {BrowserWindow} = require('electron') 18 | let win = new BrowserWindow({width: 800, height: 600, frame: false}) 19 | win.show() 20 | ``` 21 | 22 | ### Alternatives on macOS 23 | 24 | On macOS 10.9 Mavericks and newer, there's an alternative way to specify 25 | a chromeless window. Instead of setting `frame` to `false` which disables 26 | both the titlebar and window controls, you may want to have the title bar 27 | hidden and your content extend to the full window size, yet still preserve 28 | the window controls ("traffic lights") for standard window actions. 29 | You can do so by specifying the new `titleBarStyle` option: 30 | 31 | #### `hidden` 32 | 33 | Results in a hidden title bar and a full size content window, yet the title bar still has the standard window controls (“traffic lights”) in the top left. 34 | 35 | ```javascript 36 | const {BrowserWindow} = require('electron') 37 | let win = new BrowserWindow({titleBarStyle: 'hidden'}) 38 | win.show() 39 | ``` 40 | 41 | #### `hidden-inset` 42 | 43 | Results in a hidden title bar with an alternative look where the traffic light buttons are slightly more inset from the window edge. 44 | 45 | ```javascript 46 | const {BrowserWindow} = require('electron') 47 | let win = new BrowserWindow({titleBarStyle: 'hidden-inset'}) 48 | win.show() 49 | ``` 50 | 51 | ## Transparent window 52 | 53 | By setting the `transparent` option to `true`, you can also make the frameless 54 | window transparent: 55 | 56 | ```javascript 57 | const {BrowserWindow} = require('electron') 58 | let win = new BrowserWindow({transparent: true, frame: false}) 59 | win.show() 60 | ``` 61 | 62 | ### Limitations 63 | 64 | * You can not click through the transparent area. We are going to introduce an 65 | API to set window shape to solve this, see 66 | [our issue](https://github.com/electron/electron/issues/1335) for details. 67 | * Transparent windows are not resizable. Setting `resizable` to `true` may make 68 | a transparent window stop working on some platforms. 69 | * The `blur` filter only applies to the web page, so there is no way to apply 70 | blur effect to the content below the window (i.e. other applications open on 71 | the user's system). 72 | * On Windows operating systems, transparent windows will not work when DWM is 73 | disabled. 74 | * On Linux users have to put `--enable-transparent-visuals --disable-gpu` in 75 | the command line to disable GPU and allow ARGB to make transparent window, 76 | this is caused by an upstream bug that [alpha channel doesn't work on some 77 | NVidia drivers](https://code.google.com/p/chromium/issues/detail?id=369209) on 78 | Linux. 79 | * On Mac the native window shadow will not be shown on a transparent window. 80 | 81 | ## Click-through window 82 | 83 | To create a click-through window, i.e. making the window ignore all mouse 84 | events, you can call the [win.setIgnoreMouseEvents(ignore)][ignore-mouse-events] 85 | API: 86 | 87 | ```javascript 88 | const {BrowserWindow} = require('electron') 89 | let win = new BrowserWindow() 90 | win.setIgnoreMouseEvents(true) 91 | ``` 92 | 93 | ## Draggable region 94 | 95 | By default, the frameless window is non-draggable. Apps need to specify 96 | `-webkit-app-region: drag` in CSS to tell Electron which regions are draggable 97 | (like the OS's standard titlebar), and apps can also use 98 | `-webkit-app-region: no-drag` to exclude the non-draggable area from the 99 | draggable region. Note that only rectangular shapes are currently supported. 100 | 101 | To make the whole window draggable, you can add `-webkit-app-region: drag` as 102 | `body`'s style: 103 | 104 | ```html 105 | 106 | 107 | ``` 108 | 109 | And note that if you have made the whole window draggable, you must also mark 110 | buttons as non-draggable, otherwise it would be impossible for users to click on 111 | them: 112 | 113 | ```css 114 | button { 115 | -webkit-app-region: no-drag; 116 | } 117 | ``` 118 | 119 | If you're setting just a custom titlebar as draggable, you also need to make all 120 | buttons in titlebar non-draggable. 121 | 122 | ## Text selection 123 | 124 | In a frameless window the dragging behaviour may conflict with selecting text. 125 | For example, when you drag the titlebar you may accidentally select the text on 126 | the titlebar. To prevent this, you need to disable text selection within a 127 | draggable area like this: 128 | 129 | ```css 130 | .titlebar { 131 | -webkit-user-select: none; 132 | -webkit-app-region: drag; 133 | } 134 | ``` 135 | 136 | ## Context menu 137 | 138 | On some platforms, the draggable area will be treated as a non-client frame, so 139 | when you right click on it a system menu will pop up. To make the context menu 140 | behave correctly on all platforms you should never use a custom context menu on 141 | draggable areas. 142 | 143 | [ignore-mouse-events]: browser-window.md#winsetignoremouseeventsignore 144 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/content-tracing.md: -------------------------------------------------------------------------------- 1 | # contentTracing 2 | 3 | > Collect tracing data from Chromium's content module for finding performance 4 | bottlenecks and slow operations. 5 | 6 | Process: [Main](../glossary.md#main-process) 7 | 8 | This module does not include a web interface so you need to open 9 | `chrome://tracing/` in a Chrome browser and load the generated file to view the 10 | result. 11 | 12 | **Note:** You should not use this module until the `ready` event of the app 13 | module is emitted. 14 | 15 | 16 | ```javascript 17 | const {app, contentTracing} = require('electron') 18 | 19 | app.on('ready', () => { 20 | const options = { 21 | categoryFilter: '*', 22 | traceOptions: 'record-until-full,enable-sampling' 23 | } 24 | 25 | contentTracing.startRecording(options, () => { 26 | console.log('Tracing started') 27 | 28 | setTimeout(() => { 29 | contentTracing.stopRecording('', (path) => { 30 | console.log('Tracing data recorded to ' + path) 31 | }) 32 | }, 5000) 33 | }) 34 | }) 35 | ``` 36 | 37 | ## Methods 38 | 39 | The `contentTracing` module has the following methods: 40 | 41 | ### `contentTracing.getCategories(callback)` 42 | 43 | * `callback` Function 44 | * `categories` String[] 45 | 46 | Get a set of category groups. The category groups can change as new code paths 47 | are reached. 48 | 49 | Once all child processes have acknowledged the `getCategories` request the 50 | `callback` is invoked with an array of category groups. 51 | 52 | ### `contentTracing.startRecording(options, callback)` 53 | 54 | * `options` Object 55 | * `categoryFilter` String 56 | * `traceOptions` String 57 | * `callback` Function 58 | 59 | Start recording on all processes. 60 | 61 | Recording begins immediately locally and asynchronously on child processes 62 | as soon as they receive the EnableRecording request. The `callback` will be 63 | called once all child processes have acknowledged the `startRecording` request. 64 | 65 | `categoryFilter` is a filter to control what category groups should be 66 | traced. A filter can have an optional `-` prefix to exclude category groups 67 | that contain a matching category. Having both included and excluded 68 | category patterns in the same list is not supported. 69 | 70 | Examples: 71 | 72 | * `test_MyTest*`, 73 | * `test_MyTest*,test_OtherStuff`, 74 | * `"-excluded_category1,-excluded_category2` 75 | 76 | `traceOptions` controls what kind of tracing is enabled, it is a comma-delimited 77 | list. Possible options are: 78 | 79 | * `record-until-full` 80 | * `record-continuously` 81 | * `trace-to-console` 82 | * `enable-sampling` 83 | * `enable-systrace` 84 | 85 | The first 3 options are trace recording modes and hence mutually exclusive. 86 | If more than one trace recording modes appear in the `traceOptions` string, 87 | the last one takes precedence. If none of the trace recording modes are 88 | specified, recording mode is `record-until-full`. 89 | 90 | The trace option will first be reset to the default option (`record_mode` set to 91 | `record-until-full`, `enable_sampling` and `enable_systrace` set to `false`) 92 | before options parsed from `traceOptions` are applied on it. 93 | 94 | ### `contentTracing.stopRecording(resultFilePath, callback)` 95 | 96 | * `resultFilePath` String 97 | * `callback` Function 98 | * `resultFilePath` String 99 | 100 | Stop recording on all processes. 101 | 102 | Child processes typically cache trace data and only rarely flush and send 103 | trace data back to the main process. This helps to minimize the runtime overhead 104 | of tracing since sending trace data over IPC can be an expensive operation. So, 105 | to end tracing, we must asynchronously ask all child processes to flush any 106 | pending trace data. 107 | 108 | Once all child processes have acknowledged the `stopRecording` request, 109 | `callback` will be called with a file that contains the traced data. 110 | 111 | Trace data will be written into `resultFilePath` if it is not empty or into a 112 | temporary file. The actual file path will be passed to `callback` if it's not 113 | `null`. 114 | 115 | ### `contentTracing.startMonitoring(options, callback)` 116 | 117 | * `options` Object 118 | * `categoryFilter` String 119 | * `traceOptions` String 120 | * `callback` Function 121 | 122 | Start monitoring on all processes. 123 | 124 | Monitoring begins immediately locally and asynchronously on child processes as 125 | soon as they receive the `startMonitoring` request. 126 | 127 | Once all child processes have acknowledged the `startMonitoring` request the 128 | `callback` will be called. 129 | 130 | ### `contentTracing.stopMonitoring(callback)` 131 | 132 | * `callback` Function 133 | 134 | Stop monitoring on all processes. 135 | 136 | Once all child processes have acknowledged the `stopMonitoring` request the 137 | `callback` is called. 138 | 139 | ### `contentTracing.captureMonitoringSnapshot(resultFilePath, callback)` 140 | 141 | * `resultFilePath` String 142 | * `callback` Function 143 | * `resultFilePath` String 144 | 145 | Get the current monitoring traced data. 146 | 147 | Child processes typically cache trace data and only rarely flush and send 148 | trace data back to the main process. This is because it may be an expensive 149 | operation to send the trace data over IPC and we would like to avoid unneeded 150 | runtime overhead from tracing. So, to end tracing, we must asynchronously ask 151 | all child processes to flush any pending trace data. 152 | 153 | Once all child processes have acknowledged the `captureMonitoringSnapshot` 154 | request the `callback` will be called with a file that contains the traced data. 155 | 156 | 157 | ### `contentTracing.getTraceBufferUsage(callback)` 158 | 159 | * `callback` Function 160 | * `value` Number 161 | * `percentage` Number 162 | 163 | Get the maximum usage across processes of trace buffer as a percentage of the 164 | full state. When the TraceBufferUsage value is determined the `callback` is 165 | called. 166 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/auto-updater.md: -------------------------------------------------------------------------------- 1 | # autoUpdater 2 | 3 | > Enable apps to automatically update themselves. 4 | 5 | Process: [Main](../glossary.md#main-process) 6 | 7 | The `autoUpdater` module provides an interface for the 8 | [Squirrel](https://github.com/Squirrel) framework. 9 | 10 | You can quickly launch a multi-platform release server for distributing your 11 | application by using one of these projects: 12 | 13 | - [nuts][nuts]: *A smart release server for your applications, using GitHub as a backend. Auto-updates with Squirrel (Mac & Windows)* 14 | - [electron-release-server][electron-release-server]: *A fully featured, 15 | self-hosted release server for electron applications, compatible with 16 | auto-updater* 17 | - [squirrel-updates-server][squirrel-updates-server]: *A simple node.js server 18 | for Squirrel.Mac and Squirrel.Windows which uses GitHub releases* 19 | - [squirrel-release-server][squirrel-release-server]: *A simple PHP application for Squirrel.Windows which reads updates from a folder. Supports delta updates.* 20 | 21 | ## Platform notices 22 | 23 | Though `autoUpdater` provides a uniform API for different platforms, there are 24 | still some subtle differences on each platform. 25 | 26 | ### macOS 27 | 28 | On macOS, the `autoUpdater` module is built upon [Squirrel.Mac][squirrel-mac], 29 | meaning you don't need any special setup to make it work. For server-side 30 | requirements, you can read [Server Support][server-support]. Note that [App 31 | Transport Security](https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW35) (ATS) applies to all requests made as part of the 32 | update process. Apps that need to disable ATS can add the 33 | `NSAllowsArbitraryLoads` key to their app's plist. 34 | 35 | **Note:** Your application must be signed for automatic updates on macOS. 36 | This is a requirement of `Squirrel.Mac`. 37 | 38 | ### Windows 39 | 40 | On Windows, you have to install your app into a user's machine before you can 41 | use the `autoUpdater`, so it is recommended that you use the 42 | [electron-winstaller][installer-lib], [electron-builder][electron-builder-lib] or the [grunt-electron-installer][installer] package to generate a Windows installer. 43 | 44 | When using [electron-winstaller][installer-lib] or [electron-builder][electron-builder-lib] make sure you do not try to update your app [the first time it runs](https://github.com/electron/windows-installer#handling-squirrel-events) (Also see [this issue for more info](https://github.com/electron/electron/issues/7155)). It's also recommended to use [electron-squirrel-startup](https://github.com/mongodb-js/electron-squirrel-startup) to get desktop shortcuts for your app. 45 | 46 | The installer generated with Squirrel will create a shortcut icon with an 47 | [Application User Model ID][app-user-model-id] in the format of 48 | `com.squirrel.PACKAGE_ID.YOUR_EXE_WITHOUT_DOT_EXE`, examples are 49 | `com.squirrel.slack.Slack` and `com.squirrel.code.Code`. You have to use the 50 | same ID for your app with `app.setAppUserModelId` API, otherwise Windows will 51 | not be able to pin your app properly in task bar. 52 | 53 | The server-side setup is also different from macOS. You can read the documents of 54 | [Squirrel.Windows][squirrel-windows] to get more details. 55 | 56 | ### Linux 57 | 58 | There is no built-in support for auto-updater on Linux, so it is recommended to 59 | use the distribution's package manager to update your app. 60 | 61 | ## Events 62 | 63 | The `autoUpdater` object emits the following events: 64 | 65 | ### Event: 'error' 66 | 67 | Returns: 68 | 69 | * `error` Error 70 | 71 | Emitted when there is an error while updating. 72 | 73 | ### Event: 'checking-for-update' 74 | 75 | Emitted when checking if an update has started. 76 | 77 | ### Event: 'update-available' 78 | 79 | Emitted when there is an available update. The update is downloaded 80 | automatically. 81 | 82 | ### Event: 'update-not-available' 83 | 84 | Emitted when there is no available update. 85 | 86 | ### Event: 'update-downloaded' 87 | 88 | Returns: 89 | 90 | * `event` Event 91 | * `releaseNotes` String 92 | * `releaseName` String 93 | * `releaseDate` Date 94 | * `updateURL` String 95 | 96 | Emitted when an update has been downloaded. 97 | 98 | On Windows only `releaseName` is available. 99 | 100 | ## Methods 101 | 102 | The `autoUpdater` object has the following methods: 103 | 104 | ### `autoUpdater.setFeedURL(url[, requestHeaders])` 105 | 106 | * `url` String 107 | * `requestHeaders` Object _macOS_ (optional) - HTTP request headers. 108 | 109 | Sets the `url` and initialize the auto updater. 110 | 111 | ### `autoUpdater.getFeedURL()` 112 | 113 | Returns `String` - The current update feed URL. 114 | 115 | ### `autoUpdater.checkForUpdates()` 116 | 117 | Asks the server whether there is an update. You must call `setFeedURL` before 118 | using this API. 119 | 120 | ### `autoUpdater.quitAndInstall()` 121 | 122 | Restarts the app and installs the update after it has been downloaded. It 123 | should only be called after `update-downloaded` has been emitted. 124 | 125 | **Note:** `autoUpdater.quitAndInstall()` will close all application windows 126 | first and only emit `before-quit` event on `app` after that. This is different 127 | from the normal quit event sequence. 128 | 129 | [squirrel-mac]: https://github.com/Squirrel/Squirrel.Mac 130 | [server-support]: https://github.com/Squirrel/Squirrel.Mac#server-support 131 | [squirrel-windows]: https://github.com/Squirrel/Squirrel.Windows 132 | [installer]: https://github.com/electron/grunt-electron-installer 133 | [installer-lib]: https://github.com/electron/windows-installer 134 | [electron-builder-lib]: https://github.com/electron-userland/electron-builder 135 | [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx 136 | [electron-release-server]: https://github.com/ArekSredzki/electron-release-server 137 | [squirrel-updates-server]: https://github.com/Aluxian/squirrel-updates-server 138 | [nuts]: https://github.com/GitbookIO/nuts 139 | [squirrel-release-server]: https://github.com/Arcath/squirrel-release-server 140 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/web-frame.md: -------------------------------------------------------------------------------- 1 | # webFrame 2 | 3 | > Customize the rendering of the current web page. 4 | 5 | Process: [Renderer](../glossary.md#renderer-process) 6 | 7 | An example of zooming current page to 200%. 8 | 9 | ```javascript 10 | const {webFrame} = require('electron') 11 | 12 | webFrame.setZoomFactor(2) 13 | ``` 14 | 15 | ## Methods 16 | 17 | The `webFrame` module has the following methods: 18 | 19 | ### `webFrame.setZoomFactor(factor)` 20 | 21 | * `factor` Number - Zoom factor. 22 | 23 | Changes the zoom factor to the specified factor. Zoom factor is 24 | zoom percent divided by 100, so 300% = 3.0. 25 | 26 | ### `webFrame.getZoomFactor()` 27 | 28 | Returns `Number` - The current zoom factor. 29 | 30 | ### `webFrame.setZoomLevel(level)` 31 | 32 | * `level` Number - Zoom level 33 | 34 | Changes the zoom level to the specified level. The original size is 0 and each 35 | increment above or below represents zooming 20% larger or smaller to default 36 | limits of 300% and 50% of original size, respectively. 37 | 38 | ### `webFrame.getZoomLevel()` 39 | 40 | Returns `Number` - The current zoom level. 41 | 42 | ### `webFrame.setZoomLevelLimits(minimumLevel, maximumLevel)` 43 | 44 | * `minimumLevel` Number 45 | * `maximumLevel` Number 46 | 47 | **Deprecated:** Call `setVisualZoomLevelLimits` instead to set the visual zoom 48 | level limits. This method will be removed in Electron 2.0. 49 | 50 | ### `webFrame.setVisualZoomLevelLimits(minimumLevel, maximumLevel)` 51 | 52 | * `minimumLevel` Number 53 | * `maximumLevel` Number 54 | 55 | Sets the maximum and minimum pinch-to-zoom level. 56 | 57 | ### `webFrame.setLayoutZoomLevelLimits(minimumLevel, maximumLevel)` 58 | 59 | * `minimumLevel` Number 60 | * `maximumLevel` Number 61 | 62 | Sets the maximum and minimum layout-based (i.e. non-visual) zoom level. 63 | 64 | ### `webFrame.setSpellCheckProvider(language, autoCorrectWord, provider)` 65 | 66 | * `language` String 67 | * `autoCorrectWord` Boolean 68 | * `provider` Object 69 | * `spellCheck` Function - Returns `Boolean` 70 | * `text` String 71 | 72 | Sets a provider for spell checking in input fields and text areas. 73 | 74 | The `provider` must be an object that has a `spellCheck` method that returns 75 | whether the word passed is correctly spelled. 76 | 77 | An example of using [node-spellchecker][spellchecker] as provider: 78 | 79 | ```javascript 80 | const {webFrame} = require('electron') 81 | webFrame.setSpellCheckProvider('en-US', true, { 82 | spellCheck (text) { 83 | return !(require('spellchecker').isMisspelled(text)) 84 | } 85 | }) 86 | ``` 87 | 88 | ### `webFrame.registerURLSchemeAsSecure(scheme)` 89 | 90 | * `scheme` String 91 | 92 | Registers the `scheme` as secure scheme. 93 | 94 | Secure schemes do not trigger mixed content warnings. For example, `https` and 95 | `data` are secure schemes because they cannot be corrupted by active network 96 | attackers. 97 | 98 | ### `webFrame.registerURLSchemeAsBypassingCSP(scheme)` 99 | 100 | * `scheme` String 101 | 102 | Resources will be loaded from this `scheme` regardless of the current page's 103 | Content Security Policy. 104 | 105 | ### `webFrame.registerURLSchemeAsPrivileged(scheme[, options])` 106 | 107 | * `scheme` String 108 | * `options` Object (optional) 109 | * `secure` Boolean - (optional) Default true. 110 | * `bypassCSP` Boolean - (optional) Default true. 111 | * `allowServiceWorkers` Boolean - (optional) Default true. 112 | * `supportFetchAPI` Boolean - (optional) Default true. 113 | * `corsEnabled` Boolean - (optional) Default true. 114 | 115 | Registers the `scheme` as secure, bypasses content security policy for resources, 116 | allows registering ServiceWorker and supports fetch API. 117 | 118 | Specify an option with the value of `false` to omit it from the registration. 119 | An example of registering a privileged scheme, without bypassing Content Security Policy: 120 | 121 | ```javascript 122 | const {webFrame} = require('electron') 123 | webFrame.registerURLSchemeAsPrivileged('foo', { bypassCSP: false }) 124 | ``` 125 | 126 | ### `webFrame.insertText(text)` 127 | 128 | * `text` String 129 | 130 | Inserts `text` to the focused element. 131 | 132 | ### `webFrame.executeJavaScript(code[, userGesture, callback])` 133 | 134 | * `code` String 135 | * `userGesture` Boolean (optional) - Default is `false`. 136 | * `callback` Function (optional) - Called after script has been executed. 137 | * `result` Any 138 | 139 | Evaluates `code` in page. 140 | 141 | In the browser window some HTML APIs like `requestFullScreen` can only be 142 | invoked by a gesture from the user. Setting `userGesture` to `true` will remove 143 | this limitation. 144 | 145 | ### `webFrame.getResourceUsage()` 146 | 147 | Returns `Object`: 148 | 149 | * `images` [MemoryUsageDetails](structures/memory-usage-details.md) 150 | * `cssStyleSheets` [MemoryUsageDetails](structures/memory-usage-details.md) 151 | * `xslStyleSheets` [MemoryUsageDetails](structures/memory-usage-details.md) 152 | * `fonts` [MemoryUsageDetails](structures/memory-usage-details.md) 153 | * `other` [MemoryUsageDetails](structures/memory-usage-details.md) 154 | 155 | Returns an object describing usage information of Blink's internal memory 156 | caches. 157 | 158 | ```javascript 159 | const {webFrame} = require('electron') 160 | console.log(webFrame.getResourceUsage()) 161 | ``` 162 | 163 | This will generate: 164 | 165 | ```javascript 166 | { 167 | images: { 168 | count: 22, 169 | size: 2549, 170 | liveSize: 2542 171 | }, 172 | cssStyleSheets: { /* same with "images" */ }, 173 | xslStyleSheets: { /* same with "images" */ }, 174 | fonts: { /* same with "images" */ }, 175 | other: { /* same with "images" */ } 176 | } 177 | ``` 178 | 179 | ### `webFrame.clearCache()` 180 | 181 | Attempts to free memory that is no longer being used (like images from a 182 | previous navigation). 183 | 184 | Note that blindly calling this method probably makes Electron slower since it 185 | will have to refill these emptied caches, you should only call it if an event 186 | in your app has occurred that makes you think your page is actually using less 187 | memory (i.e. you have navigated from a super heavy page to a mostly empty one, 188 | and intend to stay there). 189 | 190 | [spellchecker]: https://github.com/atom/node-spellchecker 191 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/chrome-command-line-switches.md: -------------------------------------------------------------------------------- 1 | # Supported Chrome Command Line Switches 2 | 3 | > Command line switches supported by Electron. 4 | 5 | You can use [app.commandLine.appendSwitch][append-switch] to append them in 6 | your app's main script before the [ready][ready] event of the [app][app] module 7 | is emitted: 8 | 9 | ```javascript 10 | const {app} = require('electron') 11 | app.commandLine.appendSwitch('remote-debugging-port', '8315') 12 | app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1') 13 | 14 | app.on('ready', () => { 15 | // Your code here 16 | }) 17 | ``` 18 | 19 | ## --ignore-connections-limit=`domains` 20 | 21 | Ignore the connections limit for `domains` list separated by `,`. 22 | 23 | ## --disable-http-cache 24 | 25 | Disables the disk cache for HTTP requests. 26 | 27 | ## --disable-http2 28 | 29 | Disable HTTP/2 and SPDY/3.1 protocols. 30 | 31 | ## --debug=`port` and --debug-brk=`port` 32 | 33 | Debug-related flags, see the [Debugging the Main Process][debugging-main-process] guide for details. 34 | 35 | ## --remote-debugging-port=`port` 36 | 37 | Enables remote debugging over HTTP on the specified `port`. 38 | 39 | ## --js-flags=`flags` 40 | 41 | Specifies the flags passed to the Node JS engine. It has to be passed when starting 42 | Electron if you want to enable the `flags` in the main process. 43 | 44 | ```bash 45 | $ electron --js-flags="--harmony_proxies --harmony_collections" your-app 46 | ``` 47 | 48 | See the [Node documentation][node-cli] or run `node --help` in your terminal for a list of available flags. Additionally, run `node --v8-options` to see a list of flags that specifically refer to Node's V8 JavaScript engine. 49 | 50 | ## --proxy-server=`address:port` 51 | 52 | Use a specified proxy server, which overrides the system setting. This switch 53 | only affects requests with HTTP protocol, including HTTPS and WebSocket 54 | requests. It is also noteworthy that not all proxy servers support HTTPS and 55 | WebSocket requests. 56 | 57 | ## --proxy-bypass-list=`hosts` 58 | 59 | Instructs Electron to bypass the proxy server for the given semi-colon-separated 60 | list of hosts. This flag has an effect only if used in tandem with 61 | `--proxy-server`. 62 | 63 | For example: 64 | 65 | ```javascript 66 | const {app} = require('electron') 67 | app.commandLine.appendSwitch('proxy-bypass-list', ';*.google.com;*foo.com;1.2.3.4:5678') 68 | ``` 69 | 70 | Will use the proxy server for all hosts except for local addresses (`localhost`, 71 | `127.0.0.1` etc.), `google.com` subdomains, hosts that contain the suffix 72 | `foo.com` and anything at `1.2.3.4:5678`. 73 | 74 | ## --proxy-pac-url=`url` 75 | 76 | Uses the PAC script at the specified `url`. 77 | 78 | ## --no-proxy-server 79 | 80 | Don't use a proxy server and always make direct connections. Overrides any other 81 | proxy server flags that are passed. 82 | 83 | ## --host-rules=`rules` 84 | 85 | A comma-separated list of `rules` that control how hostnames are mapped. 86 | 87 | For example: 88 | 89 | * `MAP * 127.0.0.1` Forces all hostnames to be mapped to 127.0.0.1 90 | * `MAP *.google.com proxy` Forces all google.com subdomains to be resolved to 91 | "proxy". 92 | * `MAP test.com [::1]:77` Forces "test.com" to resolve to IPv6 loopback. Will 93 | also force the port of the resulting socket address to be 77. 94 | * `MAP * baz, EXCLUDE www.google.com` Remaps everything to "baz", except for 95 | "www.google.com". 96 | 97 | These mappings apply to the endpoint host in a net request (the TCP connect 98 | and host resolver in a direct connection, and the `CONNECT` in an HTTP proxy 99 | connection, and the endpoint host in a `SOCKS` proxy connection). 100 | 101 | ## --host-resolver-rules=`rules` 102 | 103 | Like `--host-rules` but these `rules` only apply to the host resolver. 104 | 105 | ## --auth-server-whitelist=`url` 106 | 107 | A comma-separated list of servers for which integrated authentication is enabled. 108 | 109 | For example: 110 | 111 | ``` 112 | --auth-server-whitelist='*example.com, *foobar.com, *baz' 113 | ``` 114 | 115 | then any `url` ending with `example.com`, `foobar.com`, `baz` will be considered 116 | for integrated authentication. Without `*` prefix the url has to match exactly. 117 | 118 | ## --auth-negotiate-delegate-whitelist=`url` 119 | 120 | A comma-separated list of servers for which delegation of user credentials is required. 121 | Without `*` prefix the url has to match exactly. 122 | 123 | ## --ignore-certificate-errors 124 | 125 | Ignores certificate related errors. 126 | 127 | ## --ppapi-flash-path=`path` 128 | 129 | Sets the `path` of the pepper flash plugin. 130 | 131 | ## --ppapi-flash-version=`version` 132 | 133 | Sets the `version` of the pepper flash plugin. 134 | 135 | ## --log-net-log=`path` 136 | 137 | Enables net log events to be saved and writes them to `path`. 138 | 139 | ## --disable-renderer-backgrounding 140 | 141 | Prevents Chromium from lowering the priority of invisible pages' renderer 142 | processes. 143 | 144 | This flag is global to all renderer processes, if you only want to disable 145 | throttling in one window, you can take the hack of 146 | [playing silent audio][play-silent-audio]. 147 | 148 | ## --enable-logging 149 | 150 | Prints Chromium's logging into console. 151 | 152 | This switch can not be used in `app.commandLine.appendSwitch` since it is parsed 153 | earlier than user's app is loaded, but you can set the `ELECTRON_ENABLE_LOGGING` 154 | environment variable to achieve the same effect. 155 | 156 | ## --v=`log_level` 157 | 158 | Gives the default maximal active V-logging level; 0 is the default. Normally 159 | positive values are used for V-logging levels. 160 | 161 | This switch only works when `--enable-logging` is also passed. 162 | 163 | ## --vmodule=`pattern` 164 | 165 | Gives the per-module maximal V-logging levels to override the value given by 166 | `--v`. E.g. `my_module=2,foo*=3` would change the logging level for all code in 167 | source files `my_module.*` and `foo*.*`. 168 | 169 | Any pattern containing a forward or backward slash will be tested against the 170 | whole pathname and not just the module. E.g. `*/foo/bar/*=2` would change the 171 | logging level for all code in the source files under a `foo/bar` directory. 172 | 173 | This switch only works when `--enable-logging` is also passed. 174 | 175 | [app]: app.md 176 | [append-switch]: app.md#appcommandlineappendswitchswitch-value 177 | [ready]: app.md#event-ready 178 | [play-silent-audio]: https://github.com/atom/atom/pull/9485/files 179 | [debugging-main-process]: ../tutorial/debugging-main-process.md 180 | [node-cli]: https://nodejs.org/api/cli.html 181 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # electron-docs-linter [![Build Status](https://travis-ci.org/electron/electron-docs-linter.svg?branch=master)](https://travis-ci.org/electron/electron-docs-linter) 2 | 3 | Parse and validate Electron's API documentation. 4 | 5 | ## Installation 6 | 7 | ```sh 8 | npm install electron-docs-linter --save 9 | ``` 10 | 11 | ## CLI Usage 12 | 13 | To lint the docs: 14 | 15 | ```sh 16 | electron-docs-linter path/to/electron/docs 17 | ``` 18 | 19 | If errors are found, they are printed to STDERR and the process 20 | exits un-gracefully. 21 | 22 | To lint the docs and save the generated [JSON schema](http://electronjs.org/blog/2016/09/27/api-docs-json-schema) to a file: 23 | 24 | ```sh 25 | electron-docs-linter docs/api --version=1.2.3 --outfile=api.json 26 | ``` 27 | 28 | ## Programmatic Usage 29 | 30 | The module exports a function that parses markdown docs in a given directory, 31 | then returns a JSON representation of all the APIs. 32 | 33 | ```js 34 | const lint = require('electron-docs-linter') 35 | const docPath = './test/fixtures/electron/docs/api' 36 | const targetVersion = '1.2.3' // the soon-to-be-released version of electron 37 | 38 | lint(docPath, targetVersion).then(function (apis) { 39 | // `apis` is an array of API objects. To find one: 40 | var win = apis.find(api => api.name === 'BrowserWindow') 41 | 42 | // The array also has a string key for each API name, so 43 | // you can access APIs like this too: 44 | win = apis.BrowserWindow 45 | 46 | win.events.length 47 | // => 25 48 | 49 | win.events[0] 50 | // { 51 | // "name": "page-title-updated", 52 | // "description": "Emitted when the document...", 53 | // "returns": [ 54 | // { 55 | // "name": "event", 56 | // "type": "Event" 57 | // } 58 | // ] 59 | // } 60 | 61 | win.instanceMethods[20] 62 | // { 63 | // name: 'setSize', 64 | // signature: '(width, height[, animate])' 65 | // } 66 | }) 67 | ``` 68 | 69 | ## How It Works 70 | 71 | The linter starts with [a list of all the API names](/lib/seeds.js) as seed data. 72 | 73 | Each API's structure is inferred by parsing its raw markdown documentation from 74 | the [electron repo](https://github.com/electron/electron/tree/master/docs/api). 75 | The [electron-docs](https://github.com/zeke/electron-docs) module abstracts away 76 | the challenges of fetching file contents in bulk. 77 | 78 | Electron's API documentation adheres to 79 | [Electron Coding Style](https://github.com/electron/electron/blob/master/docs/development/coding-style.md#naming-things) 80 | and the 81 | [Electron Styleguide](https://github.com/electron/electron/blob/master/docs/styleguide.md), 82 | so its content can be programmatically parsed. To make the content easy to parse, 83 | the raw markdown is converted to HTML using 84 | [marky-markdown-lite](https://ghub.io/marky-markdown-lite), 85 | which returns a [cheerio](https://ghub.io/cheerio) DOM object that can be queried 86 | and traversed using familiar CSS selectors. 87 | 88 | The result is an array of API objects. The following 89 | metadata is included for each API, where appropriate: 90 | 91 | - name 92 | - description 93 | - type (Class or Module) 94 | - process (main, renderer, or both) 95 | - methods 96 | - events 97 | - static methods (aka class methods) 98 | - instance events 99 | - instance methods 100 | - instance properties 101 | - website URL 102 | - GitHub repository URL 103 | 104 | ## Related Things and Prior Art 105 | 106 | - https://github.com/atom/autocomplete-atom-api 107 | - https://kapeli.com/docsets#dashDocset 108 | - [issue: Publish the public API as JSON](https://github.com/electron/electron/issues/3375) 109 | - https://raw.githubusercontent.com/atom/autocomplete-atom-api/master/completions.json 110 | - [devdocs.io](http://devdocs.io/) 111 | - [Node.js - About this Documentation](https://nodejs.org/dist/latest-v6.x/docs/api/documentation.html) 112 | 113 | ## TypeScript Definitions 114 | 115 | A lot of people want an up-to-date TypeScript definition file for Electron. 116 | 117 | - https://github.com/MarshallOfSound/Electron-DefinitelyTyped (WIP) 118 | - https://github.com/electron/electron/issues/4875 119 | - https://www.npmjs.com/package/@types/electron 120 | - https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/github-electron 121 | - https://github.com/RyanCavanaugh/dts-dom - A DOM library for generation TypeScript declaration (.d.ts) files 122 | - https://github.com/lbovet/typson - Converts TypeScript to JSON-schema 123 | - https://github.com/lbovet/docson - Documentation for your JSON types 124 | 125 | ## Dependencies 126 | 127 | - [cheerio](https://github.com/cheeriojs/cheerio): Tiny, fast, and elegant implementation of core jQuery designed specifically for the server 128 | - [clean-deep](https://github.com/seegno/clean-deep): Remove falsy, empty or nullable values from objects 129 | - [decamelize](https://github.com/sindresorhus/decamelize): Convert a camelized string into a lowercased one with a custom separator: unicornRainbow → unicorn_rainbow 130 | - [dedent](https://github.com/dmnd/dedent): An ES6 string tag that strips indentation from multi-line strings 131 | - [electron-docs](https://github.com/zeke/electron-docs): Fetch Electron documentation as raw markdown strings 132 | - [keyed-array](https://github.com/zeke/keyed-array): Recursively add named keys to arrays of objects 133 | - [lodash.pick](https://github.com/lodash/lodash): The lodash method `_.pick` exported as a module. 134 | - [lodash.sum](https://github.com/lodash/lodash): The lodash method `_.sum` exported as a module. 135 | - [marky-markdown-lite](https://github.com/zeke/marky-markdown-lite): A version of marky-markdown that does less 136 | - [minimist](https://github.com/substack/minimist): parse argument options 137 | - [ora](https://github.com/sindresorhus/ora): Elegant terminal spinner 138 | - [path-exists](https://github.com/sindresorhus/path-exists): Check if a path exists 139 | - [pify](https://github.com/sindresorhus/pify): Promisify a callback-style function 140 | - [revalidator](https://github.com/flatiron/revalidator): A cross-browser / node.js validator powered by JSON Schema 141 | - [semver](https://github.com/npm/node-semver): The semantic version parser used by npm. 142 | - [to-markdown](https://github.com/domchristie/to-markdown): HTML-to-Markdown converter 143 | 144 | ## Dev Dependencies 145 | 146 | - [chai](https://github.com/chaijs/chai): BDD/TDD assertion library for node.js and the browser. Test framework agnostic. 147 | - [mocha](https://github.com/mochajs/mocha): simple, flexible, fun test framework 148 | - [rimraf](https://github.com/isaacs/rimraf): A deep deletion module for node (like `rm -rf`) 149 | - [standard](https://github.com/feross/standard): JavaScript Standard Style 150 | 151 | ## License 152 | 153 | MIT 154 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/crash-reporter.md: -------------------------------------------------------------------------------- 1 | # crashReporter 2 | 3 | > Submit crash reports to a remote server. 4 | 5 | Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-process) 6 | 7 | The following is an example of automatically submitting a crash report to a 8 | remote server: 9 | 10 | ```javascript 11 | const {crashReporter} = require('electron') 12 | 13 | crashReporter.start({ 14 | productName: 'YourName', 15 | companyName: 'YourCompany', 16 | submitURL: 'https://your-domain.com/url-to-submit', 17 | uploadToServer: true 18 | }) 19 | ``` 20 | 21 | For setting up a server to accept and process crash reports, you can use 22 | following projects: 23 | 24 | * [socorro](https://github.com/mozilla/socorro) 25 | * [mini-breakpad-server](https://github.com/electron/mini-breakpad-server) 26 | 27 | Crash reports are saved locally in an application-specific temp directory folder. 28 | For a `productName` of `YourName`, crash reports will be stored in a folder 29 | named `YourName Crashes` inside the temp directory. You can customize this temp 30 | directory location for your app by calling the `app.setPath('temp', '/my/custom/temp')` 31 | API before starting the crash reporter. 32 | 33 | ## Methods 34 | 35 | The `crashReporter` module has the following methods: 36 | 37 | ### `crashReporter.start(options)` 38 | 39 | * `options` Object 40 | * `companyName` String (optional) 41 | * `submitURL` String - URL that crash reports will be sent to as POST. 42 | * `productName` String (optional) - Defaults to `app.getName()`. 43 | * `uploadToServer` Boolean (optional) _macOS_ - Whether crash reports should be sent to the server 44 | Default is `true`. 45 | * `ignoreSystemCrashHandler` Boolean (optional) - Default is `false`. 46 | * `extra` Record (optional) - An object you can define that will be sent along with the 47 | report. Only string properties are sent correctly. Nested objects are not 48 | supported. 49 | 50 | You are required to call this method before using any other `crashReporter` APIs 51 | and in each process (main/renderer) from which you want to collect crash reports. 52 | You can pass different options to `crashReporter.start` when calling from different processes. 53 | 54 | **Note** Child processes created via the `child_process` module will not have access to the Electron modules. 55 | Therefore, to collect crash reports from them, use `process.crashReporter.start` instead. Pass the same options as above 56 | along with an additional one called `crashesDirectory` that should point to a directory to store the crash 57 | reports temporarily. You can test this out by calling `process.crash()` to crash the child process. 58 | 59 | **Note:** To collect crash reports from child process in Windows, you need to add this extra code as well. 60 | This will start the process that will monitor and send the crash reports. Replace `submitURL`, `productName` 61 | and `crashesDirectory` with appropriate values. 62 | 63 | **Note:** If you need send additional/updated `extra` parameters after your 64 | first call `start` you can call `setExtraParameter` on macOS or call `start` 65 | again with the new/updated `extra` parameters on Linux and Windows. 66 | 67 | ```js 68 | const args = [ 69 | `--reporter-url=${submitURL}`, 70 | `--application-name=${productName}`, 71 | `--crashes-directory=${crashesDirectory}` 72 | ] 73 | const env = { 74 | ELECTRON_INTERNAL_CRASH_SERVICE: 1 75 | } 76 | spawn(process.execPath, args, { 77 | env: env, 78 | detached: true 79 | }) 80 | ``` 81 | 82 | **Note:** On macOS, Electron uses a new `crashpad` client for crash collection and reporting. 83 | If you want to enable crash reporting, initializing `crashpad` from the main process using `crashReporter.start` is required 84 | regardless of which process you want to collect crashes from. Once initialized this way, the crashpad handler collects 85 | crashes from all processes. You still have to call `crashReporter.start` from the renderer or child process, otherwise crashes from 86 | them will get reported without `companyName`, `productName` or any of the `extra` information. 87 | 88 | ### `crashReporter.getLastCrashReport()` 89 | 90 | Returns [`CrashReport`](structures/crash-report.md): 91 | 92 | Returns the date and ID of the last crash report. If no crash reports have been 93 | sent or the crash reporter has not been started, `null` is returned. 94 | 95 | ### `crashReporter.getUploadedReports()` 96 | 97 | Returns [`CrashReport[]`](structures/crash-report.md): 98 | 99 | Returns all uploaded crash reports. Each report contains the date and uploaded 100 | ID. 101 | 102 | ### `crashReporter.getUploadToServer()` _macOS_ 103 | 104 | Returns `Boolean` - Whether reports should be submitted to the server. Set through 105 | the `start` method or `setUploadToServer`. 106 | 107 | **Note:** This API can only be called from the main process. 108 | 109 | ### `crashReporter.setUploadToServer(uploadToServer)` _macOS_ 110 | 111 | * `uploadToServer` Boolean _macOS_ - Whether reports should be submitted to the server 112 | 113 | This would normally be controlled by user preferences. This has no effect if 114 | called before `start` is called. 115 | 116 | **Note:** This API can only be called from the main process. 117 | 118 | ### `crashReporter.setExtraParameter(key, value)` _macOS_ 119 | 120 | * `key` String - Parameter key. 121 | * `value` String - Parameter value. Specifying `null` or `undefined` will 122 | remove the key from the extra parameters. 123 | 124 | Set an extra parameter to set be sent with the crash report. The values 125 | specified here will be sent in addition to any values set via the `extra` option 126 | when `start` was called. This API is only available on macOS, if you need to 127 | add/update extra parameters on Linux and Windows after your first call to 128 | `start` you can call `start` again with the updated `extra` options. 129 | 130 | ## Crash Report Payload 131 | 132 | The crash reporter will send the following data to the `submitURL` as 133 | a `multipart/form-data` `POST`: 134 | 135 | * `ver` String - The version of Electron. 136 | * `platform` String - e.g. 'win32'. 137 | * `process_type` String - e.g. 'renderer'. 138 | * `guid` String - e.g. '5e1286fc-da97-479e-918b-6bfb0c3d1c72' 139 | * `_version` String - The version in `package.json`. 140 | * `_productName` String - The product name in the `crashReporter` `options` 141 | object. 142 | * `prod` String - Name of the underlying product. In this case Electron. 143 | * `_companyName` String - The company name in the `crashReporter` `options` 144 | object. 145 | * `upload_file_minidump` File - The crash report in the format of `minidump`. 146 | * All level one properties of the `extra` object in the `crashReporter` 147 | `options` object. 148 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/remote.md: -------------------------------------------------------------------------------- 1 | # remote 2 | 3 | > Use main process modules from the renderer process. 4 | 5 | Process: [Renderer](../glossary.md#renderer-process) 6 | 7 | The `remote` module provides a simple way to do inter-process communication 8 | (IPC) between the renderer process (web page) and the main process. 9 | 10 | In Electron, GUI-related modules (such as `dialog`, `menu` etc.) are only 11 | available in the main process, not in the renderer process. In order to use them 12 | from the renderer process, the `ipc` module is necessary to send inter-process 13 | messages to the main process. With the `remote` module, you can invoke methods 14 | of the main process object without explicitly sending inter-process messages, 15 | similar to Java's [RMI][rmi]. An example of creating a browser window from a 16 | renderer process: 17 | 18 | ```javascript 19 | const {BrowserWindow} = require('electron').remote 20 | let win = new BrowserWindow({width: 800, height: 600}) 21 | win.loadURL('https://github.com') 22 | ``` 23 | 24 | **Note:** For the reverse (access the renderer process from the main process), 25 | you can use [webContents.executeJavascript](web-contents.md#contentsexecutejavascriptcode-usergesture-callback). 26 | 27 | ## Remote Objects 28 | 29 | Each object (including functions) returned by the `remote` module represents an 30 | object in the main process (we call it a remote object or remote function). 31 | When you invoke methods of a remote object, call a remote function, or create 32 | a new object with the remote constructor (function), you are actually sending 33 | synchronous inter-process messages. 34 | 35 | In the example above, both `BrowserWindow` and `win` were remote objects and 36 | `new BrowserWindow` didn't create a `BrowserWindow` object in the renderer 37 | process. Instead, it created a `BrowserWindow` object in the main process and 38 | returned the corresponding remote object in the renderer process, namely the 39 | `win` object. 40 | 41 | **Note:** Only [enumerable properties][enumerable-properties] which are present 42 | when the remote object is first referenced are accessible via remote. 43 | 44 | **Note:** Arrays and Buffers are copied over IPC when accessed via the `remote` 45 | module. Modifying them in the renderer process does not modify them in the main 46 | process and vice versa. 47 | 48 | ## Lifetime of Remote Objects 49 | 50 | Electron makes sure that as long as the remote object in the renderer process 51 | lives (in other words, has not been garbage collected), the corresponding object 52 | in the main process will not be released. When the remote object has been 53 | garbage collected, the corresponding object in the main process will be 54 | dereferenced. 55 | 56 | If the remote object is leaked in the renderer process (e.g. stored in a map but 57 | never freed), the corresponding object in the main process will also be leaked, 58 | so you should be very careful not to leak remote objects. 59 | 60 | Primary value types like strings and numbers, however, are sent by copy. 61 | 62 | ## Passing callbacks to the main process 63 | 64 | Code in the main process can accept callbacks from the renderer - for instance 65 | the `remote` module - but you should be extremely careful when using this 66 | feature. 67 | 68 | First, in order to avoid deadlocks, the callbacks passed to the main process 69 | are called asynchronously. You should not expect the main process to 70 | get the return value of the passed callbacks. 71 | 72 | For instance you can't use a function from the renderer process in an 73 | `Array.map` called in the main process: 74 | 75 | ```javascript 76 | // main process mapNumbers.js 77 | exports.withRendererCallback = (mapper) => { 78 | return [1, 2, 3].map(mapper) 79 | } 80 | 81 | exports.withLocalCallback = () => { 82 | return [1, 2, 3].map(x => x + 1) 83 | } 84 | ``` 85 | 86 | ```javascript 87 | // renderer process 88 | const mapNumbers = require('electron').remote.require('./mapNumbers') 89 | const withRendererCb = mapNumbers.withRendererCallback(x => x + 1) 90 | const withLocalCb = mapNumbers.withLocalCallback() 91 | 92 | console.log(withRendererCb, withLocalCb) 93 | // [undefined, undefined, undefined], [2, 3, 4] 94 | ``` 95 | 96 | As you can see, the renderer callback's synchronous return value was not as 97 | expected, and didn't match the return value of an identical callback that lives 98 | in the main process. 99 | 100 | Second, the callbacks passed to the main process will persist until the 101 | main process garbage-collects them. 102 | 103 | For example, the following code seems innocent at first glance. It installs a 104 | callback for the `close` event on a remote object: 105 | 106 | ```javascript 107 | require('electron').remote.getCurrentWindow().on('close', () => { 108 | // window was closed... 109 | }) 110 | ``` 111 | 112 | But remember the callback is referenced by the main process until you 113 | explicitly uninstall it. If you do not, each time you reload your window the 114 | callback will be installed again, leaking one callback for each restart. 115 | 116 | To make things worse, since the context of previously installed callbacks has 117 | been released, exceptions will be raised in the main process when the `close` 118 | event is emitted. 119 | 120 | To avoid this problem, ensure you clean up any references to renderer callbacks 121 | passed to the main process. This involves cleaning up event handlers, or 122 | ensuring the main process is explicitly told to deference callbacks that came 123 | from a renderer process that is exiting. 124 | 125 | ## Accessing built-in modules in the main process 126 | 127 | The built-in modules in the main process are added as getters in the `remote` 128 | module, so you can use them directly like the `electron` module. 129 | 130 | ```javascript 131 | const app = require('electron').remote.app 132 | console.log(app) 133 | ``` 134 | 135 | ## Methods 136 | 137 | The `remote` module has the following methods: 138 | 139 | ### `remote.require(module)` 140 | 141 | * `module` String 142 | 143 | Returns `any` - The object returned by `require(module)` in the main process. 144 | 145 | ### `remote.getCurrentWindow()` 146 | 147 | Returns [`BrowserWindow`](browser-window.md) - The window to which this web page 148 | belongs. 149 | 150 | ### `remote.getCurrentWebContents()` 151 | 152 | Returns [`WebContents`](web-contents.md) - The web contents of this web page. 153 | 154 | ### `remote.getGlobal(name)` 155 | 156 | * `name` String 157 | 158 | Returns `any` - The global variable of `name` (e.g. `global[name]`) in the main 159 | process. 160 | 161 | ## Properties 162 | 163 | ### `remote.process` 164 | 165 | The `process` object in the main process. This is the same as 166 | `remote.getGlobal('process')` but is cached. 167 | 168 | [rmi]: http://en.wikipedia.org/wiki/Java_remote_method_invocation 169 | [enumerable-properties]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties 170 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/web-request.md: -------------------------------------------------------------------------------- 1 | ## Class: WebRequest 2 | 3 | > Intercept and modify the contents of a request at various stages of its lifetime. 4 | 5 | Process: [Main](../glossary.md#main-process) 6 | 7 | Instances of the `WebRequest` class are accessed by using the `webRequest` 8 | property of a `Session`. 9 | 10 | The methods of `WebRequest` accept an optional `filter` and a `listener`. The 11 | `listener` will be called with `listener(details)` when the API's event has 12 | happened. The `details` object describes the request. Passing `null` 13 | as `listener` will unsubscribe from the event. 14 | 15 | The `filter` object has a `urls` property which is an Array of URL 16 | patterns that will be used to filter out the requests that do not match the URL 17 | patterns. If the `filter` is omitted then all requests will be matched. 18 | 19 | For certain events the `listener` is passed with a `callback`, which should be 20 | called with a `response` object when `listener` has done its work. 21 | 22 | An example of adding `User-Agent` header for requests: 23 | 24 | ```javascript 25 | const {session} = require('electron') 26 | 27 | // Modify the user agent for all requests to the following urls. 28 | const filter = { 29 | urls: ['https://*.github.com/*', '*://electron.github.io'] 30 | } 31 | 32 | session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => { 33 | details.requestHeaders['User-Agent'] = 'MyAgent' 34 | callback({cancel: false, requestHeaders: details.requestHeaders}) 35 | }) 36 | ``` 37 | 38 | ### Instance Methods 39 | 40 | The following methods are available on instances of `WebRequest`: 41 | 42 | #### `webRequest.onBeforeRequest([filter, ]listener)` 43 | 44 | * `filter` Object 45 | * `listener` Function 46 | * `details` Object 47 | * `id` Integer 48 | * `url` String 49 | * `method` String 50 | * `resourceType` String 51 | * `timestamp` Double 52 | * `uploadData` [UploadData[]](structures/upload-data.md) 53 | * `callback` Function 54 | * `response` Object 55 | * `cancel` Boolean (optional) 56 | * `redirectURL` String (optional) - The original request is prevented from 57 | being sent or completed and is instead redirected to the given URL. 58 | 59 | The `listener` will be called with `listener(details, callback)` when a request 60 | is about to occur. 61 | 62 | The `uploadData` is an array of `UploadData` objects. 63 | 64 | The `callback` has to be called with an `response` object. 65 | 66 | #### `webRequest.onBeforeSendHeaders([filter, ]listener)` 67 | 68 | * `filter` Object 69 | * `listener` Function 70 | 71 | The `listener` will be called with `listener(details, callback)` before sending 72 | an HTTP request, once the request headers are available. This may occur after a 73 | TCP connection is made to the server, but before any http data is sent. 74 | 75 | * `details` Object 76 | * `id` Integer 77 | * `url` String 78 | * `method` String 79 | * `resourceType` String 80 | * `timestamp` Double 81 | * `requestHeaders` Object 82 | * `callback` Function 83 | * `response` Object 84 | * `cancel` Boolean (optional) 85 | * `requestHeaders` Object (optional) - When provided, request will be made 86 | with these headers. 87 | 88 | The `callback` has to be called with an `response` object. 89 | 90 | #### `webRequest.onSendHeaders([filter, ]listener)` 91 | 92 | * `filter` Object 93 | * `listener` Function 94 | * `details` Object 95 | * `id` Integer 96 | * `url` String 97 | * `method` String 98 | * `resourceType` String 99 | * `timestamp` Double 100 | * `requestHeaders` Object 101 | 102 | The `listener` will be called with `listener(details)` just before a request is 103 | going to be sent to the server, modifications of previous `onBeforeSendHeaders` 104 | response are visible by the time this listener is fired. 105 | 106 | #### `webRequest.onHeadersReceived([filter, ]listener)` 107 | 108 | * `filter` Object 109 | * `listener` Function 110 | 111 | The `listener` will be called with `listener(details, callback)` when HTTP 112 | response headers of a request have been received. 113 | 114 | * `details` Object 115 | * `id` String 116 | * `url` String 117 | * `method` String 118 | * `resourceType` String 119 | * `timestamp` Double 120 | * `statusLine` String 121 | * `statusCode` Integer 122 | * `responseHeaders` Object 123 | * `callback` Function 124 | * `response` Object 125 | * `cancel` Boolean 126 | * `responseHeaders` Object (optional) - When provided, the server is assumed 127 | to have responded with these headers. 128 | * `statusLine` String (optional) - Should be provided when overriding 129 | `responseHeaders` to change header status otherwise original response 130 | header's status will be used. 131 | 132 | The `callback` has to be called with an `response` object. 133 | 134 | #### `webRequest.onResponseStarted([filter, ]listener)` 135 | 136 | * `filter` Object 137 | * `listener` Function 138 | * `details` Object 139 | * `id` Integer 140 | * `url` String 141 | * `method` String 142 | * `resourceType` String 143 | * `timestamp` Double 144 | * `responseHeaders` Object 145 | * `fromCache` Boolean - Indicates whether the response was fetched from disk 146 | cache. 147 | * `statusCode` Integer 148 | * `statusLine` String 149 | 150 | The `listener` will be called with `listener(details)` when first byte of the 151 | response body is received. For HTTP requests, this means that the status line 152 | and response headers are available. 153 | 154 | #### `webRequest.onBeforeRedirect([filter, ]listener)` 155 | 156 | * `filter` Object 157 | * `listener` Function 158 | * `details` Object 159 | * `id` String 160 | * `url` String 161 | * `method` String 162 | * `resourceType` String 163 | * `timestamp` Double 164 | * `redirectURL` String 165 | * `statusCode` Integer 166 | * `ip` String (optional) - The server IP address that the request was 167 | actually sent to. 168 | * `fromCache` Boolean 169 | * `responseHeaders` Object 170 | 171 | The `listener` will be called with `listener(details)` when a server initiated 172 | redirect is about to occur. 173 | 174 | #### `webRequest.onCompleted([filter, ]listener)` 175 | 176 | * `filter` Object 177 | * `listener` Function 178 | * `details` Object 179 | * `id` Integer 180 | * `url` String 181 | * `method` String 182 | * `resourceType` String 183 | * `timestamp` Double 184 | * `responseHeaders` Object 185 | * `fromCache` Boolean 186 | * `statusCode` Integer 187 | * `statusLine` String 188 | 189 | The `listener` will be called with `listener(details)` when a request is 190 | completed. 191 | 192 | #### `webRequest.onErrorOccurred([filter, ]listener)` 193 | 194 | * `filter` Object 195 | * `listener` Function 196 | * `details` Object 197 | * `id` Integer 198 | * `url` String 199 | * `method` String 200 | * `resourceType` String 201 | * `timestamp` Double 202 | * `fromCache` Boolean 203 | * `error` String - The error description. 204 | 205 | The `listener` will be called with `listener(details)` when an error occurs. 206 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/tray.md: -------------------------------------------------------------------------------- 1 | ## Class: Tray 2 | 3 | > Add icons and context menus to the system's notification area. 4 | 5 | Process: [Main](../glossary.md#main-process) 6 | 7 | `Tray` is an [EventEmitter][event-emitter]. 8 | 9 | ```javascript 10 | const {app, Menu, Tray} = require('electron') 11 | 12 | let tray = null 13 | app.on('ready', () => { 14 | tray = new Tray('/path/to/my/icon') 15 | const contextMenu = Menu.buildFromTemplate([ 16 | {label: 'Item1', type: 'radio'}, 17 | {label: 'Item2', type: 'radio'}, 18 | {label: 'Item3', type: 'radio', checked: true}, 19 | {label: 'Item4', type: 'radio'} 20 | ]) 21 | tray.setToolTip('This is my application.') 22 | tray.setContextMenu(contextMenu) 23 | }) 24 | ``` 25 | 26 | __Platform limitations:__ 27 | 28 | * On Linux the app indicator will be used if it is supported, otherwise 29 | `GtkStatusIcon` will be used instead. 30 | * On Linux distributions that only have app indicator support, you have to 31 | install `libappindicator1` to make the tray icon work. 32 | * App indicator will only be shown when it has a context menu. 33 | * When app indicator is used on Linux, the `click` event is ignored. 34 | * On Linux in order for changes made to individual `MenuItem`s to take effect, 35 | you have to call `setContextMenu` again. For example: 36 | 37 | ```javascript 38 | const {app, Menu, Tray} = require('electron') 39 | 40 | let appIcon = null 41 | app.on('ready', () => { 42 | appIcon = new Tray('/path/to/my/icon') 43 | const contextMenu = Menu.buildFromTemplate([ 44 | {label: 'Item1', type: 'radio'}, 45 | {label: 'Item2', type: 'radio'} 46 | ]) 47 | 48 | // Make a change to the context menu 49 | contextMenu.items[1].checked = false 50 | 51 | // Call this again for Linux because we modified the context menu 52 | appIcon.setContextMenu(contextMenu) 53 | }) 54 | ``` 55 | * On Windows it is recommended to use `ICO` icons to get best visual effects. 56 | 57 | If you want to keep exact same behaviors on all platforms, you should not 58 | rely on the `click` event and always attach a context menu to the tray icon. 59 | 60 | 61 | ### `new Tray(image)` 62 | 63 | * `image` ([NativeImage](native-image.md) | String) 64 | 65 | Creates a new tray icon associated with the `image`. 66 | 67 | ### Instance Events 68 | 69 | The `Tray` module emits the following events: 70 | 71 | #### Event: 'click' 72 | 73 | * `event` Event 74 | * `altKey` Boolean 75 | * `shiftKey` Boolean 76 | * `ctrlKey` Boolean 77 | * `metaKey` Boolean 78 | * `bounds` [Rectangle](structures/rectangle.md) - The bounds of tray icon 79 | 80 | Emitted when the tray icon is clicked. 81 | 82 | #### Event: 'right-click' _macOS_ _Windows_ 83 | 84 | * `event` Event 85 | * `altKey` Boolean 86 | * `shiftKey` Boolean 87 | * `ctrlKey` Boolean 88 | * `metaKey` Boolean 89 | * `bounds` [Rectangle](structures/rectangle.md) - The bounds of tray icon 90 | 91 | Emitted when the tray icon is right clicked. 92 | 93 | #### Event: 'double-click' _macOS_ _Windows_ 94 | 95 | * `event` Event 96 | * `altKey` Boolean 97 | * `shiftKey` Boolean 98 | * `ctrlKey` Boolean 99 | * `metaKey` Boolean 100 | * `bounds` [Rectangle](structures/rectangle.md) - The bounds of tray icon 101 | 102 | Emitted when the tray icon is double clicked. 103 | 104 | #### Event: 'balloon-show' _Windows_ 105 | 106 | Emitted when the tray balloon shows. 107 | 108 | #### Event: 'balloon-click' _Windows_ 109 | 110 | Emitted when the tray balloon is clicked. 111 | 112 | #### Event: 'balloon-closed' _Windows_ 113 | 114 | Emitted when the tray balloon is closed because of timeout or user manually 115 | closes it. 116 | 117 | #### Event: 'drop' _macOS_ 118 | 119 | Emitted when any dragged items are dropped on the tray icon. 120 | 121 | #### Event: 'drop-files' _macOS_ 122 | 123 | * `event` Event 124 | * `files` String[] - The paths of the dropped files. 125 | 126 | Emitted when dragged files are dropped in the tray icon. 127 | 128 | #### Event: 'drop-text' _macOS_ 129 | 130 | * `event` Event 131 | * `text` String - the dropped text string 132 | 133 | Emitted when dragged text is dropped in the tray icon. 134 | 135 | #### Event: 'drag-enter' _macOS_ 136 | 137 | Emitted when a drag operation enters the tray icon. 138 | 139 | #### Event: 'drag-leave' _macOS_ 140 | 141 | Emitted when a drag operation exits the tray icon. 142 | 143 | #### Event: 'drag-end' _macOS_ 144 | 145 | Emitted when a drag operation ends on the tray or ends at another location. 146 | 147 | ### Instance Methods 148 | 149 | The `Tray` class has the following methods: 150 | 151 | #### `tray.destroy()` 152 | 153 | Destroys the tray icon immediately. 154 | 155 | #### `tray.setImage(image)` 156 | 157 | * `image` ([NativeImage](native-image.md) | String) 158 | 159 | Sets the `image` associated with this tray icon. 160 | 161 | #### `tray.setPressedImage(image)` _macOS_ 162 | 163 | * `image` [NativeImage](native-image.md) 164 | 165 | Sets the `image` associated with this tray icon when pressed on macOS. 166 | 167 | #### `tray.setToolTip(toolTip)` 168 | 169 | * `toolTip` String 170 | 171 | Sets the hover text for this tray icon. 172 | 173 | #### `tray.setTitle(title)` _macOS_ 174 | 175 | * `title` String 176 | 177 | Sets the title displayed aside of the tray icon in the status bar. 178 | 179 | #### `tray.setHighlightMode(mode)` _macOS_ 180 | 181 | * `mode` String - Highlight mode with one of the following values: 182 | * `selection` - Highlight the tray icon when it is clicked and also when 183 | its context menu is open. This is the default. 184 | * `always` - Always highlight the tray icon. 185 | * `never` - Never highlight the tray icon. 186 | 187 | Sets when the tray's icon background becomes highlighted (in blue). 188 | 189 | **Note:** You can use `highlightMode` with a [`BrowserWindow`](browser-window.md) 190 | by toggling between `'never'` and `'always'` modes when the window visibility 191 | changes. 192 | 193 | ```javascript 194 | const {BrowserWindow, Tray} = require('electron') 195 | 196 | const win = new BrowserWindow({width: 800, height: 600}) 197 | const tray = new Tray('/path/to/my/icon') 198 | 199 | tray.on('click', () => { 200 | win.isVisible() ? win.hide() : win.show() 201 | }) 202 | win.on('show', () => { 203 | tray.setHighlightMode('always') 204 | }) 205 | win.on('hide', () => { 206 | tray.setHighlightMode('never') 207 | }) 208 | ``` 209 | 210 | #### `tray.displayBalloon(options)` _Windows_ 211 | 212 | * `options` Object 213 | * `icon` ([NativeImage](native-image.md) | String) - (optional) 214 | * `title` String - (optional) 215 | * `content` String - (optional) 216 | 217 | Displays a tray balloon. 218 | 219 | #### `tray.popUpContextMenu([menu, position])` _macOS_ _Windows_ 220 | 221 | * `menu` Menu (optional) 222 | * `position` Object (optional) - The pop up position. 223 | * `x` Integer 224 | * `y` Integer 225 | 226 | Pops up the context menu of the tray icon. When `menu` is passed, the `menu` will 227 | be shown instead of the tray icon's context menu. 228 | 229 | The `position` is only available on Windows, and it is (0, 0) by default. 230 | 231 | #### `tray.setContextMenu(menu)` 232 | 233 | * `menu` Menu 234 | 235 | Sets the context menu for this icon. 236 | 237 | #### `tray.getBounds()` _macOS_ _Windows_ 238 | 239 | Returns [`Rectangle`](structures/rectangle.md) 240 | 241 | The `bounds` of this tray icon as `Object`. 242 | 243 | #### `tray.isDestroyed()` 244 | 245 | Returns `Boolean` - Whether the tray icon is destroyed. 246 | 247 | [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter 248 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/client-request.md: -------------------------------------------------------------------------------- 1 | ## Class: ClientRequest 2 | 3 | > Make HTTP/HTTPS requests. 4 | 5 | Process: [Main](../glossary.md#main-process) 6 | 7 | `ClientRequest` implements the [Writable Stream](https://nodejs.org/api/stream.html#stream_writable_streams) 8 | interface and is therefore an [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter). 9 | 10 | ### `new ClientRequest(options)` 11 | 12 | * `options` (Object | String) - If `options` is a String, it is interpreted as 13 | the request URL. If it is an object, it is expected to fully specify an HTTP request via the 14 | following properties: 15 | * `method` String (optional) - The HTTP request method. Defaults to the GET 16 | method. 17 | * `url` String (optional) - The request URL. Must be provided in the absolute 18 | form with the protocol scheme specified as http or https. 19 | * `session` Object (optional) - The [`Session`](session.md) instance with 20 | which the request is associated. 21 | * `partition` String (optional) - The name of the [`partition`](session.md) 22 | with which the request is associated. Defaults to the empty string. The 23 | `session` option prevails on `partition`. Thus if a `session` is explicitly 24 | specified, `partition` is ignored. 25 | * `protocol` String (optional) - The protocol scheme in the form 'scheme:'. 26 | Currently supported values are 'http:' or 'https:'. Defaults to 'http:'. 27 | * `host` String (optional) - The server host provided as a concatenation of 28 | the hostname and the port number 'hostname:port' 29 | * `hostname` String (optional) - The server host name. 30 | * `port` Integer (optional) - The server's listening port number. 31 | * `path` String (optional) - The path part of the request URL. 32 | 33 | `options` properties such as `protocol`, `host`, `hostname`, `port` and `path` 34 | strictly follow the Node.js model as described in the 35 | [URL](https://nodejs.org/api/url.html) module. 36 | 37 | For instance, we could have created the same request to 'github.com' as follows: 38 | 39 | ```JavaScript 40 | const request = net.request({ 41 | method: 'GET', 42 | protocol: 'https:', 43 | hostname: 'github.com', 44 | port: 443, 45 | path: '/' 46 | }) 47 | ``` 48 | 49 | ### Instance Events 50 | 51 | #### Event: 'response' 52 | 53 | Returns: 54 | 55 | * `response` IncomingMessage - An object representing the HTTP response message. 56 | 57 | #### Event: 'login' 58 | 59 | Returns: 60 | 61 | * `authInfo` Object 62 | * `isProxy` Boolean 63 | * `scheme` String 64 | * `host` String 65 | * `port` Integer 66 | * `realm` String 67 | * `callback` Function 68 | 69 | Emitted when an authenticating proxy is asking for user credentials. 70 | 71 | The `callback` function is expected to be called back with user credentials: 72 | 73 | * `username` String 74 | * `password` String 75 | 76 | ```JavaScript 77 | request.on('login', (authInfo, callback) => { 78 | callback('username', 'password') 79 | }) 80 | ``` 81 | Providing empty credentials will cancel the request and report an authentication 82 | error on the response object: 83 | 84 | ```JavaScript 85 | request.on('response', (response) => { 86 | console.log(`STATUS: ${response.statusCode}`); 87 | response.on('error', (error) => { 88 | console.log(`ERROR: ${JSON.stringify(error)}`) 89 | }) 90 | }) 91 | request.on('login', (authInfo, callback) => { 92 | callback() 93 | }) 94 | ``` 95 | 96 | #### Event: 'finish' 97 | 98 | Emitted just after the last chunk of the `request`'s data has been written into 99 | the `request` object. 100 | 101 | #### Event: 'abort' 102 | 103 | Emitted when the `request` is aborted. The `abort` event will not be fired if 104 | the `request` is already closed. 105 | 106 | #### Event: 'error' 107 | 108 | Returns: 109 | 110 | * `error` Error - an error object providing some information about the failure. 111 | 112 | Emitted when the `net` module fails to issue a network request. Typically when 113 | the `request` object emits an `error` event, a `close` event will subsequently 114 | follow and no response object will be provided. 115 | 116 | #### Event: 'close' 117 | 118 | Emitted as the last event in the HTTP request-response transaction. The `close` 119 | event indicates that no more events will be emitted on either the `request` or 120 | `response` objects. 121 | 122 | ### Instance Properties 123 | 124 | #### `request.chunkedEncoding` 125 | 126 | A Boolean specifying whether the request will use HTTP chunked transfer encoding 127 | or not. Defaults to false. The property is readable and writable, however it can 128 | be set only before the first write operation as the HTTP headers are not yet put 129 | on the wire. Trying to set the `chunkedEncoding` property after the first write 130 | will throw an error. 131 | 132 | Using chunked encoding is strongly recommended if you need to send a large 133 | request body as data will be streamed in small chunks instead of being 134 | internally buffered inside Electron process memory. 135 | 136 | ### Instance Methods 137 | 138 | #### `request.setHeader(name, value)` 139 | 140 | * `name` String - An extra HTTP header name. 141 | * `value` String - An extra HTTP header value. 142 | 143 | Adds an extra HTTP header. The header name will issued as it is without 144 | lowercasing. It can be called only before first write. Calling this method after 145 | the first write will throw an error. 146 | 147 | #### `request.getHeader(name)` 148 | 149 | * `name` String - Specify an extra header name. 150 | 151 | Returns String - The value of a previously set extra header name. 152 | 153 | #### `request.removeHeader(name)` 154 | 155 | * `name` String - Specify an extra header name. 156 | 157 | Removes a previously set extra header name. This method can be called only 158 | before first write. Trying to call it after the first write will throw an error. 159 | 160 | #### `request.write(chunk[, encoding][, callback])` 161 | 162 | * `chunk` (String | Buffer) - A chunk of the request body's data. If it is a 163 | string, it is converted into a Buffer using the specified encoding. 164 | * `encoding` String (optional) - Used to convert string chunks into Buffer 165 | objects. Defaults to 'utf-8'. 166 | * `callback` Function (optional) - Called after the write operation ends. 167 | 168 | `callback` is essentially a dummy function introduced in the purpose of keeping 169 | similarity with the Node.js API. It is called asynchronously in the next tick 170 | after `chunk` content have been delivered to the Chromium networking layer. 171 | Contrary to the Node.js implementation, it is not guaranteed that `chunk` 172 | content have been flushed on the wire before `callback` is called. 173 | 174 | Adds a chunk of data to the request body. The first write operation may cause 175 | the request headers to be issued on the wire. After the first write operation, 176 | it is not allowed to add or remove a custom header. 177 | 178 | #### `request.end([chunk][, encoding][, callback])` 179 | 180 | * `chunk` (String | Buffer) (optional) 181 | * `encoding` String (optional) 182 | * `callback` Function (optional) 183 | 184 | Sends the last chunk of the request data. Subsequent write or end operations 185 | will not be allowed. The `finish` event is emitted just after the end operation. 186 | 187 | #### `request.abort()` 188 | 189 | Cancels an ongoing HTTP transaction. If the request has already emitted the 190 | `close` event, the abort operation will have no effect. Otherwise an ongoing 191 | event will emit `abort` and `close` events. Additionally, if there is an ongoing 192 | response object,it will emit the `aborted` event. 193 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/native-image.md: -------------------------------------------------------------------------------- 1 | # nativeImage 2 | 3 | > Create tray, dock, and application icons using PNG or JPG files. 4 | 5 | Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-process) 6 | 7 | In Electron, for the APIs that take images, you can pass either file paths or 8 | `NativeImage` instances. An empty image will be used when `null` is passed. 9 | 10 | For example, when creating a tray or setting a window's icon, you can pass an 11 | image file path as a `String`: 12 | 13 | ```javascript 14 | const {BrowserWindow, Tray} = require('electron') 15 | 16 | const appIcon = new Tray('/Users/somebody/images/icon.png') 17 | let win = new BrowserWindow({icon: '/Users/somebody/images/window.png'}) 18 | console.log(appIcon, win) 19 | ``` 20 | 21 | Or read the image from the clipboard which returns a `NativeImage`: 22 | 23 | ```javascript 24 | const {clipboard, Tray} = require('electron') 25 | const image = clipboard.readImage() 26 | const appIcon = new Tray(image) 27 | console.log(appIcon) 28 | ``` 29 | 30 | ## Supported Formats 31 | 32 | Currently `PNG` and `JPEG` image formats are supported. `PNG` is recommended 33 | because of its support for transparency and lossless compression. 34 | 35 | On Windows, you can also load `ICO` icons from file paths. For best visual 36 | quality it is recommended to include at least the following sizes in the: 37 | 38 | * Small icon 39 | * 16x16 (100% DPI scale) 40 | * 20x20 (125% DPI scale) 41 | * 24x24 (150% DPI scale) 42 | * 32x32 (200% DPI scale) 43 | * Large icon 44 | * 32x32 (100% DPI scale) 45 | * 40x40 (125% DPI scale) 46 | * 48x48 (150% DPI scale) 47 | * 64x64 (200% DPI scale) 48 | * 256x256 49 | 50 | Check the *Size requirements* section in [this article][icons]. 51 | 52 | [icons]:https://msdn.microsoft.com/en-us/library/windows/desktop/dn742485(v=vs.85).aspx 53 | 54 | ## High Resolution Image 55 | 56 | On platforms that have high-DPI support such as Apple Retina displays, you can 57 | append `@2x` after image's base filename to mark it as a high resolution image. 58 | 59 | For example if `icon.png` is a normal image that has standard resolution, then 60 | `icon@2x.png` will be treated as a high resolution image that has double DPI 61 | density. 62 | 63 | If you want to support displays with different DPI densities at the same time, 64 | you can put images with different sizes in the same folder and use the filename 65 | without DPI suffixes. For example: 66 | 67 | ```text 68 | images/ 69 | ├── icon.png 70 | ├── icon@2x.png 71 | └── icon@3x.png 72 | ``` 73 | 74 | 75 | ```javascript 76 | const {Tray} = require('electron') 77 | let appIcon = new Tray('/Users/somebody/images/icon.png') 78 | console.log(appIcon) 79 | ``` 80 | 81 | Following suffixes for DPI are also supported: 82 | 83 | * `@1x` 84 | * `@1.25x` 85 | * `@1.33x` 86 | * `@1.4x` 87 | * `@1.5x` 88 | * `@1.8x` 89 | * `@2x` 90 | * `@2.5x` 91 | * `@3x` 92 | * `@4x` 93 | * `@5x` 94 | 95 | ## Template Image 96 | 97 | Template images consist of black and clear colors (and an alpha channel). 98 | Template images are not intended to be used as standalone images and are usually 99 | mixed with other content to create the desired final appearance. 100 | 101 | The most common case is to use template images for a menu bar icon so it can 102 | adapt to both light and dark menu bars. 103 | 104 | **Note:** Template image is only supported on macOS. 105 | 106 | To mark an image as a template image, its filename should end with the word 107 | `Template`. For example: 108 | 109 | * `xxxTemplate.png` 110 | * `xxxTemplate@2x.png` 111 | 112 | ## Methods 113 | 114 | The `nativeImage` module has the following methods, all of which return 115 | an instance of the `NativeImage` class: 116 | 117 | ### `nativeImage.createEmpty()` 118 | 119 | Returns `NativeImage` 120 | 121 | Creates an empty `NativeImage` instance. 122 | 123 | ### `nativeImage.createFromPath(path)` 124 | 125 | * `path` String 126 | 127 | Returns `NativeImage` 128 | 129 | Creates a new `NativeImage` instance from a file located at `path`. This method 130 | returns an empty image if the `path` does not exist, cannot be read, or is not 131 | a valid image. 132 | 133 | ```javascript 134 | const nativeImage = require('electron').nativeImage 135 | 136 | let image = nativeImage.createFromPath('/Users/somebody/images/icon.png') 137 | console.log(image) 138 | ``` 139 | 140 | ### `nativeImage.createFromBuffer(buffer[, options])` 141 | 142 | * `buffer` [Buffer][buffer] 143 | * `options` Object (optional) 144 | * `width` Integer (optional) - Required for bitmap buffers. 145 | * `height` Integer (optional) - Required for bitmap buffers. 146 | * `scaleFactor` Double (optional) - Defaults to 1.0. 147 | 148 | Returns `NativeImage` 149 | 150 | Creates a new `NativeImage` instance from `buffer`. 151 | 152 | ### `nativeImage.createFromDataURL(dataURL)` 153 | 154 | * `dataURL` String 155 | 156 | Creates a new `NativeImage` instance from `dataURL`. 157 | 158 | ## Class: NativeImage 159 | 160 | > Natively wrap images such as tray, dock, and application icons. 161 | 162 | Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-process) 163 | 164 | ### Instance Methods 165 | 166 | The following methods are available on instances of the `NativeImage` class: 167 | 168 | #### `image.toPNG()` 169 | 170 | Returns `Buffer` - A [Buffer][buffer] that contains the image's `PNG` encoded data. 171 | 172 | #### `image.toJPEG(quality)` 173 | 174 | * `quality` Integer (**required**) - Between 0 - 100. 175 | 176 | Returns `Buffer` - A [Buffer][buffer] that contains the image's `JPEG` encoded data. 177 | 178 | #### `image.toBitmap()` 179 | 180 | Returns `Buffer` - A [Buffer][buffer] that contains a copy of the image's raw bitmap pixel 181 | data. 182 | 183 | #### `image.toDataURL()` 184 | 185 | Returns `String` - The data URL of the image. 186 | 187 | #### `image.getBitmap()` 188 | 189 | Returns `Buffer` - A [Buffer][buffer] that contains the image's raw bitmap pixel data. 190 | 191 | The difference between `getBitmap()` and `toBitmap()` is, `getBitmap()` does not 192 | copy the bitmap data, so you have to use the returned Buffer immediately in 193 | current event loop tick, otherwise the data might be changed or destroyed. 194 | 195 | #### `image.getNativeHandle()` _macOS_ 196 | 197 | Returns `Buffer` - A [Buffer][buffer] that stores C pointer to underlying native handle of 198 | the image. On macOS, a pointer to `NSImage` instance would be returned. 199 | 200 | Notice that the returned pointer is a weak pointer to the underlying native 201 | image instead of a copy, so you _must_ ensure that the associated 202 | `nativeImage` instance is kept around. 203 | 204 | #### `image.isEmpty()` 205 | 206 | Returns `Boolean` - Whether the image is empty. 207 | 208 | #### `image.getSize()` 209 | 210 | Returns `Object`: 211 | 212 | * `width` Integer 213 | * `height` Integer 214 | 215 | #### `image.setTemplateImage(option)` 216 | 217 | * `option` Boolean 218 | 219 | Marks the image as a template image. 220 | 221 | #### `image.isTemplateImage()` 222 | 223 | Returns `Boolean` - Whether the image is a template image. 224 | 225 | #### `image.crop(rect)` 226 | 227 | * `rect` Object - The area of the image to crop 228 | * `x` Integer 229 | * `y` Integer 230 | * `width` Integer 231 | * `height` Integer 232 | 233 | Returns `NativeImage` - The cropped image. 234 | 235 | #### `image.resize(options)` 236 | 237 | * `options` Object 238 | * `width` Integer (optional) 239 | * `height` Integer (optional) 240 | * `quality` String (optional) - The desired quality of the resize image. 241 | Possible values are `good`, `better` or `best`. The default is `best`. 242 | These values express a desired quality/speed tradeoff. They are translated 243 | into an algorithm-specific method that depends on the capabilities 244 | (CPU, GPU) of the underlying platform. It is possible for all three methods 245 | to be mapped to the same algorithm on a given platform. 246 | 247 | Returns `NativeImage` - The resized image. 248 | 249 | If only the `height` or the `width` are specified then the current aspect ratio 250 | will be preserved in the resized image. 251 | 252 | #### `image.getAspectRatio()` 253 | 254 | Returns `Float` - The image's aspect ratio. 255 | 256 | [buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer 257 | -------------------------------------------------------------------------------- /lib/api.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const decamelize = require('decamelize') 4 | const marky = require('marky-markdown-lite') 5 | const cleanDeep = require('clean-deep') 6 | const pick = require('lodash.pick') 7 | const revalidator = require('revalidator') 8 | const schemata = require('./schemata') 9 | const parsers = require('./parsers') 10 | const Collection = require('./collection') 11 | 12 | class API { 13 | constructor (props, docs) { 14 | Object.assign(this, props) 15 | this.slug = this.parseSlug() 16 | this.websiteUrl = `http://electronjs.org/docs/api/${props.structure ? 'structures/' : ''}${this.slug}` 17 | this.repoUrl = `https://github.com/electron/electron/blob/v${this.version}/docs/api/${props.structure ? 'structures/' : ''}${this.slug}.md` 18 | this.type = this.parseType(props) 19 | this.parseDoc(docs) 20 | this.description = this.parseDescription() 21 | this.process = this.parseProcesses() 22 | 23 | if (this.type === 'Module') { 24 | const subObjects = {} 25 | const makeSubObject = (name) => { 26 | if (!subObjects[name]) { 27 | subObjects[name] = { 28 | name, 29 | type: 'Object', 30 | required: true, 31 | properties: [] 32 | } 33 | } 34 | return subObjects[name] 35 | } 36 | this.events = new Collection('Event', this, '#events', 2) 37 | this.properties = new Collection('Property', this, `#properties`, 2).filter(prop => { 38 | if (!prop._superObject) return true 39 | const obj = makeSubObject(prop._superObject) 40 | obj.properties.push(prop) 41 | return false 42 | }) 43 | this.methods = new Collection('Method', this, '#methods', 2).filter(method => { 44 | if (!method._superObject) return true 45 | const obj = makeSubObject(method._superObject) 46 | method.type = 'Function' 47 | method.props.pop(method.props.length - 1) 48 | method.props.push('type') 49 | obj.properties.push(method) 50 | return false 51 | }) 52 | Object.keys(subObjects).forEach(subPropKey => this.properties.push(subObjects[subPropKey])) 53 | } 54 | 55 | if (this.type === 'Class') { 56 | this.instanceEvents = new Collection('Event', this, `h3#instance-events`, 3) 57 | this.instanceMethods = new Collection('Method', this, `h3#instance-methods`, 3) 58 | this.instanceProperties = new Collection('Property', this, `h3#instance-properties`, 3) 59 | this.staticMethods = new Collection('Method', this, `h3#static-methods`, 3) 60 | this.constructorMethod = this.parseConstructor() 61 | this.instanceName = this.parseInstanceName() 62 | } 63 | 64 | if (this.type === 'Element') { 65 | this.methods = new Collection('Method', this, `h2#methods`, 2) 66 | this.attributes = new Collection('Attribute', this, `h2#tag-attributes`, 2) 67 | this.domEvents = new Collection('Event', this, 'h2#dom-events', 2) 68 | } 69 | 70 | if (this.type === 'Structure') { 71 | this.properties = parsers.generateObjectProps(this.$, this.$('ul').first(), this) 72 | 73 | if (this.moduleLevelHeading) { 74 | const extendsMatch = this.moduleLevelHeading.match(/.+extends `(.+?)`/) 75 | if (extendsMatch) { 76 | this.extends = extendsMatch[1] 77 | } 78 | } 79 | } 80 | } 81 | 82 | get valid () { 83 | return this.validSchema && this.collectionErrors.length === 0 84 | } 85 | 86 | get validateSchema () { 87 | return revalidator.validate(this, schemata[this.type]) 88 | } 89 | 90 | get validSchema () { 91 | return this.validateSchema.valid 92 | } 93 | 94 | get validationErrors () { 95 | if (this.validSchema) return [] 96 | return this.validateSchema.errors.map(error => `${error.property} ${error.message}`) 97 | } 98 | 99 | // Check that each collection includes the same number of valid items 100 | // as there are headings in the source document. If number does not match, 101 | // then some items in the collection failed to parse properly 102 | get collectionErrors () { 103 | // return cached errors if they were already computed 104 | if (this._collectionErrors) return this._collectionErrors 105 | 106 | var errors = [] 107 | Collection.types.forEach(collection => { 108 | if (!this.expectedCounts) return 109 | const expected = this.expectedCounts[collection] 110 | const actual = this[collection] ? this[collection].length : 0 111 | if (expected && expected > actual) { 112 | const names = this[collection].map(item => item.name).join(', ') 113 | errors.push(`expected ${expected} ${collection} but only found ${actual}: ${names}`) 114 | } 115 | }) 116 | 117 | // cache the result to avoid excess computation 118 | this._collectionErrors = errors 119 | return errors 120 | } 121 | 122 | report () { 123 | if (this.valid) return `✓ ${this.name}` 124 | 125 | var errors = this.validationErrors.concat(this.collectionErrors) 126 | return `✘ ${this.name}\n${errors.map(e => ` - ${e}`)}` 127 | } 128 | 129 | inspect () { 130 | return this.toJSON() 131 | } 132 | 133 | toJSON () { 134 | var props = [ 135 | 'name', 136 | 'description', 137 | 'process', 138 | 'version', 139 | 'type', 140 | 'slug', 141 | 'websiteUrl', 142 | 'repoUrl', 143 | 'methods', 144 | 'events', 145 | 'staticMethods', 146 | 'staticProperties', 147 | 'constructorMethod', 148 | 'instanceName', 149 | 'instanceMethods', 150 | 'instanceProperties', 151 | 'instanceEvents', 152 | 'properties', 153 | 'attributes', 154 | 'domEvents', 155 | 'extends' 156 | ] 157 | 158 | return cleanDeep(pick(this, props)) 159 | } 160 | 161 | parseType (props) { 162 | if (props.structure) return 'Structure' 163 | if (this.name.match(/webview/i)) return 'Element' 164 | if (this.name.charAt(0) === this.name.charAt(0).toLowerCase()) return 'Module' 165 | return 'Class' 166 | } 167 | 168 | parseDoc (docs) { 169 | this.doc = docs.find(doc => doc.slug === this.slug) 170 | 171 | if (!this.doc) { 172 | throw (new Error(`${this.name} does not appear to have a source document`)) 173 | } 174 | 175 | this.$ = marky(this.doc.markdown_content) 176 | } 177 | 178 | parseDescription () { 179 | if (this.type === 'Class' && this.name !== 'webviewTag') { 180 | return this.$(`#class-${this.slug.replace(/-/g, '')}`) 181 | .next('blockquote').find('p').first().text() 182 | } else { 183 | return this.$('blockquote > p').first().text() 184 | } 185 | } 186 | 187 | parseConstructor () { 188 | const $heading = this.$('h3') 189 | .filter((i, el) => this.$(el).text().match(`new ${this.name}`)) 190 | .first() 191 | 192 | if (!$heading || !$heading.length) return 193 | 194 | const pattern = /new \w+(.*)<\/code>/ 195 | const match = $heading.html().match(pattern) 196 | 197 | if (!match) return 198 | 199 | return { 200 | signature: match[1], 201 | parameters: parsers.parameters(this.$, $heading, this) 202 | } 203 | } 204 | 205 | parseInstanceName () { 206 | if (this.name === 'webviewTag') return 'webview' 207 | 208 | // Some classes don't have any instance events/methods/properties from 209 | // which to infer an instance name. In that case, derive it from the name. 210 | // TouchBarGroup -> touchBarGroup 211 | if (!this.instanceEvents.length && !this.instanceMethods.length && !this.instanceProperties.length) { 212 | return this.name.charAt(0).toLowerCase() + this.name.slice(1) 213 | } 214 | 215 | var $heading = (this.$('[id$="instance-methods"]')) 216 | if (!$heading.length) $heading = this.$('[id$="instance-properties"]') 217 | if (!$heading.length) $heading = this.$('[id$="instance-events"]') 218 | if (!$heading.length) return 219 | 220 | $heading = $heading 221 | .nextUntil('h3') 222 | .filter((i, el) => this.$(el).get(0).tagName === `h4`) 223 | .first() 224 | 225 | if ($heading.length) return $heading.text().split('.')[0] 226 | } 227 | 228 | parseProcesses () { 229 | const processes = this.$('p') 230 | .filter((i, el) => this.$(el).text().match(/^Process: /)) 231 | .first() 232 | .html() 233 | 234 | // structures don't have a process annotation 235 | if (!processes) return 236 | 237 | return { 238 | main: !!processes.match('Main'), 239 | renderer: !!processes.match('Renderer') 240 | } 241 | } 242 | 243 | parseSlug () { 244 | if (this.name.match(/webview/i)) return 'webview-tag' 245 | return decamelize(this.name, '-') 246 | } 247 | } 248 | 249 | module.exports = API 250 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/system-preferences.md: -------------------------------------------------------------------------------- 1 | # systemPreferences 2 | 3 | > Get system preferences. 4 | 5 | Process: [Main](../glossary.md#main-process) 6 | 7 | ```javascript 8 | const {systemPreferences} = require('electron') 9 | console.log(systemPreferences.isDarkMode()) 10 | ``` 11 | 12 | ## Events 13 | 14 | The `systemPreferences` object emits the following events: 15 | 16 | ### Event: 'accent-color-changed' _Windows_ 17 | 18 | Returns: 19 | 20 | * `event` Event 21 | * `newColor` String - The new RGBA color the user assigned to be their system 22 | accent color. 23 | 24 | ### Event: 'color-changed' _Windows_ 25 | 26 | Returns: 27 | 28 | * `event` Event 29 | 30 | ### Event: 'inverted-color-scheme-changed' _Windows_ 31 | 32 | Returns: 33 | 34 | * `event` Event 35 | * `invertedColorScheme` Boolean - `true` if an inverted color scheme, such as 36 | a high contrast theme, is being used, `false` otherwise. 37 | 38 | ## Methods 39 | 40 | ### `systemPreferences.isDarkMode()` _macOS_ 41 | 42 | Returns `Boolean` - Whether the system is in Dark Mode. 43 | 44 | ### `systemPreferences.isSwipeTrackingFromScrollEventsEnabled()` _macOS_ 45 | 46 | Returns `Boolean` - Whether the Swipe between pages setting is on. 47 | 48 | ### `systemPreferences.postNotification(event, userInfo)` _macOS_ 49 | 50 | * `event` String 51 | * `userInfo` Object 52 | 53 | Posts `event` as native notifications of macOS. The `userInfo` is an Object 54 | that contains the user information dictionary sent along with the notification. 55 | 56 | ### `systemPreferences.postLocalNotification(event, userInfo)` _macOS_ 57 | 58 | * `event` String 59 | * `userInfo` Object 60 | 61 | Posts `event` as native notifications of macOS. The `userInfo` is an Object 62 | that contains the user information dictionary sent along with the notification. 63 | 64 | ### `systemPreferences.subscribeNotification(event, callback)` _macOS_ 65 | 66 | * `event` String 67 | * `callback` Function 68 | * `event` String 69 | * `userInfo` Object 70 | 71 | Subscribes to native notifications of macOS, `callback` will be called with 72 | `callback(event, userInfo)` when the corresponding `event` happens. The 73 | `userInfo` is an Object that contains the user information dictionary sent 74 | along with the notification. 75 | 76 | The `id` of the subscriber is returned, which can be used to unsubscribe the 77 | `event`. 78 | 79 | Under the hood this API subscribes to `NSDistributedNotificationCenter`, 80 | example values of `event` are: 81 | 82 | * `AppleInterfaceThemeChangedNotification` 83 | * `AppleAquaColorVariantChanged` 84 | * `AppleColorPreferencesChangedNotification` 85 | * `AppleShowScrollBarsSettingChanged` 86 | 87 | ### `systemPreferences.unsubscribeNotification(id)` _macOS_ 88 | 89 | * `id` Integer 90 | 91 | Removes the subscriber with `id`. 92 | 93 | ### `systemPreferences.subscribeLocalNotification(event, callback)` _macOS_ 94 | 95 | * `event` String 96 | * `callback` Function 97 | * `event` String 98 | * `userInfo` Object 99 | 100 | Same as `subscribeNotification`, but uses `NSNotificationCenter` for local defaults. 101 | This is necessary for events such as `NSUserDefaultsDidChangeNotification` 102 | 103 | ### `systemPreferences.unsubscribeLocalNotification(id)` _macOS_ 104 | 105 | * `id` Integer 106 | 107 | Same as `unsubscribeNotification`, but removes the subscriber from `NSNotificationCenter`. 108 | 109 | ### `systemPreferences.getUserDefault(key, type)` _macOS_ 110 | 111 | * `key` String 112 | * `type` String - Can be `string`, `boolean`, `integer`, `float`, `double`, 113 | `url`, `array`, `dictionary` 114 | 115 | Get the value of `key` in system preferences. 116 | 117 | This API uses `NSUserDefaults` on macOS. Some popular `key` and `type`s are: 118 | 119 | * `AppleInterfaceStyle`: `string` 120 | * `AppleAquaColorVariant`: `integer` 121 | * `AppleHighlightColor`: `string` 122 | * `AppleShowScrollBars`: `string` 123 | * `NSNavRecentPlaces`: `array` 124 | * `NSPreferredWebServices`: `dictionary` 125 | * `NSUserDictionaryReplacementItems`: `array` 126 | 127 | ### `systemPreferences.setUserDefault(key, type, value)` _macOS_ 128 | 129 | * `key` String 130 | * `type` String - See [`getUserDefault`][#systempreferencesgetuserdefaultkey-type-macos] 131 | * `value` String 132 | 133 | Set the value of `key` in system preferences. 134 | 135 | Note that `type` should match actual type of `value`. An exception is thrown 136 | if they don't. 137 | 138 | This API uses `NSUserDefaults` on macOS. Some popular `key` and `type`s are: 139 | 140 | * `ApplePressAndHoldEnabled`: `boolean` 141 | 142 | ### `systemPreferences.isAeroGlassEnabled()` _Windows_ 143 | 144 | This method returns `true` if [DWM composition][dwm-composition] (Aero Glass) is 145 | enabled, and `false` otherwise. 146 | 147 | An example of using it to determine if you should create a transparent window or 148 | not (transparent windows won't work correctly when DWM composition is disabled): 149 | 150 | ```javascript 151 | const {BrowserWindow, systemPreferences} = require('electron') 152 | let browserOptions = {width: 1000, height: 800} 153 | 154 | // Make the window transparent only if the platform supports it. 155 | if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) { 156 | browserOptions.transparent = true 157 | browserOptions.frame = false 158 | } 159 | 160 | // Create the window. 161 | let win = new BrowserWindow(browserOptions) 162 | 163 | // Navigate. 164 | if (browserOptions.transparent) { 165 | win.loadURL(`file://${__dirname}/index.html`) 166 | } else { 167 | // No transparency, so we load a fallback that uses basic styles. 168 | win.loadURL(`file://${__dirname}/fallback.html`) 169 | } 170 | ``` 171 | 172 | [dwm-composition]:https://msdn.microsoft.com/en-us/library/windows/desktop/aa969540.aspx 173 | 174 | ### `systemPreferences.getAccentColor()` _Windows_ 175 | 176 | Returns `String` - The users current system wide accent color preference in RGBA 177 | hexadecimal form. 178 | 179 | ```js 180 | const color = systemPreferences.getAccentColor() // `"aabbccdd"` 181 | const red = color.substr(0, 2) // "aa" 182 | const green = color.substr(2, 2) // "bb" 183 | const blue = color.substr(4, 2) // "cc" 184 | const alpha = color.substr(6, 2) // "dd" 185 | ``` 186 | 187 | ### `systemPreferences.getColor(color)` _Windows_ 188 | 189 | * `color` String - One of the following values: 190 | * `3d-dark-shadow` - Dark shadow for three-dimensional display elements. 191 | * `3d-face` - Face color for three-dimensional display elements and for dialog 192 | box backgrounds. 193 | * `3d-highlight` - Highlight color for three-dimensional display elements. 194 | * `3d-light` - Light color for three-dimensional display elements. 195 | * `3d-shadow` - Shadow color for three-dimensional display elements. 196 | * `active-border` - Active window border. 197 | * `active-caption` - Active window title bar. Specifies the left side color in 198 | the color gradient of an active window's title bar if the gradient effect is 199 | enabled. 200 | * `active-caption-gradient` - Right side color in the color gradient of an 201 | active window's title bar. 202 | * `app-workspace` - Background color of multiple document interface (MDI) 203 | applications. 204 | * `button-text` - Text on push buttons. 205 | * `caption-text` - Text in caption, size box, and scroll bar arrow box. 206 | * `desktop` - Desktop background color. 207 | * `disabled-text` - Grayed (disabled) text. 208 | * `highlight` - Item(s) selected in a control. 209 | * `highlight-text` - Text of item(s) selected in a control. 210 | * `hotlight` - Color for a hyperlink or hot-tracked item. 211 | * `inactive-border` - Inactive window border. 212 | * `inactive-caption` - Inactive window caption. Specifies the left side color 213 | in the color gradient of an inactive window's title bar if the gradient 214 | effect is enabled. 215 | * `inactive-caption-gradient` - Right side color in the color gradient of an 216 | inactive window's title bar. 217 | * `inactive-caption-text` - Color of text in an inactive caption. 218 | * `info-background` - Background color for tooltip controls. 219 | * `info-text` - Text color for tooltip controls. 220 | * `menu` - Menu background. 221 | * `menu-highlight` - The color used to highlight menu items when the menu 222 | appears as a flat menu. 223 | * `menubar` - The background color for the menu bar when menus appear as flat 224 | menus. 225 | * `menu-text` - Text in menus. 226 | * `scrollbar` - Scroll bar gray area. 227 | * `window` - Window background. 228 | * `window-frame` - Window frame. 229 | * `window-text` - Text in windows. 230 | 231 | Returns `String` - The system color setting in RGB hexadecimal form (`#ABCDEF`). 232 | See the [Windows docs][windows-colors] for more details. 233 | 234 | ### `systemPreferences.isInvertedColorScheme()` _Windows_ 235 | 236 | Returns `Boolean` - `true` if an inverted color scheme, such as a high contrast 237 | theme, is active, `false` otherwise. 238 | 239 | [windows-colors]:https://msdn.microsoft.com/en-us/library/windows/desktop/ms724371(v=vs.85).aspx 240 | -------------------------------------------------------------------------------- /test/fixtures/electron/docs/api/dialog.md: -------------------------------------------------------------------------------- 1 | # dialog 2 | 3 | > Display native system dialogs for opening and saving files, alerting, etc. 4 | 5 | Process: [Main](../glossary.md#main-process) 6 | 7 | An example of showing a dialog to select multiple files and directories: 8 | 9 | ```javascript 10 | const {dialog} = require('electron') 11 | console.log(dialog.showOpenDialog({properties: ['openFile', 'openDirectory', 'multiSelections']})) 12 | ``` 13 | 14 | The Dialog is opened from Electron's main thread. If you want to use the dialog 15 | object from a renderer process, remember to access it using the remote: 16 | 17 | ```javascript 18 | const {dialog} = require('electron').remote 19 | console.log(dialog) 20 | ``` 21 | 22 | ## Methods 23 | 24 | The `dialog` module has the following methods: 25 | 26 | ### `dialog.showOpenDialog([browserWindow, ]options[, callback])` 27 | 28 | * `browserWindow` BrowserWindow (optional) 29 | * `options` Object 30 | * `title` String (optional) 31 | * `defaultPath` String (optional) 32 | * `buttonLabel` String (optional) - Custom label for the confirmation button, when 33 | left empty the default label will be used. 34 | * `filters` [FileFilter[]](structures/file-filter.md) (optional) 35 | * `properties` String[] (optional) - Contains which features the dialog should 36 | use. The following values are supported: 37 | * `openFile` - Allow files to be selected. 38 | * `openDirectory` - Allow directories to be selected. 39 | * `multiSelections` - Allow multiple paths to be selected. 40 | * `showHiddenFiles` - Show hidden files in dialog. 41 | * `createDirectory` - Allow creating new directories from dialog. _macOS_ 42 | * `promptToCreate` - Prompt for creation if the file path entered 43 | in the dialog does not exist. This does not actually create the file at 44 | the path but allows non-existent paths to be returned that should be 45 | created by the application. _Windows_ 46 | * `noResolveAliases` - Disable the automatic alias (symlink) path 47 | resolution. Selected aliases will now return the alias path instead of 48 | their target path. _macOS_ 49 | * `normalizeAccessKeys` Boolean (optional) - Normalize the keyboard access keys 50 | across platforms. Default is `false`. Enabling this assumes `&` is used in 51 | the button labels for the placement of the keyboard shortcut access key 52 | and labels will be converted so they work correctly on each platform, `&` 53 | characters are removed on macOS, converted to `_` on Linux, and left 54 | untouched on Windows. For example, a button label of `Vie&w` will be 55 | converted to `Vie_w` on Linux and `View` on macOS and can be selected 56 | via `Alt-W` on Windows and Linux. 57 | * `message` String (optional) _macOS_ - Message to display above input 58 | boxes. 59 | * `callback` Function (optional) 60 | * `filePaths` String[] - An array of file paths chosen by the user 61 | 62 | Returns `String[]`, an array of file paths chosen by the user, 63 | if the callback is provided it returns `undefined`. 64 | 65 | The `browserWindow` argument allows the dialog to attach itself to a parent window, making it modal. 66 | 67 | The `filters` specifies an array of file types that can be displayed or 68 | selected when you want to limit the user to a specific type. For example: 69 | 70 | ```javascript 71 | { 72 | filters: [ 73 | {name: 'Images', extensions: ['jpg', 'png', 'gif']}, 74 | {name: 'Movies', extensions: ['mkv', 'avi', 'mp4']}, 75 | {name: 'Custom File Type', extensions: ['as']}, 76 | {name: 'All Files', extensions: ['*']} 77 | ] 78 | } 79 | ``` 80 | 81 | The `extensions` array should contain extensions without wildcards or dots (e.g. 82 | `'png'` is good but `'.png'` and `'*.png'` are bad). To show all files, use the 83 | `'*'` wildcard (no other wildcard is supported). 84 | 85 | If a `callback` is passed, the API call will be asynchronous and the result 86 | will be passed via `callback(filenames)` 87 | 88 | **Note:** On Windows and Linux an open dialog can not be both a file selector 89 | and a directory selector, so if you set `properties` to 90 | `['openFile', 'openDirectory']` on these platforms, a directory selector will be 91 | shown. 92 | 93 | ### `dialog.showSaveDialog([browserWindow, ]options[, callback])` 94 | 95 | * `browserWindow` BrowserWindow (optional) 96 | * `options` Object 97 | * `title` String (optional) 98 | * `defaultPath` String (optional) 99 | * `buttonLabel` String (optional) - Custom label for the confirmation button, when 100 | left empty the default label will be used. 101 | * `filters` [FileFilter[]](structures/file-filter.md) (optional) 102 | * `message` String (optional) _macOS_ - Message to display above text fields. 103 | * `nameFieldLabel` String (optional) _macOS_ - Custom label for the text 104 | displayed in front of the filename text field. 105 | * `showsTagField` Boolean (optional) _macOS_ - Show the tags input box, 106 | defaults to `true`. 107 | * `callback` Function (optional) 108 | * `filename` String 109 | 110 | Returns `String`, the path of the file chosen by the user, 111 | if a callback is provided it returns `undefined`. 112 | 113 | The `browserWindow` argument allows the dialog to attach itself to a parent window, making it modal. 114 | 115 | The `filters` specifies an array of file types that can be displayed, see 116 | `dialog.showOpenDialog` for an example. 117 | 118 | If a `callback` is passed, the API call will be asynchronous and the result 119 | will be passed via `callback(filename)` 120 | 121 | ### `dialog.showMessageBox([browserWindow, ]options[, callback])` 122 | 123 | * `browserWindow` BrowserWindow (optional) 124 | * `options` Object 125 | * `type` String (optional) - Can be `"none"`, `"info"`, `"error"`, `"question"` or 126 | `"warning"`. On Windows, "question" displays the same icon as "info", unless 127 | you set an icon using the "icon" option. 128 | * `buttons` String[] (optional) - Array of texts for buttons. On Windows, an empty array 129 | will result in one button labeled "OK". 130 | * `defaultId` Integer (optional) - Index of the button in the buttons array which will 131 | be selected by default when the message box opens. 132 | * `title` String (optional) - Title of the message box, some platforms will not show it. 133 | * `message` String - Content of the message box. 134 | * `detail` String (optional) - Extra information of the message. 135 | * `checkboxLabel` String (optional) - If provided, the message box will 136 | include a checkbox with the given label. The checkbox state can be 137 | inspected only when using `callback`. 138 | * `checkboxChecked` Boolean (optional) - Initial checked state of the 139 | checkbox. `false` by default. 140 | * `icon` [NativeImage](native-image.md) (optional) 141 | * `cancelId` Integer (optional) - The index of the button to be used to cancel the dialog, via 142 | the `Esc` key. By default this is assigned to the first button with "cancel" or "no" as the 143 | label. If no such labeled buttons exist and this option is not set, `0` will be used as the 144 | return value or callback response. This option is ignored on Windows. 145 | * `noLink` Boolean (optional) - On Windows Electron will try to figure out which one of 146 | the `buttons` are common buttons (like "Cancel" or "Yes"), and show the 147 | others as command links in the dialog. This can make the dialog appear in 148 | the style of modern Windows apps. If you don't like this behavior, you can 149 | set `noLink` to `true`. 150 | * `callback` Function (optional) 151 | * `response` Number - The index of the button that was clicked 152 | * `checkboxChecked` Boolean - The checked state of the checkbox if 153 | `checkboxLabel` was set. Otherwise `false`. 154 | 155 | Returns `Integer`, the index of the clicked button, if a callback is provided 156 | it returns undefined. 157 | 158 | Shows a message box, it will block the process until the message box is closed. 159 | It returns the index of the clicked button. 160 | 161 | The `browserWindow` argument allows the dialog to attach itself to a parent window, making it modal. 162 | 163 | If a `callback` is passed, the API call will be asynchronous and the result 164 | will be passed via `callback(response)`. 165 | 166 | ### `dialog.showErrorBox(title, content)` 167 | 168 | * `title` String - The title to display in the error box 169 | * `content` String - The text content to display in the error box 170 | 171 | Displays a modal dialog that shows an error message. 172 | 173 | This API can be called safely before the `ready` event the `app` module emits, 174 | it is usually used to report errors in early stage of startup. If called 175 | before the app `ready`event on Linux, the message will be emitted to stderr, 176 | and no GUI dialog will appear. 177 | 178 | ## Sheets 179 | 180 | On macOS, dialogs are presented as sheets attached to a window if you provide 181 | a `BrowserWindow` reference in the `browserWindow` parameter, or modals if no 182 | window is provided. 183 | 184 | You can call `BrowserWindow.getCurrentWindow().setSheetOffset(offset)` to change 185 | the offset from the window frame where sheets are attached. 186 | --------------------------------------------------------------------------------