From d9997c303f6173e74444473cd1972eb4aa2b4113 Mon Sep 17 00:00:00 2001 From: Shelley Vohr Date: Tue, 9 Mar 2021 05:51:44 -0800 Subject: [PATCH] fix: capturePage not resolving with hidden windows (#27883) --- docs/api/browser-window.md | 2 +- shell/browser/api/electron_api_web_contents.cc | 12 ++++++++++++ spec-main/api-browser-window-spec.ts | 16 ++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 9d150fe155c..1939430b4b6 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -1370,7 +1370,7 @@ Returns `Boolean` - Whether the window's document has been edited. Returns `Promise` - Resolves with a [NativeImage](native-image.md) -Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. +Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. If the page is not visible, `rect` may be empty. #### `win.loadURL(url[, options])` diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc index bd5adffaf75..5d8395996c3 100644 --- a/shell/browser/api/electron_api_web_contents.cc +++ b/shell/browser/api/electron_api_web_contents.cc @@ -2758,6 +2758,18 @@ v8::Local WebContents::CapturePage(gin::Arguments* args) { return handle; } +#if !defined(OS_MAC) + // If the view's renderer is suspended this may fail on Windows/Linux - + // bail if so. See CopyFromSurface in + // content/public/browser/render_widget_host_view.h. + auto* rfh = web_contents()->GetMainFrame(); + if (rfh && + rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { + promise.Resolve(gfx::Image()); + return handle; + } +#endif // defined(OS_MAC) + // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); diff --git a/spec-main/api-browser-window-spec.ts b/spec-main/api-browser-window-spec.ts index dd02458ff67..0c53edd1b0f 100644 --- a/spec-main/api-browser-window-spec.ts +++ b/spec-main/api-browser-window-spec.ts @@ -1338,6 +1338,22 @@ describe('BrowserWindow module', () => { expect(image.isEmpty()).to.equal(true); }); + it('resolves after the window is hidden', async () => { + const w = new BrowserWindow({ show: false }); + w.loadFile(path.join(fixtures, 'pages', 'a.html')); + await emittedOnce(w, 'ready-to-show'); + w.show(); + + const visibleImage = await w.capturePage(); + expect(visibleImage.isEmpty()).to.equal(false); + + w.hide(); + + const hiddenImage = await w.capturePage(); + const isEmpty = process.platform !== 'darwin'; + expect(hiddenImage.isEmpty()).to.equal(isEmpty); + }); + it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html'));