Reputation: 287460
I'm trying to use capturePage on a window in Electron and when the window is not visible because it's obscure entirely by other windows, it dumps an empty PNG.
I tried passing these options individually when creating the window but they made not difference:
useContentSize: true,
enableLargerThanScreen: true
webPreferences: {
offscreen: true
webgl: false
}
Any ideas how to make it work?
Upvotes: 3
Views: 3436
Reputation: 369
First of all @pergy answer works, thanks him for that.
I want to share some changes ([email protected]) and some hacks:
If you want to use this method not inside root BrowserWindow
, but somewhere inside your application you will be unable to use new BrowserWindow()
, instead you should add enableRemoteModule: true
in root BrowserWindow, and use new remote.BrowserWindow()
where you want inside your application;
I prefer to use dom-ready
event not did-stop-loading
, on this moment the page have been loaded but annoying widgets are not;
I'm not sure if win.capturePage
will work, it's recommended to use win.webContents.capturePage()
Upvotes: 0
Reputation: 5531
The following code works for hidden, offscreen and visible browser windows as well even when they're covered by other windows
const {app, BrowserWindow} = require('electron')
const fs = require('fs')
app.on('ready', () => {
let win = new BrowserWindow({
show: false // or true
})
win.webContents.on('did-stop-loading', () => {
win.capturePage((image) => {
fs.writeFile('test.png', image.toPNG(), (err) => {
if (err) throw err
console.log('It\'s saved!')
app.quit()
})
})
})
win.loadURL('http://github.com')
})
If you receive empty PNG with this code it indicates that browser window is not ready for capture yet. It might be the situation in your case, too!
capturePage
seems to be missing some pieces of the webview in the created image in older electron versions sometimes (experienced in 1.8.4)
Upvotes: 7