Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I render web pages with Electron without showing them to the user?

I need to render a web page in an Electron app and take a screenshot without showing this web page to the user. How should I do it? What's the best method?

I tried creating a webview element and hiding by giving it an absolute positioning and -99999px top and left, but every now and then the capturePage method stalls forever. When I make it visible by using the inspector to remove that CSS, it looks blank but immediately the page renders and the callback is called.

I tried offscreen rendering starting a BrowserWindow, but it actually creates another window, with no title bar, that looks like this:enter image description here

Any ideas how to make any of these work or another method?

like image 210
pupeno Avatar asked Oct 18 '22 10:10

pupeno


1 Answers

Try this. This example saves the file as a png to the local computer.

const { app, BrowserWindow } = require('electron')
const fs = require("fs")

app.disableHardwareAcceleration()

let win
app.once('ready', () => {
    win = new BrowserWindow({
        webPreferences: {
            offscreen: true
        }
    })
    win.loadURL('http://github.com')
    win.webContents.on('paint', (event, dirty, image) => {
        // Example Code
        fs.writeFile('ex.png', image.toPNG(), (err) => {
            if (err) throw err;
            console.log('The file has been saved!');
        })
    })
    win.webContents.setFrameRate(30)
})
like image 192
fall simply Avatar answered Oct 21 '22 06:10

fall simply