chore: remove promisification deprecation callbacks (#17907)

* chore: remove promisification deprecation callbacks

* update docs

* fix smoke test

* fix executejs issue

* cleanup leftovers

* fix webContents.executeJavaScript tests

* cleanup WebContents.prototype.takeHeapSnapshot

* fix "sets arbitrary webContents as devtools" test

* fix executeJavaScriptInFrame related tests
This commit is contained in:
Shelley Vohr 2019-04-30 07:08:33 -07:00 committed by John Kleinschmidt
parent fdf5f838f4
commit d87b3ead76
44 changed files with 94 additions and 1418 deletions

View file

@ -610,29 +610,6 @@ You can request the following paths by the name:
* `logs` Directory for your app's log folder.
* `pepperFlashSystemPlugin` Full path to the system version of the Pepper Flash plugin.
### `app.getFileIcon(path[, options], callback)`
* `path` String
* `options` Object (optional)
* `size` String
* `small` - 16x16
* `normal` - 32x32
* `large` - 48x48 on _Linux_, 32x32 on _Windows_, unsupported on _macOS_.
* `callback` Function
* `error` Error
* `icon` [NativeImage](native-image.md)
Fetches a path's associated icon.
On _Windows_, there are 2 kinds of icons:
* Icons associated with certain file extensions, like `.mp3`, `.png`, etc.
* Icons inside the file itself, like `.exe`, `.dll`, `.ico`.
On _Linux_ and _macOS_, icons depend on the application associated with file mime type.
**[Deprecated Soon](modernization/promisification.md)**
### `app.getFileIcon(path[, options])`
* `path` String

View file

@ -1221,18 +1221,6 @@ Returns `Boolean` - Whether the window's document has been edited.
#### `win.blurWebView()`
#### `win.capturePage([rect, ]callback)`
* `rect` [Rectangle](structures/rectangle.md) (optional) - The bounds to capture
* `callback` Function
* `image` [NativeImage](native-image.md)
Captures a snapshot of the page within `rect`. Upon completion `callback` will
be called with `callback(image)`. The `image` is an instance of [NativeImage](native-image.md)
that stores data of the snapshot. Omitting `rect` will capture the whole visible page.
**[Deprecated Soon](modernization/promisification.md)**
#### `win.capturePage([rect])`
* `rect` [Rectangle](structures/rectangle.md) (optional) - The bounds to capture

View file

@ -37,37 +37,12 @@ app.on('ready', () => {
The `contentTracing` module has the following methods:
### `contentTracing.getCategories(callback)`
* `callback` Function
* `categories` String[]
Get a set of category groups. The category groups can change as new code paths are reached.
Once all child processes have acknowledged the `getCategories` request the `callback` is invoked with an array of category groups.
**[Deprecated Soon](modernization/promisification.md)**
### `contentTracing.getCategories()`
Returns `Promise<String[]>` - resolves with an array of category groups once all child processes have acknowledged the `getCategories` request
Get a set of category groups. The category groups can change as new code paths are reached.
### `contentTracing.startRecording(options, callback)`
* `options` ([TraceCategoriesAndOptions](structures/trace-categories-and-options.md) | [TraceConfig](structures/trace-config.md))
* `callback` Function
Start recording on all processes.
Recording begins immediately locally and asynchronously on child processes
as soon as they receive the EnableRecording request. The `callback` will be
called once all child processes have acknowledged the `startRecording` request.
**[Deprecated Soon](modernization/promisification.md)**
### `contentTracing.startRecording(options)`
* `options` ([TraceCategoriesAndOptions](structures/trace-categories-and-options.md) | [TraceConfig](structures/trace-config.md))
@ -79,29 +54,6 @@ Start recording on all processes.
Recording begins immediately locally and asynchronously on child processes
as soon as they receive the EnableRecording request.
### `contentTracing.stopRecording(resultFilePath, callback)`
* `resultFilePath` String
* `callback` Function
* `resultFilePath` String
Stop recording on all processes.
Child processes typically cache trace data and only rarely flush and send
trace data back to the main process. This helps to minimize the runtime overhead
of tracing since sending trace data over IPC can be an expensive operation. So,
to end tracing, we must asynchronously ask all child processes to flush any
pending trace data.
Once all child processes have acknowledged the `stopRecording` request,
`callback` will be called with a file that contains the traced data.
Trace data will be written into `resultFilePath` if it is not empty or into a
temporary file. The actual file path will be passed to `callback` if it's not
`null`.
**[Deprecated Soon](modernization/promisification.md)**
### `contentTracing.stopRecording(resultFilePath)`
* `resultFilePath` String
@ -119,19 +71,6 @@ pending trace data.
Trace data will be written into `resultFilePath` if it is not empty or into a
temporary file.
### `contentTracing.getTraceBufferUsage(callback)`
* `callback` Function
* Object
* `value` Number
* `percentage` Number
Get the maximum usage across processes of trace buffer as a percentage of the
full state. When the TraceBufferUsage value is determined the `callback` is
called.
**[Deprecated Soon](modernization/promisification.md)**
### `contentTracing.getTraceBufferUsage()`
Returns `Promise<Object>` - Resolves with an object containing the `value` and `percentage` of trace buffer maximum usage

View file

@ -81,26 +81,6 @@ Returns `Promise<Cookie[]>` - A promise which resolves an array of cookie object
Sends a request to get all cookies matching `filter`, and resolves a promise with
the response.
#### `cookies.get(filter, callback)`
* `filter` Object
* `url` String (optional) - Retrieves cookies which are associated with
`url`. Empty implies retrieving cookies of all urls.
* `name` String (optional) - Filters cookies by name.
* `domain` String (optional) - Retrieves cookies whose domains match or are
subdomains of `domains`.
* `path` String (optional) - Retrieves cookies whose path matches `path`.
* `secure` Boolean (optional) - Filters cookies by their Secure property.
* `session` Boolean (optional) - Filters out session or persistent cookies.
* `callback` Function
* `error` Error
* `cookies` [Cookie[]](structures/cookie.md) - an array of cookie objects.
Sends a request to get all cookies matching `filter`, `callback` will be called
with `callback(error, cookies)` on complete.
**[Deprecated Soon](modernization/promisification.md)**
#### `cookies.set(details)`
* `details` Object
@ -121,29 +101,6 @@ Returns `Promise<void>` - A promise which resolves when the cookie has been set
Sets a cookie with `details`.
#### `cookies.set(details, callback)`
* `details` Object
* `url` String - The url to associate the cookie with.
* `name` String (optional) - The name of the cookie. Empty by default if omitted.
* `value` String (optional) - The value of the cookie. Empty by default if omitted.
* `domain` String (optional) - The domain of the cookie. Empty by default if omitted.
* `path` String (optional) - The path of the cookie. Empty by default if omitted.
* `secure` Boolean (optional) - Whether the cookie should be marked as Secure. Defaults to
false.
* `httpOnly` Boolean (optional) - Whether the cookie should be marked as HTTP only.
Defaults to false.
* `expirationDate` Double (optional) - The expiration date of the cookie as the number of
seconds since the UNIX epoch. If omitted then the cookie becomes a session
cookie and will not be retained between sessions.
* `callback` Function
* `error` Error
Sets a cookie with `details`, `callback` will be called with `callback(error)`
on complete.
**[Deprecated Soon](modernization/promisification.md)**
#### `cookies.remove(url, name)`
* `url` String - The URL associated with the cookie.
@ -153,27 +110,8 @@ Returns `Promise<void>` - A promise which resolves when the cookie has been remo
Removes the cookies matching `url` and `name`
#### `cookies.remove(url, name, callback)`
* `url` String - The URL associated with the cookie.
* `name` String - The name of cookie to remove.
* `callback` Function
Removes the cookies matching `url` and `name`, `callback` will called with
`callback()` on complete.
**[Deprecated Soon](modernization/promisification.md)**
#### `cookies.flushStore()`
Returns `Promise<void>` - A promise which resolves when the cookie store has been flushed
Writes any unwritten cookies data to disk.
#### `cookies.flushStore(callback)`
* `callback` Function
Writes any unwritten cookies data to disk.
**[Deprecated Soon](modernization/promisification.md)**

View file

@ -48,20 +48,6 @@ Returns `Boolean` - Whether a debugger is attached to the `webContents`.
Detaches the debugger from the `webContents`.
#### `debugger.sendCommand(method[, commandParams, callback])`
* `method` String - Method name, should be one of the methods defined by the
[remote debugging protocol][rdp].
* `commandParams` Object (optional) - JSON object with request parameters.
* `callback` Function (optional) - Response
* `error` Object - Error message indicating the failure of the command.
* `result` Any - Response defined by the 'returns' attribute of
the command description in the remote debugging protocol.
Send given command to the debugging target.
**[Deprecated Soon](modernization/promisification.md)**
#### `debugger.sendCommand(method[, commandParams])`
* `method` String - Method name, should be one of the methods defined by the

View file

@ -76,33 +76,6 @@ const constraints = {
The `desktopCapturer` module has the following methods:
### `desktopCapturer.getSources(options, callback)`
* `options` Object
* `types` String[] - An array of Strings that lists the types of desktop sources
to be captured, available types are `screen` and `window`.
* `thumbnailSize` [Size](structures/size.md) (optional) - The size that the media source thumbnail
should be scaled to. Default is `150` x `150`. Set width or height to 0 when you do not need
the thumbnails. This will save the processing time required for capturing the content of each
window and screen.
* `fetchWindowIcons` Boolean (optional) - Set to true to enable fetching window icons. The default
value is false. When false the appIcon property of the sources return null. Same if a source has
the type screen.
* `callback` Function
* `error` Error
* `sources` [DesktopCapturerSource[]](structures/desktop-capturer-source.md)
Starts gathering information about all available desktop media sources,
and calls `callback(error, sources)` when finished.
`sources` is an array of [`DesktopCapturerSource`](structures/desktop-capturer-source.md)
objects, each `DesktopCapturerSource` represents a screen or an individual window that can be
captured.
[`navigator.mediaDevices.getUserMedia`]: https://developer.mozilla.org/en/docs/Web/API/MediaDevices/getUserMedia
**[Deprecated Soon](modernization/promisification.md)**
### `desktopCapturer.getSources(options)`
* `options` Object

View file

@ -225,15 +225,14 @@ expanding and collapsing the dialog.
* `message` String - Content of the message box.
* `detail` String (optional) - Extra information of the message.
* `checkboxLabel` String (optional) - If provided, the message box will
include a checkbox with the given label. The checkbox state can be
inspected only when using `callback`.
include a checkbox with the given label.
* `checkboxChecked` Boolean (optional) - Initial checked state of the
checkbox. `false` by default.
* `icon` [NativeImage](native-image.md) (optional)
* `cancelId` Integer (optional) - The index of the button to be used to cancel the dialog, via
the `Esc` key. By default this is assigned to the first button with "cancel" or "no" as the
label. If no such labeled buttons exist and this option is not set, `0` will be used as the
return value or callback response.
return value.
* `noLink` Boolean (optional) - On Windows Electron will try to figure out which one of
the `buttons` are common buttons (like "Cancel" or "Yes"), and show the
others as command links in the dialog. This can make the dialog appear in
@ -271,15 +270,14 @@ The `browserWindow` argument allows the dialog to attach itself to a parent wind
* `message` String - Content of the message box.
* `detail` String (optional) - Extra information of the message.
* `checkboxLabel` String (optional) - If provided, the message box will
include a checkbox with the given label. The checkbox state can be
inspected only when using `callback`.
include a checkbox with the given label.
* `checkboxChecked` Boolean (optional) - Initial checked state of the
checkbox. `false` by default.
* `icon` [NativeImage](native-image.md) (optional)
* `cancelId` Integer (optional) - The index of the button to be used to cancel the dialog, via
the `Esc` key. By default this is assigned to the first button with "cancel" or "no" as the
label. If no such labeled buttons exist and this option is not set, `0` will be used as the
return value or callback response.
return value.
* `noLink` Boolean (optional) - On Windows Electron will try to figure out which one of
the `buttons` are common buttons (like "Cancel" or "Yes"), and show the
others as command links in the dialog. This can make the dialog appear in
@ -315,28 +313,6 @@ it is usually used to report errors in early stage of startup. If called
before the app `ready`event on Linux, the message will be emitted to stderr,
and no GUI dialog will appear.
### `dialog.showCertificateTrustDialog([browserWindow, ]options, callback)` _macOS_ _Windows_
* `browserWindow` [BrowserWindow](browser-window.md) (optional)
* `options` Object
* `certificate` [Certificate](structures/certificate.md) - The certificate to trust/import.
* `message` String - The message to display to the user.
* `callback` Function
On macOS, this displays a modal dialog that shows a message and certificate
information, and gives the user the option of trusting/importing the
certificate. If you provide a `browserWindow` argument the dialog will be
attached to the parent window, making it modal.
On Windows the options are more limited, due to the Win32 APIs used:
* The `message` argument is not used, as the OS provides its own confirmation
dialog.
* The `browserWindow` argument is ignored since it is not possible to make
this confirmation dialog modal.
**[Deprecated Soon](modernization/promisification.md)**
### `dialog.showCertificateTrustDialog([browserWindow, ]options)` _macOS_ _Windows_
* `browserWindow` [BrowserWindow](browser-window.md) (optional)

View file

@ -21,17 +21,6 @@ Returns:
The `inAppPurchase` module has the following methods:
### `inAppPurchase.purchaseProduct(productID, quantity, callback)`
* `productID` String - The identifiers of the product to purchase. (The identifier of `com.example.app.product1` is `product1`).
* `quantity` Integer (optional) - The number of items the user wants to purchase.
* `callback` Function (optional) - The callback called when the payment is added to the PaymentQueue.
* `isProductValid` Boolean - Determine if the product is valid and added to the payment queue.
You should listen for the `transactions-updated` event as soon as possible and certainly before you call `purchaseProduct`.
**[Deprecated Soon](modernization/promisification.md)**
### `inAppPurchase.purchaseProduct(productID, quantity)`
* `productID` String - The identifiers of the product to purchase. (The identifier of `com.example.app.product1` is `product1`).
@ -41,16 +30,6 @@ Returns `Promise<Boolean>` - Returns `true` if the product is valid and added to
You should listen for the `transactions-updated` event as soon as possible and certainly before you call `purchaseProduct`.
### `inAppPurchase.getProducts(productIDs, callback)`
* `productIDs` String[] - The identifiers of the products to get.
* `callback` Function - The callback called with the products or an empty array if the products don't exist.
* `products` Product[] - Array of [`Product`](structures/product.md) objects
Retrieves the product descriptions.
**[Deprecated Soon](modernization/promisification.md)**
### `inAppPurchase.getProducts(productIDs)`
* `productIDs` String[] - The identifiers of the products to get.

View file

@ -28,15 +28,6 @@ of the `app` module gets emitted.
Starts recording network events to `path`.
### `netLog.stopLogging([callback])`
* `callback` Function (optional)
* `path` String - File path to which network logs were recorded.
Stops recording network events. If not called, net logging will automatically end when app quits.
**[Deprecated Soon](modernization/promisification.md)**
### `netLog.stopLogging()`
Returns `Promise<String>` - resolves with a file path to which network logs were recorded.

View file

@ -312,17 +312,6 @@ protocol.registerStreamProtocol('atom', (request, callback) => {
Unregisters the custom protocol of `scheme`.
### `protocol.isProtocolHandled(scheme, callback)`
* `scheme` String
* `callback` Function
* `handled` Boolean
The `callback` will be called with a boolean that indicates whether there is
already a handler for `scheme`.
**[Deprecated Soon](modernization/promisification.md)**
### `protocol.isProtocolHandled(scheme)`
* `scheme` String

View file

@ -22,7 +22,7 @@ win.loadURL('https://github.com')
```
**Note:** For the reverse (access the renderer process from the main process),
you can use [webContents.executeJavaScript](web-contents.md#contentsexecutejavascriptcode-usergesture-callback).
you can use [webContents.executeJavaScript](web-contents.md#contentsexecutejavascriptcode-usergesture).
**Note:** The remote module can be disabled for security reasons in the following contexts:
- [`BrowserWindow`](browser-window.md) - by setting the `enableRemoteModule` option to `false`.

View file

@ -93,51 +93,16 @@ session.defaultSession.on('will-download', (event, item, webContents) => {
The following methods are available on instances of `Session`:
#### `ses.getCacheSize(callback)`
* `callback` Function
* `size` Integer - Cache size used in bytes.
* `error` Integer - The error code corresponding to the failure.
Callback is invoked with the session's current cache size.
**[Deprecated Soon](modernization/promisification.md)**
#### `ses.getCacheSize()`
Returns `Promise<Integer>` - the session's current cache size, in bytes.
#### `ses.clearCache(callback)`
* `callback` Function - Called when operation is done.
* `error` Integer - The error code corresponding to the failure.
Clears the sessions HTTP cache.
**[Deprecated Soon](modernization/promisification.md)**
#### `ses.clearCache()`
Returns `Promise<void>` - resolves when the cache clear operation is complete.
Clears the sessions HTTP cache.
#### `ses.clearStorageData([options,] callback)`
* `options` Object (optional)
* `origin` String (optional) - Should follow `window.location.origin`s representation
`scheme://host:port`.
* `storages` String[] (optional) - The types of storages to clear, can contain:
`appcache`, `cookies`, `filesystem`, `indexdb`, `localstorage`,
`shadercache`, `websql`, `serviceworkers`, `cachestorage`.
* `quotas` String[] (optional) - The types of quotas to clear, can contain:
`temporary`, `persistent`, `syncable`.
* `callback` Function (optional) - Called when operation is done.
Clears the storage data for the current session.
**[Deprecated Soon](modernization/promisification.md)**
#### `ses.clearStorageData([options])`
* `options` Object (optional)
@ -155,84 +120,6 @@ Returns `Promise<void>` - resolves when the storage data has been cleared.
Writes any unwritten DOMStorage data to disk.
#### `ses.setProxy(config, callback)`
* `config` Object
* `pacScript` String - The URL associated with the PAC file.
* `proxyRules` String - Rules indicating which proxies to use.
* `proxyBypassRules` String - Rules indicating which URLs should
bypass the proxy settings.
* `callback` Function - Called when operation is done.
Sets the proxy settings.
When `pacScript` and `proxyRules` are provided together, the `proxyRules`
option is ignored and `pacScript` configuration is applied.
The `proxyRules` has to follow the rules below:
```sh
proxyRules = schemeProxies[";"<schemeProxies>]
schemeProxies = [<urlScheme>"="]<proxyURIList>
urlScheme = "http" | "https" | "ftp" | "socks"
proxyURIList = <proxyURL>[","<proxyURIList>]
proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>]
```
For example:
* `http=foopy:80;ftp=foopy2` - Use HTTP proxy `foopy:80` for `http://` URLs, and
HTTP proxy `foopy2:80` for `ftp://` URLs.
* `foopy:80` - Use HTTP proxy `foopy:80` for all URLs.
* `foopy:80,bar,direct://` - Use HTTP proxy `foopy:80` for all URLs, failing
over to `bar` if `foopy:80` is unavailable, and after that using no proxy.
* `socks4://foopy` - Use SOCKS v4 proxy `foopy:1080` for all URLs.
* `http=foopy,socks5://bar.com` - Use HTTP proxy `foopy` for http URLs, and fail
over to the SOCKS5 proxy `bar.com` if `foopy` is unavailable.
* `http=foopy,direct://` - Use HTTP proxy `foopy` for http URLs, and use no
proxy if `foopy` is unavailable.
* `http=foopy;socks=foopy2` - Use HTTP proxy `foopy` for http URLs, and use
`socks4://foopy2` for all other URLs.
The `proxyBypassRules` is a comma separated list of rules described below:
* `[ URL_SCHEME "://" ] HOSTNAME_PATTERN [ ":" <port> ]`
Match all hostnames that match the pattern HOSTNAME_PATTERN.
Examples:
"foobar.com", "*foobar.com", "*.foobar.com", "*foobar.com:99",
"https://x.*.y.com:99"
* `"." HOSTNAME_SUFFIX_PATTERN [ ":" PORT ]`
Match a particular domain suffix.
Examples:
".google.com", ".com", "http://.google.com"
* `[ SCHEME "://" ] IP_LITERAL [ ":" PORT ]`
Match URLs which are IP address literals.
Examples:
"127.0.1", "[0:0::1]", "[::1]", "http://[::1]:99"
* `IP_LITERAL "/" PREFIX_LENGTH_IN_BITS`
Match any URL that is to an IP literal that falls between the
given range. IP range is specified using CIDR notation.
Examples:
"192.168.1.1/16", "fefe:13::abc/33".
* `<local>`
Match local addresses. The meaning of `<local>` is whether the
host matches one of: "127.0.0.1", "::1", "localhost".
**[Deprecated Soon](modernization/promisification.md)**
#### `ses.setProxy(config)`
* `config` Object
@ -310,17 +197,6 @@ The `proxyBypassRules` is a comma separated list of rules described below:
Match local addresses. The meaning of `<local>` is whether the
host matches one of: "127.0.0.1", "::1", "localhost".
#### `ses.resolveProxy(url, callback)`
* `url` URL
* `callback` Function
* `proxy` String
Resolves the proxy information for `url`. The `callback` will be called with
`callback(proxy)` when the request is performed.
**[Deprecated Soon](modernization/promisification.md)**
#### `ses.resolveProxy(url)`
* `url` URL
@ -457,14 +333,6 @@ session.fromPartition('some-partition').setPermissionCheckHandler((webContents,
})
```
#### `ses.clearHostResolverCache(callback)`
* `callback` Function (optional) - Called when operation is done.
Clears the host resolver cache.
**[Deprecated Soon](modernization/promisification.md)**
#### `ses.clearHostResolverCache()`
Returns `Promise<void>` - Resolves when the operation is complete.
@ -506,14 +374,6 @@ This doesn't affect existing `WebContents`, and each `WebContents` can use
Returns `String` - The user agent for this session.
#### `ses.getBlobData(identifier, callback)`
* `identifier` String - Valid UUID.
* `callback` Function
* `result` Buffer - Blob data.
**[Deprecated Soon](modernization/promisification.md)**
#### `ses.getBlobData(identifier)`
* `identifier` String - Valid UUID.
@ -539,15 +399,6 @@ event. The [DownloadItem](download-item.md) will not have any `WebContents` asso
the initial state will be `interrupted`. The download will start only when the
`resume` API is called on the [DownloadItem](download-item.md).
#### `ses.clearAuthCache(options, callback)`
* `options` ([RemovePassword](structures/remove-password.md) | [RemoveClientCertificate](structures/remove-client-certificate.md))
* `callback` Function - Called when operation is done.
Clears the sessions HTTP authentication cache.
**[Deprecated Soon](modernization/promisification.md)**
#### `ses.clearAuthCache(options)`
* `options` ([RemovePassword](structures/remove-password.md) | [RemoveClientCertificate](structures/remove-client-certificate.md))

View file

@ -2,5 +2,5 @@
* `bytes` Buffer - Content being sent.
* `file` String - Path of file being uploaded.
* `blobUUID` String - UUID of blob data. Use [ses.getBlobData](../session.md#sesgetblobdataidentifier-callback) method
* `blobUUID` String - UUID of blob data. Use [ses.getBlobData](../session.md#sesgetblobdataidentifier method
to retrieve the data.

View file

@ -957,31 +957,6 @@ contents.on('did-finish-load', function () {
})
```
#### `contents.executeJavaScript(code[, userGesture, callback])`
* `code` String
* `userGesture` Boolean (optional) - Default is `false`.
* `callback` Function (optional) - Called after script has been executed.
* `result` Any
Returns `Promise<any>` - A promise that resolves with the result of the executed code
or is rejected if the result of the code is a rejected promise.
Evaluates `code` in page.
In the browser window some HTML APIs like `requestFullScreen` can only be
invoked by a gesture from the user. Setting `userGesture` to `true` will remove
this limitation.
```js
contents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true)
.then((result) => {
console.log(result) // Will be the JSON object from the fetch call
})
```
**[Deprecated Soon](modernization/promisification.md)**
#### `contents.executeJavaScript(code[, userGesture])`
* `code` String
@ -1169,18 +1144,6 @@ const requestId = webContents.findInPage('api')
console.log(requestId)
```
#### `contents.capturePage([rect, ]callback)`
* `rect` [Rectangle](structures/rectangle.md) (optional) - The bounds to capture
* `callback` Function
* `image` [NativeImage](native-image.md)
Captures a snapshot of the page within `rect`. Upon completion `callback` will
be called with `callback(image)`. The `image` is an instance of [NativeImage](native-image.md)
that stores data of the snapshot. Omitting `rect` will capture the whole visible page.
**[Deprecated Soon](modernization/promisification.md)**
#### `contents.capturePage([rect])`
* `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured.
@ -1214,29 +1177,6 @@ Calling `window.print()` in web page is equivalent to calling
Use `page-break-before: always; ` CSS style to force to print to a new page.
#### `contents.printToPDF(options, callback)`
* `options` Object
* `marginsType` Integer (optional) - Specifies the type of margins to use. Uses 0 for
default margin, 1 for no margin, and 2 for minimum margin.
* `pageSize` String | Size (optional) - Specify page size of the generated PDF. Can be `A3`,
`A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height`
and `width` in microns.
* `printBackground` Boolean (optional) - Whether to print CSS backgrounds.
* `printSelectionOnly` Boolean (optional) - Whether to print selection only.
* `landscape` Boolean (optional) - `true` for landscape, `false` for portrait.
* `callback` Function
* `error` Error
* `data` Buffer
Prints window's web page as PDF with Chromium's preview printing custom
settings.
The `callback` will be called with `callback(error, data)` on completion. The
`data` is a `Buffer` that contains the generated PDF data.
**[Deprecated Soon](modernization/promisification.md)**
#### `contents.printToPDF(options)`
* `options` Object

View file

@ -107,24 +107,6 @@ Inserts `css` as a style sheet in the document.
Inserts `text` to the focused element.
### `webFrame.executeJavaScript(code[, userGesture, callback])`
* `code` String
* `userGesture` Boolean (optional) - Default is `false`.
* `callback` Function (optional) - Called after script has been executed.
* `result` Any
Returns `Promise<any>` - A promise that resolves with the result of the executed code
or is rejected if the result of the code is a rejected promise.
Evaluates `code` in page.
In the browser window some HTML APIs like `requestFullScreen` can only be
invoked by a gesture from the user. Setting `userGesture` to `true` will remove
this limitation.
**[Deprecated Soon](modernization/promisification.md)**
### `webFrame.executeJavaScript(code[, userGesture])`
* `code` String
@ -139,21 +121,6 @@ In the browser window some HTML APIs like `requestFullScreen` can only be
invoked by a gesture from the user. Setting `userGesture` to `true` will remove
this limitation.
### `webFrame.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture, callback])`
* `worldId` Integer - The ID of the world to run the javascript in, `0` is the default world, `999` is the world used by Electrons `contextIsolation` feature. Chrome extensions reserve the range of IDs in `[1 << 20, 1 << 29)`. You can provide any integer here.
* `scripts` [WebSource[]](structures/web-source.md)
* `userGesture` Boolean (optional) - Default is `false`.
* `callback` Function (optional) - Called after script has been executed.
* `result` Any
Returns `Promise<any>` - A promise that resolves with the result of the executed code
or is rejected if the result of the code is a rejected promise.
Works like `executeJavaScript` but evaluates `scripts` in an isolated context.
**[Deprecated Soon](modernization/promisification.md)**
### `webFrame.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])`
* `worldId` Integer - The ID of the world to run the javascript in, `0` is the default world, `999` is the world used by Electrons `contextIsolation` feature. You can provide any integer here.

View file

@ -381,22 +381,6 @@ Returns `String` - The user agent for guest page.
Injects CSS into the guest page.
### `<webview>.executeJavaScript(code[, userGesture, callback])`
* `code` String
* `userGesture` Boolean (optional) - Default `false`.
* `callback` Function (optional) - Called after script has been executed.
* `result` Any
Returns `Promise<any>` - A promise that resolves with the result of the executed code
or is rejected if the result of the code is a rejected promise.
Evaluates `code` in page. If `userGesture` is set, it will create the user
gesture context in the page. HTML APIs like `requestFullScreen`, which require
user action, can take advantage of this option for automation.
**[Deprecated Soon](modernization/promisification.md)**
### `<webview>.executeJavaScript(code[, userGesture])`
* `code` String
@ -549,25 +533,6 @@ Stops any `findInPage` request for the `webview` with the provided `action`.
Prints `webview`'s web page. Same as `webContents.print([options])`.
### `<webview>.printToPDF(options, callback)`
* `options` Object
* `marginsType` Integer (optional) - Specifies the type of margins to use. Uses 0 for
default margin, 1 for no margin, and 2 for minimum margin.
* `pageSize` String | Size (optional) - Specify page size of the generated PDF. Can be `A3`,
`A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height`
and `width` in microns.
* `printBackground` Boolean (optional) - Whether to print CSS backgrounds.
* `printSelectionOnly` Boolean (optional) - Whether to print selection only.
* `landscape` Boolean (optional) - `true` for landscape, `false` for portrait.
* `callback` Function
* `error` Error
* `data` Buffer
Prints `webview`'s web page as PDF, Same as `webContents.printToPDF(options, callback)`.
**[Deprecated Soon](modernization/promisification.md)**
### `<webview>.printToPDF(options)`
* `options` Object
@ -584,18 +549,6 @@ Returns `Promise<Buffer>` - Resolves with the generated PDF data.
Prints `webview`'s web page as PDF, Same as `webContents.printToPDF(options)`.
### `<webview>.capturePage([rect, ]callback)`
* `rect` [Rectangle](structures/rectangle.md) (optional) - The bounds to capture
* `callback` Function
* `image` [NativeImage](native-image.md)
Captures a snapshot of the page within `rect`. Upon completion `callback` will
be called with `callback(image)`. The `image` is an instance of [NativeImage](native-image.md)
that stores data of the snapshot. Omitting `rect` will capture the whole visible page.
**[Deprecated Soon](modernization/promisification.md)**
### `<webview>.capturePage([rect])`
* `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured.

View file

@ -86,9 +86,6 @@ for (const name of events) {
})
}
// Function Deprecations
app.getFileIcon = deprecate.promisify(app.getFileIcon)
// Property Deprecations
deprecate.fnToProperty(app, 'accessibilitySupportEnabled', '_isAccessibilitySupportEnabled', '_setAccessibilitySupportEnabled')
deprecate.fnToProperty(app, 'badgeCount', '_getBadgeCount', '_setBadgeCount')

View file

@ -1,14 +1,5 @@
'use strict'
const { deprecate } = require('electron')
const contentTracing = process.electronBinding('content_tracing')
const contentTracing =
contentTracing.getCategories = deprecate.promisify(contentTracing.getCategories)
contentTracing.startRecording = deprecate.promisify(contentTracing.startRecording)
contentTracing.stopRecording = deprecate.promisify(contentTracing.stopRecording)
contentTracing.getTraceBufferUsage = deprecate.promisifyMultiArg(
contentTracing.getTraceBufferUsage
// convertPromiseValue: Temporarily disabled until it's used
/* (value) => [value.paths, value.bookmarks] */
)
module.exports = contentTracing
module.exports = process.electronBinding('content_tracing')

View file

@ -216,8 +216,3 @@ module.exports = {
return binding.showCertificateTrustDialog(window, certificate, message)
}
}
module.exports.showMessageBox = deprecate.promisify(module.exports.showMessageBox)
module.exports.showOpenDialog = deprecate.promisify(module.exports.showOpenDialog)
module.exports.showSaveDialog = deprecate.promisify(module.exports.showSaveDialog)
module.exports.showCertificateTrustDialog = deprecate.promisify(module.exports.showCertificateTrustDialog)

View file

@ -20,6 +20,3 @@ if (process.platform === 'darwin') {
getReceiptURL: () => ''
}
}
module.exports.purchaseProduct = deprecate.promisify(module.exports.purchaseProduct)
module.exports.getProducts = deprecate.promisify(module.exports.getProducts)

View file

@ -22,21 +22,3 @@ Object.setPrototypeOf(Cookies.prototype, EventEmitter.prototype)
Session.prototype._init = function () {
app.emit('session-created', this)
}
Session.prototype.clearStorageData = deprecate.promisify(Session.prototype.clearStorageData)
Session.prototype.clearHostResolverCache = deprecate.promisify(Session.prototype.clearHostResolverCache)
Session.prototype.resolveProxy = deprecate.promisify(Session.prototype.resolveProxy)
Session.prototype.setProxy = deprecate.promisify(Session.prototype.setProxy)
Session.prototype.getCacheSize = deprecate.promisify(Session.prototype.getCacheSize)
Session.prototype.clearCache = deprecate.promisify(Session.prototype.clearCache)
Session.prototype.clearAuthCache = deprecate.promisify(Session.prototype.clearAuthCache)
Session.prototype.getBlobData = deprecate.promisifyMultiArg(Session.prototype.getBlobData)
Cookies.prototype.flushStore = deprecate.promisify(Cookies.prototype.flushStore)
Cookies.prototype.get = deprecate.promisify(Cookies.prototype.get)
Cookies.prototype.remove = deprecate.promisify(Cookies.prototype.remove)
Cookies.prototype.set = deprecate.promisify(Cookies.prototype.set)
NetLog.prototype.stopLogging = deprecate.promisify(NetLog.prototype.stopLogging)
Protocol.prototype.isProtocolHandled = deprecate.promisify(Protocol.prototype.isProtocolHandled)

View file

@ -202,30 +202,6 @@ WebContents.prototype.executeJavaScript = function (code, hasUserGesture) {
}
}
// TODO(codebytere): remove when promisifications is complete
const nativeZoomLevel = WebContents.prototype.getZoomLevel
WebContents.prototype.getZoomLevel = function (callback) {
if (callback == null) {
return nativeZoomLevel.call(this)
} else {
process.nextTick(() => {
callback(nativeZoomLevel.call(this))
})
}
}
// TODO(codebytere): remove when promisifications is complete
const nativeZoomFactor = WebContents.prototype.getZoomFactor
WebContents.prototype.getZoomFactor = function (callback) {
if (callback == null) {
return nativeZoomFactor.call(this)
} else {
process.nextTick(() => {
callback(nativeZoomFactor.call(this))
})
}
}
// Translate the options of printToPDF.
WebContents.prototype.printToPDF = function (options) {
const printingSetting = Object.assign({}, defaultPrintingSetting)
@ -306,11 +282,6 @@ WebContents.prototype.loadFile = function (filePath, options = {}) {
}))
}
WebContents.prototype.capturePage = deprecate.promisify(WebContents.prototype.capturePage)
WebContents.prototype.executeJavaScript = deprecate.promisify(WebContents.prototype.executeJavaScript)
WebContents.prototype.printToPDF = deprecate.promisify(WebContents.prototype.printToPDF)
WebContents.prototype.savePage = deprecate.promisify(WebContents.prototype.savePage)
const addReplyToEvent = (event) => {
event.reply = (...args) => {
event.sender.sendToFrame(event.frameId, ...args)
@ -452,9 +423,6 @@ WebContents.prototype._init = function () {
// JavaScript wrapper of Debugger.
const { Debugger } = process.electronBinding('debugger')
Debugger.prototype.sendCommand = deprecate.promisify(Debugger.prototype.sendCommand)
Object.setPrototypeOf(Debugger.prototype, EventEmitter.prototype)
// Public APIs.

View file

@ -19,7 +19,7 @@ function mapSources (sources) {
}))
}
const getSources = (options) => {
exports.getSources = (options) => {
return new Promise((resolve, reject) => {
if (!isValid(options)) throw new Error('Invalid options')
@ -40,5 +40,3 @@ const getSources = (options) => {
.then(sources => resolve(mapSources(sources)), reject)
})
}
exports.getSources = deprecate.promisify(getSources)

View file

@ -85,15 +85,6 @@ function getWebFrame (context: Window) {
return context ? new WebFrame(context) : null
}
const promisifiedMethods = new Set<string>([
'executeJavaScript',
'executeJavaScriptInIsolatedWorld'
])
for (const method of promisifiedMethods) {
(WebFrame as any).prototype[method] = deprecate.promisify((WebFrame as any).prototype[method])
}
const _webFrame = new WebFrame(window)
export default _webFrame

View file

@ -1,4 +1,4 @@
import { deprecate, remote, webFrame } from 'electron'
import { remote, webFrame } from 'electron'
import * as ipcRendererUtils from '@electron/internal/renderer/ipc-renderer-internal-utils'
import * as guestViewInternal from '@electron/internal/renderer/web-view/guest-view-internal'
@ -273,7 +273,7 @@ export const setupMethods = (WebViewElement: typeof ElectronInternal.WebViewElem
}
for (const method of asyncPromiseMethods) {
(WebViewElement.prototype as Record<string, any>)[method] = deprecate.promisify(createPromiseHandler(method))
(WebViewElement.prototype as Record<string, any>)[method] = createPromiseHandler(method)
}
}

View file

@ -22,7 +22,7 @@
"colors": "^1.1.2",
"dotenv-safe": "^4.0.4",
"dugite": "^1.45.0",
"electron-docs-linter": "^3.0.1",
"electron-docs-linter": "^3.0.3",
"electron-typescript-definitions": "^8.3.0",
"eslint": "^5.13.0",
"eslint-config-standard": "^12.0.0",

View file

@ -412,7 +412,7 @@ describe('app module', () => {
await w.loadURL('about:blank')
const promise = emittedOnce(app, 'desktop-capturer-get-sources')
w.webContents.executeJavaScript(`require('electron').desktopCapturer.getSources({ types: ['screen'] }, () => {})`)
w.webContents.executeJavaScript(`require('electron').desktopCapturer.getSources({ types: ['screen'] })`)
const [, webContents] = await promise
expect(webContents).to.equal(w.webContents)
@ -856,15 +856,6 @@ describe('app module', () => {
expect(icon.isEmpty()).to.equal(false)
})
// TODO(codebytere): remove when promisification is complete
it('fetches a non-empty icon (callback)', (done) => {
app.getFileIcon(iconPath, (error, icon) => {
expect(error).to.equal(null)
expect(icon.isEmpty()).to.equal(false)
done()
})
})
it('fetches normal icon size by default', async () => {
const icon = await app.getFileIcon(iconPath)
const size = icon.getSize()
@ -873,18 +864,6 @@ describe('app module', () => {
expect(size.width).to.equal(sizes.normal)
})
// TODO(codebytere): remove when promisification is complete
it('fetches normal icon size by default (callback)', (done) => {
app.getFileIcon(iconPath, (error, icon) => {
expect(error).to.equal(null)
const size = icon.getSize()
expect(size.height).to.equal(sizes.normal)
expect(size.width).to.equal(sizes.normal)
done()
})
})
describe('size option', () => {
it('fetches a small icon', async () => {
const icon = await app.getFileIcon(iconPath, { size: 'small' })
@ -902,18 +881,6 @@ describe('app module', () => {
expect(size.width).to.equal(sizes.normal)
})
// TODO(codebytere): remove when promisification is complete
it('fetches a normal icon (callback)', (done) => {
app.getFileIcon(iconPath, { size: 'normal' }, (error, icon) => {
expect(error).to.equal(null)
const size = icon.getSize()
expect(size.height).to.equal(sizes.normal)
expect(size.width).to.equal(sizes.normal)
done()
})
})
it('fetches a large icon', async () => {
// macOS does not support large icons
if (process.platform === 'darwin') return

View file

@ -547,19 +547,6 @@ describe('BrowserWindow module', () => {
expect(image.isEmpty()).to.be.true()
})
// TODO(codebytere): remove when promisification is complete
it('returns a Promise with a Buffer (callback)', (done) => {
w.capturePage({
x: 0,
y: 0,
width: 100,
height: 100
}, (image) => {
expect(image.isEmpty()).to.be.true()
done()
})
})
it('preserves transparency', async () => {
const w = await openTheWindow({
show: false,
@ -579,30 +566,6 @@ describe('BrowserWindow module', () => {
// Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
expect(imgBuffer[25]).to.equal(6)
})
// TODO(codebytere): remove when promisification is complete
it('preserves transparency (callback)', (done) => {
openTheWindow({
show: false,
width: 400,
height: 400,
transparent: true
}).then(w => {
const p = emittedOnce(w, 'ready-to-show')
w.loadURL('data:text/html,<html><body background-color: rgba(255,255,255,0)></body></html>')
p.then(() => {
w.show()
w.capturePage((image) => {
const imgBuffer = image.toPNG()
// Check the 25th byte in the PNG.
// Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
expect(imgBuffer[25]).to.equal(6)
done()
})
})
})
})
})
describe('BrowserWindow.setBounds(bounds[, animate])', () => {
@ -3096,13 +3059,14 @@ describe('BrowserWindow module', () => {
w.destroy()
w = new BrowserWindow()
w.webContents.once('did-finish-load', () => {
w.once('enter-full-screen', () => {
w.once('leave-html-full-screen', () => {
done()
w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true).then(() => {
w.once('enter-full-screen', () => {
w.once('leave-html-full-screen', () => {
done()
})
w.setFullScreen(false)
})
w.setFullScreen(false)
})
w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true)
})
w.loadURL('about:blank')
})
@ -3265,7 +3229,7 @@ describe('BrowserWindow module', () => {
const lastPanelId = UI.inspectorView._tabbedPane._tabs.peekLast().id
UI.inspectorView.showPanel(lastPanelId)
}
devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false, () => {
devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false).then(() => {
showPanelTimeoutId = setTimeout(show, 100)
})
}
@ -3466,47 +3430,22 @@ describe('BrowserWindow module', () => {
URIError
])
it('doesnt throw when no calback is provided', () => {
const result = ipcRenderer.sendSync('executeJavaScript', code, false)
assert.strictEqual(result, 'success')
})
it('returns result when calback is provided', (done) => {
ipcRenderer.send('executeJavaScript', code, true)
ipcRenderer.once('executeJavaScript-response', function (event, result) {
assert.strictEqual(result, expected)
done()
})
})
it('returns result if the code returns an asyncronous promise', (done) => {
ipcRenderer.send('executeJavaScript', asyncCode, true)
ipcRenderer.once('executeJavaScript-response', (event, result) => {
assert.strictEqual(result, expected)
done()
})
})
it('resolves the returned promise with the result when a callback is specified', (done) => {
ipcRenderer.send('executeJavaScript', code, true)
ipcRenderer.once('executeJavaScript-promise-response', (event, result) => {
assert.strictEqual(result, expected)
done()
})
})
it('resolves the returned promise with the result when no callback is specified', (done) => {
ipcRenderer.send('executeJavaScript', code, false)
it('resolves the returned promise with the result', (done) => {
ipcRenderer.send('executeJavaScript', code)
ipcRenderer.once('executeJavaScript-promise-response', (event, result) => {
assert.strictEqual(result, expected)
done()
})
})
it('resolves the returned promise with the result if the code returns an asyncronous promise', (done) => {
ipcRenderer.send('executeJavaScript', asyncCode, true)
ipcRenderer.send('executeJavaScript', asyncCode)
ipcRenderer.once('executeJavaScript-promise-response', (event, result) => {
assert.strictEqual(result, expected)
done()
})
})
it('rejects the returned promise if an async error is thrown', (done) => {
ipcRenderer.send('executeJavaScript', badAsyncCode, true)
ipcRenderer.send('executeJavaScript', badAsyncCode)
ipcRenderer.once('executeJavaScript-promise-error', (event, error) => {
assert.strictEqual(error, expectedErrorMsg)
done()
@ -3515,7 +3454,7 @@ describe('BrowserWindow module', () => {
it('rejects the returned promise with an error if an Error.prototype is thrown', async () => {
for (const error in errorTypes) {
await new Promise((resolve) => {
ipcRenderer.send('executeJavaScript', `Promise.reject(new ${error.name}("Wamp-wamp")`, true)
ipcRenderer.send('executeJavaScript', `Promise.reject(new ${error.name}("Wamp-wamp")`)
ipcRenderer.once('executeJavaScript-promise-error-name', (event, name) => {
assert.strictEqual(name, error.name)
resolve()
@ -3523,6 +3462,7 @@ describe('BrowserWindow module', () => {
})
}
})
it('works after page load and during subframe load', (done) => {
w.webContents.once('did-finish-load', () => {
// initiate a sub-frame load, then try and execute script during it
@ -3530,23 +3470,25 @@ describe('BrowserWindow module', () => {
var iframe = document.createElement('iframe')
iframe.src = '${server.url}/slow'
document.body.appendChild(iframe)
`, () => {
w.webContents.executeJavaScript('console.log(\'hello\')', () => {
`).then(() => {
w.webContents.executeJavaScript('console.log(\'hello\')').then(() => {
done()
})
})
})
w.loadURL(server.url)
})
it('executes after page load', (done) => {
w.webContents.executeJavaScript(code, (result) => {
w.webContents.executeJavaScript(code).then(result => {
assert.strictEqual(result, expected)
done()
})
w.loadURL(server.url)
})
it('works with result objects that have DOM class prototypes', (done) => {
w.webContents.executeJavaScript('document.location', (result) => {
w.webContents.executeJavaScript('document.location').then(result => {
assert.strictEqual(result.origin, server.url)
assert.strictEqual(result.protocol, 'http:')
done()

View file

@ -38,35 +38,6 @@ describe('contentTracing', () => {
return resultFilePath
}
// TODO(codebytere): remove when promisification is complete
const recordCallback = async (options, outputFilePath, recordTimeInMilliseconds = 1e3) => {
await app.whenReady()
await startRecording(options)
await timeout(recordTimeInMilliseconds)
const resultFilePath = await stopRecording(outputFilePath)
return resultFilePath
}
// TODO(codebytere): remove when promisification is complete
const startRecording = async (options) => {
return new Promise((resolve) => {
contentTracing.startRecording(options, () => {
resolve()
})
})
}
// TODO(codebytere): remove when promisification is complete
const stopRecording = async (filePath) => {
return new Promise((resolve) => {
contentTracing.stopRecording(filePath, (resultFilePath) => {
resolve(resultFilePath)
})
})
}
const outputFilePath = getPathInATempFolder('trace.json')
beforeEach(() => {
if (fs.existsSync(outputFilePath)) {
@ -95,18 +66,6 @@ describe('contentTracing', () => {
`the trace output file is empty, check "${outputFilePath}"`)
})
// TODO(codebytere): remove when promisification is complete
it('accepts an empty config (callback)', async () => {
const config = {}
await recordCallback(config, outputFilePath)
expect(fs.existsSync(outputFilePath)).to.be.true()
const fileSizeInKiloBytes = getFileSizeInKiloBytes(outputFilePath)
expect(fileSizeInKiloBytes).to.be.above(0,
`the trace output file is empty, check "${outputFilePath}"`)
})
it('accepts a trace config', async () => {
// (alexeykuzmin): All categories are excluded on purpose,
// so only metadata gets into the output file.
@ -129,29 +88,6 @@ describe('contentTracing', () => {
check "${outputFilePath}"`)
})
// TODO(codebytere): remove when promisification is complete
it('accepts a trace config (callback)', async () => {
// (alexeykuzmin): All categories are excluded on purpose,
// so only metadata gets into the output file.
const config = {
excluded_categories: ['*']
}
await recordCallback(config, outputFilePath)
expect(fs.existsSync(outputFilePath)).to.be.true()
// If the `excluded_categories` param above is not respected
// the file size will be above 50KB.
const fileSizeInKiloBytes = getFileSizeInKiloBytes(outputFilePath)
const expectedMaximumFileSize = 10 // Depends on a platform.
expect(fileSizeInKiloBytes).to.be.above(0,
`the trace output file is empty, check "${outputFilePath}"`)
expect(fileSizeInKiloBytes).to.be.below(expectedMaximumFileSize,
`the trace output file is suspiciously large (${fileSizeInKiloBytes}KB),
check "${outputFilePath}"`)
})
it('accepts "categoryFilter" and "traceOptions" as a config', async () => {
// (alexeykuzmin): All categories are excluded on purpose,
// so only metadata gets into the output file.
@ -174,30 +110,6 @@ describe('contentTracing', () => {
`the trace output file is suspiciously large (${fileSizeInKiloBytes}KB),
check "${outputFilePath}"`)
})
// TODO(codebytere): remove when promisification is complete
it('accepts "categoryFilter" and "traceOptions" as a config (callback)', async () => {
// (alexeykuzmin): All categories are excluded on purpose,
// so only metadata gets into the output file.
const config = {
categoryFilter: '__ThisIsANonexistentCategory__',
traceOptions: ''
}
await recordCallback(config, outputFilePath)
expect(fs.existsSync(outputFilePath)).to.be.true()
// If the `categoryFilter` param above is not respected
// the file size will be above 50KB.
const fileSizeInKiloBytes = getFileSizeInKiloBytes(outputFilePath)
const expectedMaximumFileSize = 10 // Depends on a platform.
expect(fileSizeInKiloBytes).to.be.above(0,
`the trace output file is empty, check "${outputFilePath}"`)
expect(fileSizeInKiloBytes).to.be.below(expectedMaximumFileSize,
`the trace output file is suspiciously large (${fileSizeInKiloBytes}KB),
check "${outputFilePath}"`)
})
})
describe('stopRecording', function () {
@ -208,12 +120,6 @@ describe('contentTracing', () => {
expect(resultFilePath).to.be.a('string').and.be.equal(outputFilePath)
})
// TODO(codebytere): remove when promisification is complete
it('calls its callback with a result file path (callback)', async () => {
const resultFilePath = await recordCallback(/* options */ {}, outputFilePath)
expect(resultFilePath).to.be.a('string').and.be.equal(outputFilePath)
})
it('creates a temporary file when an empty string is passed', async function () {
const resultFilePath = await record(/* options */ {}, /* outputFilePath */ '')
expect(resultFilePath).to.be.a('string').that.is.not.empty()

View file

@ -116,28 +116,6 @@ describe('debugger module', () => {
w.webContents.debugger.detach()
})
// TODO(miniak): remove when promisification is complete
it('returns response (callback)', done => {
w.webContents.loadURL('about:blank')
try {
w.webContents.debugger.attach()
} catch (err) {
return done(`unexpected error : ${err}`)
}
const callback = (err, res) => {
expect(err).to.be.null()
expect(res.wasThrown).to.be.undefined()
expect(res.result.value).to.equal(6)
w.webContents.debugger.detach()
done()
}
const params = { 'expression': '4+2' }
w.webContents.debugger.sendCommand('Runtime.evaluate', params, callback)
})
it('returns response when devtools is opened', async () => {
w.webContents.loadURL('about:blank')
w.webContents.debugger.attach()
@ -155,28 +133,6 @@ describe('debugger module', () => {
w.webContents.debugger.detach()
})
// TODO(miniak): remove when promisification is complete
it('returns response when devtools is opened (callback)', done => {
w.webContents.loadURL('about:blank')
try {
w.webContents.debugger.attach()
} catch (err) {
return done(`unexpected error : ${err}`)
}
const callback = (err, res) => {
expect(err).to.be.null()
expect(res.wasThrown).to.be.undefined()
expect(res.result.value).to.equal(6)
w.webContents.debugger.detach()
done()
}
w.webContents.openDevTools()
w.webContents.once('devtools-opened', () => {
const params = { 'expression': '4+2' }
w.webContents.debugger.sendCommand('Runtime.evaluate', params, callback)
})
})
it('fires message event', done => {
const url = process.platform !== 'win32'
? `file://${path.join(fixtures, 'pages', 'a.html')}`
@ -212,22 +168,6 @@ describe('debugger module', () => {
w.webContents.debugger.detach()
})
// TODO(miniak): remove when promisification is complete
it('returns error message when command fails (callback)', done => {
w.webContents.loadURL('about:blank')
try {
w.webContents.debugger.attach()
} catch (err) {
done(`unexpected error : ${err}`)
}
w.webContents.debugger.sendCommand('Test', (err, res) => {
expect(err).to.be.an.instanceOf(Error).with.property('message', "'Test' wasn't found")
w.webContents.debugger.detach()
done()
})
})
it('handles valid unicode characters in message', (done) => {
try {
w.webContents.debugger.attach()
@ -239,7 +179,7 @@ describe('debugger module', () => {
if (method === 'Network.loadingFinished') {
w.webContents.debugger.sendCommand('Network.getResponseBody', {
requestId: params.requestId
}, (_, data) => {
}).then(data => {
expect(data.body).to.equal('\u0024')
done()
})

View file

@ -30,15 +30,6 @@ describe('desktopCapturer', () => {
expect(sources).to.be.an('array').that.is.not.empty()
})
// TODO(codebytere): remove when promisification is complete
it('should return a non-empty array of sources (callback)', (done) => {
desktopCapturer.getSources({ types: ['window', 'screen'] }, (err, sources) => {
expect(sources).to.be.an('array').that.is.not.empty()
expect(err).to.be.null()
done()
})
})
it('throws an error for invalid options', async () => {
const promise = desktopCapturer.getSources(['window', 'screen'])
expect(promise).to.be.eventually.rejectedWith(Error, 'Invalid options')
@ -60,20 +51,6 @@ describe('desktopCapturer', () => {
expect(promise2).to.not.eventually.be.rejected()
})
// TODO(codebytere): remove when promisification is complete
it('responds to subsequent calls of different options (callback)', (done) => {
let callCount = 0
const callback = (err, sources) => {
callCount++
expect(err).to.be.null()
expect(sources).to.not.be.null()
if (callCount === 2) done()
}
desktopCapturer.getSources({ types: ['window'] }, callback)
desktopCapturer.getSources({ types: ['screen'] }, callback)
})
it('returns an empty display_id for window sources on Windows and Mac', async () => {
// Linux doesn't return any window sources.
if (process.platform !== 'win32' && process.platform !== 'darwin') return

View file

@ -43,37 +43,13 @@ describe('inAppPurchase module', function () {
expect(success).to.be.false()
})
// TODO(codebytere): remove when promisification is complete
it('purchaseProduct() fails when buying invalid product (callback)', done => {
inAppPurchase.purchaseProduct('non-exist', 1, success => {
expect(success).to.be.false()
done()
})
})
it('purchaseProduct() accepts optional arguments', async () => {
const success = await inAppPurchase.purchaseProduct('non-exist')
expect(success).to.be.false()
})
// TODO(codebytere): remove when promisification is complete
it('purchaseProduct() accepts optional arguments (callback)', done => {
inAppPurchase.purchaseProduct('non-exist', success => {
expect(success).to.be.false()
done()
})
})
it('getProducts() returns an empty list when getting invalid product', async () => {
const products = await inAppPurchase.getProducts(['non-exist'])
expect(products).to.be.an('array').of.length(0)
})
// TODO(codebytere): remove when promisification is complete
it('getProducts() returns an empty list when getting invalid product (callback)', done => {
inAppPurchase.getProducts(['non-exist'], products => {
expect(products).to.be.an('array').of.length(0)
done()
})
})
})

View file

@ -78,27 +78,6 @@ describe('netLog module', () => {
expect(fs.existsSync(dumpFileDynamic)).to.be.true()
})
// TODO(miniak): remove when promisification is complete
it('should begin and end logging to file when .startLogging() and .stopLogging() is called (callback)', done => {
expect(netLog.currentlyLogging).to.be.false()
expect(netLog.currentlyLoggingPath).to.equal('')
netLog.startLogging(dumpFileDynamic)
expect(netLog.currentlyLogging).to.be.true()
expect(netLog.currentlyLoggingPath).to.equal(dumpFileDynamic)
netLog.stopLogging((path) => {
expect(netLog.currentlyLogging).to.be.false()
expect(netLog.currentlyLoggingPath).to.equal('')
expect(path).to.equal(dumpFileDynamic)
expect(fs.existsSync(dumpFileDynamic)).to.be.true()
done()
})
})
it('should silence when .stopLogging() is called without calling .startLogging()', async () => {
expect(netLog.currentlyLogging).to.be.false()
expect(netLog.currentlyLoggingPath).to.equal('')
@ -111,21 +90,6 @@ describe('netLog module', () => {
expect(path).to.equal('')
})
// TODO(miniak): remove when promisification is complete
it('should silence when .stopLogging() is called without calling .startLogging() (callback)', done => {
expect(netLog.currentlyLogging).to.be.false()
expect(netLog.currentlyLoggingPath).to.equal('')
netLog.stopLogging(path => {
expect(netLog.currentlyLogging).to.be.false()
expect(netLog.currentlyLoggingPath).to.equal('')
expect(path).to.equal('')
done()
})
})
it('should begin and end logging automatically when --log-net-log is passed', done => {
if (isCI && process.platform === 'linux') {
done()

View file

@ -686,27 +686,11 @@ describe('protocol module', () => {
assert.strictEqual(result, true)
})
// TODO(codebytere): remove when promisification is complete
it('returns true for about: (callback)', (done) => {
protocol.isProtocolHandled('about', (result) => {
assert.strictEqual(result, true)
done()
})
})
it('returns true for file:', async () => {
const result = await protocol.isProtocolHandled('file')
assert.strictEqual(result, true)
})
// TODO(codebytere): remove when promisification is complete
it('returns true for file: (callback)', (done) => {
protocol.isProtocolHandled('file', (result) => {
assert.strictEqual(result, true)
done()
})
})
it('returns true for http:', async () => {
const result = await protocol.isProtocolHandled('http')
assert.strictEqual(result, true)
@ -732,18 +716,6 @@ describe('protocol module', () => {
})
})
// TODO(codebytere): remove when promisification is complete
it('returns true for custom protocol (callback)', (done) => {
const emptyHandler = (request, callback) => callback()
protocol.registerStringProtocol(protocolName, emptyHandler, (error) => {
assert.strictEqual(error, null)
protocol.isProtocolHandled(protocolName, (result) => {
assert.strictEqual(result, true)
done()
})
})
})
it('returns true for intercepted protocol', (done) => {
const emptyHandler = (request, callback) => callback()
protocol.interceptStringProtocol('http', emptyHandler, async (error) => {
@ -753,18 +725,6 @@ describe('protocol module', () => {
done()
})
})
// TODO(codebytere): remove when promisification is complete
it('returns true for intercepted protocol (callback)', (done) => {
const emptyHandler = (request, callback) => callback()
protocol.interceptStringProtocol('http', emptyHandler, (error) => {
assert.strictEqual(error, null)
protocol.isProtocolHandled('http', (result) => {
assert.strictEqual(result, true)
done()
})
})
})
})
describe('protocol.intercept(Any)Protocol', () => {

View file

@ -71,7 +71,7 @@ describe('session module', () => {
const name = '0'
const value = '0'
it('should get cookies with promises', (done) => {
it('should get cookies', (done) => {
const server = http.createServer((req, res) => {
res.setHeader('Set-Cookie', [`${name}=${value}`])
res.end('finished')
@ -90,27 +90,7 @@ describe('session module', () => {
})
})
it('should get cookies with callbacks', (done) => {
const server = http.createServer((req, res) => {
res.setHeader('Set-Cookie', [`${name}=${value}`])
res.end('finished')
server.close()
})
server.listen(0, '127.0.0.1', () => {
w.webContents.once('did-finish-load', () => {
w.webContents.session.cookies.get({ url }, (error, list) => {
if (error) return done(error)
const cookie = list.find(cookie => cookie.name === name)
expect(cookie).to.exist.and.to.have.property('value', value)
done()
})
})
const { port } = server.address()
w.loadURL(`${url}:${port}`)
})
})
it('sets cookies with promises', async () => {
it('sets cookies', async () => {
const { cookies } = session.defaultSession
const name = '1'
const value = '1'
@ -118,13 +98,6 @@ describe('session module', () => {
await cookies.set({ url, name, value })
})
it('sets cookies with callbacks', (done) => {
const { cookies } = session.defaultSession
const name = '1'
const value = '1'
cookies.set({ url, name, value }, (error, list) => done(error))
})
it('yields an error when setting a cookie with missing required fields', async () => {
let error
try {
@ -150,7 +123,7 @@ describe('session module', () => {
}
})
it('should remove cookies with promises', async () => {
it('should remove cookies', async () => {
const { cookies } = session.defaultSession
const name = '2'
const value = '2'
@ -162,24 +135,6 @@ describe('session module', () => {
assert(!list.some(cookie => cookie.name === name && cookie.value === value))
})
it('should remove cookies with callbacks', (done) => {
const { cookies } = session.defaultSession
const name = '2'
const value = '2'
cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 }, (error) => {
if (error) return done(error)
cookies.remove(url, name, (error) => {
if (error) return done(error)
cookies.get({ url }, (error, list) => {
if (error) return done(error)
assert(!list.some(cookie => cookie.name === name))
done()
})
})
})
})
it('should set cookie for standard scheme', async () => {
const { cookies } = session.defaultSession
const standardScheme = remote.getGlobal('standardScheme')
@ -220,39 +175,13 @@ describe('session module', () => {
})
describe('ses.cookies.flushStore()', async () => {
describe('flushes the cookies to disk and invokes the callback when done', async () => {
it('with promises', async () => {
const name = 'foo'
const value = 'bar'
const { cookies } = session.defaultSession
describe('flushes the cookies to disk', async () => {
const name = 'foo'
const value = 'bar'
const { cookies } = session.defaultSession
await cookies.set({ url, name, value })
await cookies.flushStore()
})
it('with callbacks', (done) => {
const name = 'foo'
const value = 'bar'
const { cookies } = session.defaultSession
cookies.set({ url, name, value }, (error) => {
if (error) return done(error)
cookies.flushStore(error => done(error))
})
})
})
})
describe('ses.cookies.flushStore(callback)', () => {
it('flushes the cookies to disk and invokes the callback when done', (done) => {
session.defaultSession.cookies.set({
url: url,
name: 'foo',
value: 'bar'
}, (error) => {
if (error) return done(error)
session.defaultSession.cookies.flushStore(() => done())
})
await cookies.set({ url, name, value })
await cookies.flushStore()
})
})
@ -304,26 +233,6 @@ describe('session module', () => {
})
w.loadFile(path.join(fixtures, 'api', 'localstorage.html'))
})
// TODO(codebytere): remove when promisification is complete
it('clears localstorage data (callback)', (done) => {
ipcMain.on('count', (event, count) => {
ipcMain.removeAllListeners('count')
assert.strictEqual(count, 0)
done()
})
w.webContents.on('did-finish-load', () => {
const options = {
origin: 'file://',
storages: ['localstorage'],
quotas: ['persistent']
}
w.webContents.session.clearStorageData(options, () => {
w.webContents.send('getcount')
})
})
w.loadFile(path.join(fixtures, 'api', 'localstorage.html'))
})
})
describe('will-download event', () => {
@ -627,17 +536,6 @@ describe('session module', () => {
assert.strictEqual(proxy, 'PROXY myproxy:80')
})
// TODO(codebytere): remove when Promisification is complete
it('allows configuring proxy settings (callback)', (done) => {
const config = { proxyRules: 'http=myproxy:80' }
customSession.setProxy(config, () => {
customSession.resolveProxy('http://example.com/', proxy => {
assert.strictEqual(proxy, 'PROXY myproxy:80')
done()
})
})
})
it('allows removing the implicit bypass rules for localhost', async () => {
const config = {
proxyRules: 'http=myproxy:80',
@ -649,20 +547,6 @@ describe('session module', () => {
assert.strictEqual(proxy, 'PROXY myproxy:80')
})
// TODO(codebytere): remove when Promisification is complete
it('allows removing the implicit bypass rules for localhost (callback)', (done) => {
const config = {
proxyRules: 'http=myproxy:80',
proxyBypassRules: '<-loopback>'
}
customSession.setProxy(config).then(() => {
customSession.resolveProxy('http://localhost').then(proxy => {
assert.strictEqual(proxy, 'PROXY myproxy:80')
done()
})
})
})
it('allows configuring proxy settings with pacScript', async () => {
server = http.createServer((req, res) => {
const pac = `
@ -690,30 +574,6 @@ describe('session module', () => {
})
})
// TODO(codebytere): reconfigure when Promisification is complete
it('allows configuring proxy settings with pacScript (callback)', (done) => {
server = http.createServer((req, res) => {
const pac = `
function FindProxyForURL(url, host) {
return "PROXY myproxy:8132";
}
`
res.writeHead(200, {
'Content-Type': 'application/x-ns-proxy-autoconfig'
})
res.end(pac)
})
server.listen(0, '127.0.0.1', () => {
const config = { pacScript: `http://127.0.0.1:${server.address().port}` }
customSession.setProxy(config, () => {
customSession.resolveProxy('https://google.com', proxy => {
assert.strictEqual(proxy, 'PROXY myproxy:8132')
done()
})
})
})
})
it('allows bypassing proxy settings', async () => {
const config = {
proxyRules: 'http=myproxy:80',
@ -723,20 +583,6 @@ describe('session module', () => {
const proxy = await customSession.resolveProxy('http://example/')
assert.strictEqual(proxy, 'DIRECT')
})
// TODO(codebytere): remove when Promisification is complete
it('allows bypassing proxy settings (callback)', (done) => {
const config = {
proxyRules: 'http=myproxy:80',
proxyBypassRules: '<local>'
}
customSession.setProxy(config, () => {
customSession.resolveProxy('http://example/', proxy => {
assert.strictEqual(proxy, 'DIRECT')
done()
})
})
})
})
describe('ses.getBlobData()', () => {
@ -982,59 +828,6 @@ describe('session module', () => {
issueLoginRequest()
})
})
// TODO(codebytere): remove when promisification complete
it('can clear http auth info from cache (callback)', (done) => {
const ses = session.fromPartition('auth-cache')
const server = http.createServer((req, res) => {
const credentials = auth(req)
if (!credentials || credentials.name !== 'test' || credentials.pass !== 'test') {
res.statusCode = 401
res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"')
res.end()
} else {
res.end('authenticated')
}
})
server.listen(0, '127.0.0.1', () => {
const port = server.address().port
function issueLoginRequest (attempt = 1) {
if (attempt > 2) {
server.close()
return done()
}
const request = net.request({
url: `http://127.0.0.1:${port}`,
session: ses
})
request.on('login', (info, callback) => {
attempt += 1
assert.strictEqual(info.scheme, 'basic')
assert.strictEqual(info.realm, 'Restricted')
callback('test', 'test')
})
request.on('response', (response) => {
let data = ''
response.pause()
response.on('data', (chunk) => {
data += chunk
})
response.on('end', () => {
assert.strictEqual(data, 'authenticated')
ses.clearAuthCache({ type: 'password' }, () => {
issueLoginRequest(attempt)
})
})
response.on('error', (error) => { done(error) })
response.resume()
})
// Internal api to bypass cache for testing.
request.urlRequest._setLoadFlags(1 << 1)
request.end()
}
issueLoginRequest()
})
})
})
describe('ses.setPermissionRequestHandler(handler)', () => {

View file

@ -85,20 +85,17 @@ describe('renderer nodeIntegrationInSubFrames', () => {
w.loadFile(path.resolve(__dirname, `fixtures/sub-frames/frame-container${fixtureSuffix}.html`))
const details = await detailsPromise
const senders = details.map(event => event[0].sender)
await new Promise((resolve) => {
await new Promise(async resolve => {
let resultCount = 0
senders.forEach(sender => {
sender.webContents.executeJavaScript('window.isolatedGlobal', result => {
if (webPreferences.contextIsolation) {
expect(result).to.be.null()
} else {
expect(result).to.equal(true)
}
resultCount++
if (resultCount === senders.length) {
resolve()
}
})
senders.forEach(async sender => {
const result = await sender.webContents.executeJavaScript('window.isolatedGlobal')
if (webPreferences.contextIsolation) {
expect(result).to.be.null()
} else {
expect(result).to.equal(true)
}
resultCount++
if (resultCount === senders.length) resolve()
})
})
})

View file

@ -184,18 +184,16 @@ describe('webContents module', () => {
})
describe('setDevToolsWebContents() API', () => {
it('sets arbitry webContents as devtools', (done) => {
it('sets arbitrary webContents as devtools', async () => {
const devtools = new BrowserWindow({ show: false })
devtools.webContents.once('dom-ready', () => {
assert.ok(devtools.getURL().startsWith('chrome-devtools://devtools'))
devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name', (name) => {
assert.ok(name, 'InspectorFrontendHostImpl')
devtools.destroy()
done()
})
})
const promise = emittedOnce(devtools.webContents, 'dom-ready')
w.webContents.setDevToolsWebContents(devtools.webContents)
w.webContents.openDevTools()
await promise
expect(devtools.getURL().startsWith('chrome-devtools://devtools')).to.be.true()
const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name')
expect(result).to.equal('InspectorFrontendHostImpl')
devtools.destroy()
})
})
@ -478,20 +476,16 @@ describe('webContents module', () => {
})
})
it('supports inserting CSS', (done) => {
it('supports inserting CSS', async () => {
w.loadURL('about:blank')
w.webContents.insertCSS('body { background-repeat: round; }')
w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")', (result) => {
assert.strictEqual(result, 'round')
done()
})
const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")')
expect(result).to.equal('round')
})
it('supports inspecting an element in the devtools', (done) => {
w.loadURL('about:blank')
w.webContents.once('devtools-opened', () => {
done()
})
w.webContents.once('devtools-opened', () => { done() })
w.webContents.inspectElement(10, 10)
})
@ -578,20 +572,6 @@ describe('webContents module', () => {
}
})
// TODO(codebytere): remove when promisification is complete
it('can set the correct zoom level (callback)', async () => {
try {
await w.loadURL('about:blank')
const zoomLevel = await new Promise(resolve => w.webContents.getZoomLevel(resolve))
expect(zoomLevel).to.eql(0.0)
w.webContents.setZoomLevel(0.5)
const newZoomLevel = await new Promise(resolve => w.webContents.getZoomLevel(resolve))
expect(newZoomLevel).to.eql(0.5)
} finally {
w.webContents.setZoomLevel(0)
}
})
it('can persist zoom level across navigation', (done) => {
let finalNavigation = false
ipcMain.on('set-zoom', (e, host) => {
@ -732,7 +712,7 @@ describe('webContents module', () => {
`
w.webContents.on('did-finish-load', () => {
if (initialNavigation) {
w.webContents.executeJavaScript(source, () => {})
w.webContents.executeJavaScript(source)
} else {
const zoomLevel = w.webContents.getZoomLevel()
assert.strictEqual(zoomLevel, 0)
@ -1066,24 +1046,6 @@ describe('webContents module', () => {
const result = await w.webContents.executeJavaScript('37 + 5')
assert.strictEqual(result, 42)
})
// TODO(miniak): remove when promisification is complete
it('responds to executeJavaScript (callback)', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
})
w.webContents.once('did-finish-load', () => {
w.webContents.executeJavaScript('37 + 5', (result) => {
assert.strictEqual(result, 42)
done()
})
})
w.loadURL('about:blank')
})
})
describe('preload-error event', () => {
@ -1306,25 +1268,5 @@ describe('webContents module', () => {
assert.strictEqual(data instanceof Buffer, true)
assert.notStrictEqual(data.length, 0)
})
// TODO(miniak): remove when promisification is complete
it('can print to PDF (callback)', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
})
w.webContents.once('did-finish-load', () => {
w.webContents.printToPDF({}, function (error, data) {
assert.strictEqual(error, null)
assert.strictEqual(data instanceof Buffer, true)
assert.notStrictEqual(data.length, 0)
done()
})
})
w.loadURL('data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E')
})
})
})

View file

@ -1347,11 +1347,11 @@ describe('chromium feature', () => {
describe('window.history.pushState', () => {
it('should push state after calling history.pushState() from the same url', (done) => {
w = new BrowserWindow({ show: false })
w.webContents.once('did-finish-load', () => {
w.webContents.once('did-finish-load', async () => {
// History should have current page by now.
assert.strictEqual(w.webContents.length(), 1)
w.webContents.executeJavaScript('window.history.pushState({}, "")', () => {
w.webContents.executeJavaScript('window.history.pushState({}, "")').then(() => {
// Initial page + pushed state
assert.strictEqual(w.webContents.length(), 2)
done()

View file

@ -52,33 +52,27 @@ describe('chrome extension content scripts', () => {
return closeWindow(w).then(() => { w = null })
})
it('should run content script at document_start', (done) => {
it('should run content script at document_start', () => {
addExtension('content-script-document-start')
w.webContents.once('dom-ready', () => {
w.webContents.executeJavaScript('document.documentElement.style.backgroundColor', (result) => {
expect(result).to.equal('red')
done()
})
w.webContents.once('dom-ready', async () => {
const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor')
expect(result).to.equal('red')
})
w.loadURL('about:blank')
})
it('should run content script at document_idle', (done) => {
it('should run content script at document_idle', async () => {
addExtension('content-script-document-idle')
w.loadURL('about:blank')
w.webContents.executeJavaScript('document.body.style.backgroundColor', (result) => {
expect(result).to.equal('red')
done()
})
const result = await w.webContents.executeJavaScript('document.body.style.backgroundColor')
expect(result).to.equal('red')
})
it('should run content script at document_end', (done) => {
it('should run content script at document_end', () => {
addExtension('content-script-document-end')
w.webContents.once('did-finish-load', () => {
w.webContents.executeJavaScript('document.documentElement.style.backgroundColor', (result) => {
expect(result).to.equal('red')
done()
})
w.webContents.once('did-finish-load', async () => {
const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor')
expect(result).to.equal('red')
})
w.loadURL('about:blank')
})

View file

@ -7,7 +7,7 @@ if (process.isMainFrame) {
if (!frame) {
throw new Error(`Can't find frame for routing ID ${frameRoutingId}`)
}
frame.executeJavaScript(code, false, result => {
frame.executeJavaScript(code, false).then(result => {
event.sender.send(`executeJavaScriptInFrame_${responseId}`, result)
})
})

View file

@ -217,18 +217,8 @@ app.on('ready', function () {
event.returnValue = null
})
ipcMain.on('executeJavaScript', function (event, code, hasCallback) {
let promise
if (hasCallback) {
promise = window.webContents.executeJavaScript(code, (result) => {
window.webContents.send('executeJavaScript-response', result)
})
} else {
promise = window.webContents.executeJavaScript(code)
}
promise.then((result) => {
ipcMain.on('executeJavaScript', function (event, code) {
window.webContents.executeJavaScript(code).then((result) => {
window.webContents.send('executeJavaScript-promise-response', result)
}).catch((error) => {
window.webContents.send('executeJavaScript-promise-error', error)
@ -237,10 +227,6 @@ app.on('ready', function () {
window.webContents.send('executeJavaScript-promise-error-name', error.name)
}
})
if (!hasCallback) {
event.returnValue = 'success'
}
})
})

View file

@ -92,14 +92,14 @@ app.on('ready', () => {
printBackground: true,
printSelectionOnly: true,
landscape: true
}, (error: Error, data: Buffer) => console.log(error))
}).then((data: Buffer) => console.log(data))
mainWindow.webContents.printToPDF({}, (err, data) => console.log(err))
mainWindow.webContents.printToPDF({}).then(data => console.log(data))
mainWindow.webContents.executeJavaScript('return true;').then((v: boolean) => console.log(v))
mainWindow.webContents.executeJavaScript('return true;', true).then((v: boolean) => console.log(v))
mainWindow.webContents.executeJavaScript('return true;', true)
mainWindow.webContents.executeJavaScript('return true;', true, (result: boolean) => console.log(result))
mainWindow.webContents.executeJavaScript('return true;', true).then((result: boolean) => console.log(result))
mainWindow.webContents.insertText('blah, blah, blah')
mainWindow.webContents.startDrag({ file: '/path/to/img.png', icon: nativeImage.createFromPath('/path/to/icon.png') })
mainWindow.webContents.findInPage('blah')
@ -138,10 +138,10 @@ app.on('ready', () => {
})
mainWindow.webContents.debugger.sendCommand('Network.enable')
mainWindow.webContents.capturePage((image) => {
mainWindow.webContents.capturePage().then(image => {
console.log(image.toDataURL())
})
mainWindow.webContents.capturePage({ x: 0, y: 0, width: 100, height: 200 }, (image) => {
mainWindow.webContents.capturePage({ x: 0, y: 0, width: 100, height: 200 }).then(image => {
console.log(image.toPNG())
})
})
@ -467,11 +467,11 @@ const options = {
traceOptions: 'record-until-full,enable-sampling'
}
contentTracing.startRecording(options, function () {
contentTracing.startRecording(options).then(() => {
console.log('Tracing started')
setTimeout(function () {
contentTracing.stopRecording('', function (path) {
console.log('Tracing data recorded to ' + path)
contentTracing.stopRecording('').then(path => {
console.log(`Tracing data recorded to ${path}`)
})
}, 5000)
})
@ -850,7 +850,7 @@ app.on('ready', () => {
console.log(error ? error.message : 'ok')
})
protocol.isProtocolHandled('atom', (handled) => {
protocol.isProtocolHandled('atom').then(handled => {
console.log(handled)
})
})

View file

@ -5,7 +5,6 @@ import {
webFrame,
clipboard,
crashReporter,
nativeImage,
screen,
shell
} from 'electron'
@ -34,7 +33,7 @@ remote.getCurrentWindow().on('close', () => {
// blabla...
})
remote.getCurrentWindow().capturePage(buf => {
remote.getCurrentWindow().capturePage().then(buf => {
fs.writeFile('/tmp/screenshot.png', buf, err => {
console.log(err)
})
@ -42,7 +41,7 @@ remote.getCurrentWindow().capturePage(buf => {
remote.getCurrentWebContents().print()
remote.getCurrentWindow().capturePage(buf => {
remote.getCurrentWindow().capturePage().then(buf => {
remote.require('fs').writeFile('/tmp/screenshot.png', buf, (err: Error) => {
console.log(err)
})
@ -75,7 +74,7 @@ webFrame.insertText('text')
webFrame.executeJavaScript('return true;').then((v: boolean) => console.log(v))
webFrame.executeJavaScript('return true;', true).then((v: boolean) => console.log(v))
webFrame.executeJavaScript('return true;', true)
webFrame.executeJavaScript('return true;', true, (result: boolean) => console.log(result))
webFrame.executeJavaScript('return true;', true).then((result: boolean) => console.log(result))
console.log(webFrame.getResourceUsage())
webFrame.clearCache()
@ -111,8 +110,7 @@ crashReporter.start({
const desktopCapturer = require('electron').desktopCapturer
desktopCapturer.getSources({ types: ['window', 'screen'] }, function (error, sources) {
if (error) throw error
desktopCapturer.getSources({ types: ['window', 'screen'] }).then(sources => {
for (let i = 0; i < sources.length; ++i) {
if (sources[i].name == 'Electron') {
(navigator as any).webkitGetUserMedia({
@ -253,7 +251,7 @@ webview.addEventListener('ipc-message', function (event) {
console.log(event.channel) // Prints "pong"
})
webview.send('ping')
webview.capturePage((image) => { console.log(image) })
webview.capturePage().then(image => { console.log(image) })
{
const opened: boolean = webview.isDevToolsOpened()

View file

@ -1000,23 +1000,6 @@ describe('<webview> tag', function () {
const result = await webview.executeJavaScript(jsScript)
assert.strictEqual(result, expectedResult)
})
// TODO(miniak): remove when promisification is complete
it('can return the result of the executed script (callback)', async () => {
await loadWebView(webview, {
src: 'about:blank'
})
const jsScript = "'4'+2"
const expectedResult = '42'
const result = await new Promise((resolve) => {
webview.executeJavaScript(jsScript, false, (result) => {
resolve(result)
})
})
assert.strictEqual(result, expectedResult)
})
})
describe('sendInputEvent', () => {
@ -1272,21 +1255,6 @@ describe('<webview> tag', function () {
assert.strictEqual(data instanceof Buffer, true)
assert.notStrictEqual(data.length, 0)
})
// TODO(miniak): remove when promisification is complete
it('can print to PDF (callback)', (done) => {
webview.addEventListener('did-finish-load', () => {
webview.printToPDF({}, function (error, data) {
assert.strictEqual(error, null)
assert.strictEqual(data instanceof Buffer, true)
assert.notStrictEqual(data.length, 0)
done()
})
})
webview.src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'
document.body.appendChild(webview)
})
})
// FIXME(deepak1556): Ch69 follow up.