From 511dcf9d32638c8b6166dad90b11d432e79f2dd2 Mon Sep 17 00:00:00 2001 From: Tony Brix Date: Thu, 9 May 2019 18:24:52 -0500 Subject: [PATCH] feat(browser): Add browser.isConnected() (#4403) Add `browser.isConnected()` to the public api to be able to tell when the browser is connected fixes https://github.com/smooth-code/jest-puppeteer/pull/237#issuecomment-490260041 --- docs/api.md | 7 +++++++ experimental/puppeteer-firefox/lib/Browser.js | 7 +++++++ lib/Browser.js | 7 +++++++ test/browser.spec.js | 10 ++++++++++ 4 files changed, 31 insertions(+) diff --git a/docs/api.md b/docs/api.md index b56cb08c..b01dd5e7 100644 --- a/docs/api.md +++ b/docs/api.md @@ -48,6 +48,7 @@ * [browser.createIncognitoBrowserContext()](#browsercreateincognitobrowsercontext) * [browser.defaultBrowserContext()](#browserdefaultbrowsercontext) * [browser.disconnect()](#browserdisconnect) + * [browser.isConnected()](#browserisconnected) * [browser.newPage()](#browsernewpage) * [browser.pages()](#browserpages) * [browser.process()](#browserprocess) @@ -700,6 +701,12 @@ Returns the default browser context. The default browser context can not be clos Disconnects Puppeteer from the browser, but leaves the Chromium process running. After calling `disconnect`, the [Browser] object is considered disposed and cannot be used anymore. +#### browser.isConnected() + +- returns: <[boolean]> + +Indicates that the browser is connected. + #### browser.newPage() - returns: <[Promise]<[Page]>> diff --git a/experimental/puppeteer-firefox/lib/Browser.js b/experimental/puppeteer-firefox/lib/Browser.js index 44a1768b..5d2169fe 100644 --- a/experimental/puppeteer-firefox/lib/Browser.js +++ b/experimental/puppeteer-firefox/lib/Browser.js @@ -57,6 +57,13 @@ class Browser extends EventEmitter { this._connection.dispose(); } + /** + * @return {boolean} + */ + isConnected() { + return !this._connection._closed; + } + /** * @return {!BrowserContext} */ diff --git a/lib/Browser.js b/lib/Browser.js index 88c177ad..1b6d600f 100644 --- a/lib/Browser.js +++ b/lib/Browser.js @@ -260,6 +260,13 @@ class Browser extends EventEmitter { this._connection.dispose(); } + /** + * @return {boolean} + */ + isConnected() { + return !this._connection._closed; + } + /** * @return {!Promise} */ diff --git a/test/browser.spec.js b/test/browser.spec.js index c821c34b..614a045b 100644 --- a/test/browser.spec.js +++ b/test/browser.spec.js @@ -60,4 +60,14 @@ module.exports.addTests = function({testRunner, expect, headless, puppeteer, CHR await remoteBrowser.disconnect(); }); }); + + describe('Browser.isConnected', () => { + it('should set the browser connected state', async({browser}) => { + const browserWSEndpoint = browser.wsEndpoint(); + const newBrowser = await puppeteer.connect({browserWSEndpoint}); + expect(newBrowser.isConnected()).toBe(true); + await newBrowser.disconnect(); + expect(newBrowser.isConnected()).toBe(false); + }); + }); };