DEV Community

Sony AK
Sony AK

Posted on

How to use Playwright with external/existing Chrome

Mostly example using Playwright in JavaScript is using Chromium that bundled with Playwright. How about if we want to use existing or external Chrome?

No worries, it means you have to set the Playwright to connect to a Chromium instance manually using Chrome DevTools Protocol (CDP) and that means you should run the Chrome with --remote-debugging-port=9222.

For the external Chrome I recommend using Chrome for Testing that is good for this situation. Just to to https://developer.chrome.com/blog/chrome-for-testing to read more.

I have created the repository and quick script sample about this. Just go to https://github.com/sonyarianto/playwright-using-external-chrome

Wanna quick try? Here is the script index.js.

import { chromium } from 'playwright';

(async () => {
    try {
        const browser = await chromium.connectOverCDP('http://localhost:9222');

        console.log(browser.isConnected() && 'Connected to Chrome.');
        console.log(`Contexts in CDP session: ${browser.contexts().length}.`);

        const context = browser.contexts()[0];

        const page = await context.newPage();
        await page.goto('https://example.com');
        await page.screenshot({ path: 'example.png' });

        await page.close();
        await context.close();
        await browser.close();
    } catch (error) {
        console.log('Cannot connect to Chrome.');
    }
})();
Enter fullscreen mode Exit fullscreen mode

Then run it like this. Make sure you already run the Chrome first (with argument --remote-debugging-port=9222).

node ./index.js
Enter fullscreen mode Exit fullscreen mode

Happy using Playwright.

Top comments (1)

Collapse
 
vlatkodimeski profile image
driveIN

good job man!
Thanks!