#54488: fix: throw instead of crashing when nativeImage cannot create a Buffer
Description of Change
toPNG(), toJPEG(), toBitmap(), getBitmap() and getNativeHandle() on a NativeImage crash the renderer when they are called from a context that has no Node.js environment: a sandboxed preload script, a service worker preload script, or a sandboxed page holding the result of <webview>.capturePage(). Node.js throws ERR_BUFFER_CONTEXT_NOT_AVAILABLE and returns an empty handle when asked for a Buffer there, and each method called ToLocalChecked() on it. Reproduces on 43.7.2, 44.4.5 and 45.0.0-alpha.12.
The methods now return the empty handle, so the error Node.js threw reaches the caller as a normal exception. toBitmap() allocates its Buffer before reading pixels, so it throws before doing the work and a failed allocation throws too. Built and run on Linux; getNativeHandle() is covered by the new spec on macOS only.
Checklist
- I have built and tested this change
- I have filled out the PR description
- I have reviewed and verified the changes
- tests are changed or added
- relevant API documentation, tutorials, and examples are updated and follow the documentation style guide
Release Notes
Notes: Fixed a renderer crash calling image.toPNG() from a sandboxed preload script.
Backports
Semver Impact
Semantic Versioning helps users understand the impact of updates:
- Major (X.y.z): Breaking changes that may require code modifications
- Minor (x.Y.z): New features that maintain backward compatibility
- Patch (x.y.Z): Bug fixes that don't change the API
- None: Changes that don't affect using facing parts of Electron