Hugues M.
Hugues M.

Reputation: 20467

Capture screenshot of Electron window before quitting

In an Electron app, I can take a screenshot of my window from the main process using this:

let win = new BrowserWindow(/* ... */);
let capturedPicFilePath = /* where I want that saved */
win.capturePage((img) => {
    fs.writeFile(capturedPicFilePath, img.toPng(), () => console.log(`Saved ${capturedPicFilePath}`))
})

Awesome. Now I'd like to do that right before app quits. Electron emits a particular event for that, that I tried to use:

Event: 'before-quit' : emitted before the application starts closing its windows.

Problem: if I use the same code as above in a handler for that event, the file is created but empty.

I'm guessing it's because the screenshot is taken in an asynchronous way, and the window is already closed when it happens.

So this does not work for me:

app.on('before-quit', (event) => {
    win.capturePage(function(img) {
        fs.writeFile(capturedPicFilePath, img.toPng(), () => console.log(`Saved ${capturedPicFilePath}`))
    })
})

Edit 1 : Doing this in the renderer process with window.onbeforeunload fails too. It's also too late to perform the screenshot. I get this in the main console (i.e. it goes to terminal):

Attempting to call a function in a renderer window that has been closed or released.

Context: for now I'm exploring the limits of what is possible to do with screen capture (essentially for support purposes), and found that one. Not sure yet what I would do with that edge case, I thought about it not just for support, I'm also considering displaying at startup a blurred pic of previous state (some parts of my app take 1-2 seconds to load).

Any ideas?

Upvotes: 2

Views: 1768

Answers (1)

Sean
Sean

Reputation: 1464

I have had a similar problem before, I got around it by using the window close event and then preventing it from closing. Once my action had performed I then ran app.quit().

window.on('close', function (event) {
    event.preventDefault();

    let capturedPicFilePath = /* where you want it saved */
    window.capturePage((img) => {
        fs.writeFile(capturedPicFilePath, img.toPng(), () => 
        console.log(`Saved ${capturedPicFilePath}`));

        app.quit(); // quit once screenshot has saved.
    });
});

Hope this helps!

Upvotes: 2

Related Questions