title: Capture screenshot of Electron window before quitting
body: <p>In an Electron app, I can take a screenshot of my window from the main process using this:</p>
  
  <pre><code>let win = new BrowserWindow(/* ... */);
  let capturedPicFilePath = /* where I want that saved */
  win.capturePage((img) =&gt; {
      fs.writeFile(capturedPicFilePath, img.toPng(), () =&gt; console.log(`Saved ${capturedPicFilePath}`))
  })
  </code></pre>
  
  <p>Awesome. Now I'd like to do that right before app quits. Electron emits a <a href="https://github.com/electron/electron/blob/master/docs/api/app.md#event-before-quit" rel="nofollow noreferrer">particular event</a> for that, that I tried to use:</p>
  
  <blockquote>
    <p>Event: <code>'before-quit'</code> : emitted before the application starts closing its windows.</p>
  </blockquote>
  
  <p><strong>Problem</strong>: if I use the same code as above in a handler for that event, the file is created but empty.</p>
  
  <p>I'm guessing it's because the screenshot is taken in an asynchronous way, and the window is already closed when it happens.</p>
  
  <p>So this does not work for me:</p>
  
  <pre><code>app.on('before-quit', (event) =&gt; {
      win.capturePage(function(img) {
          fs.writeFile(capturedPicFilePath, img.toPng(), () =&gt; console.log(`Saved ${capturedPicFilePath}`))
      })
  })
  </code></pre>
  
  <p>Edit 1 : Doing this in the renderer process with <code>window.onbeforeunload</code> fails too. It's also too late to perform the screenshot. I get this in the main console (i.e. it goes to terminal):</p>
  
  <blockquote>
    <p>Attempting to call a function in a renderer window that has been closed or released.</p>
  </blockquote>
  
  <p>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).</p>
  
  <p>Any ideas?</p>