17

Is it possible to connect a browser to puppeteer without instantiating it in puppeteer? For example, running an instance of chromium like a regular user and then connecting that to an instance of puppeteer in code?

hardkoded
  • 18,915
  • 3
  • 52
  • 64
Jak
  • 181
  • 1
  • 2
  • 6

3 Answers3

31

The answer is Yes and No.

You can connect to an existing using the connect function:

const browserURL = 'http://127.0.0.1:21222';
const browser = await puppeteer.connect({browserURL});

But, if you want to use those 2 lines you need to launch Chrome with the "--remote-debugging-port=21222 argument.

hardkoded
  • 18,915
  • 3
  • 52
  • 64
  • Thanks, very helpful. How about if I want to launch with Chromium? Would I still have to launch with any added arguments? – Jak Mar 11 '19 at 20:14
  • 1
    @Jak yes, you always need to tell Chrome that he has to "open the doors" for remote debugging. – hardkoded Mar 11 '19 at 20:29
  • Alright that makes sense. I am having some trouble finding any sort of documentation to help identify the appropriate browserURL for my instance of Chrome. Do you have any suggestions? – Jak Mar 12 '19 at 01:35
  • @Jak If you launch chromium with the flag `--remote-debugging-port=21222`, you will know that the `browserURL` (not the browserWSEndpoint) will be `http://127.0.0.1:21222` – hardkoded Mar 12 '19 at 12:18
  • 12
    I opened chromium with command `chromium-browser --remote-debugging-port=21222`. but when connect, I get an error `Error: connect ECONNREFUSED 127.0.0.1:21222`. – Jason Zhou Mar 05 '20 at 04:56
  • hi , i wonder if there is a way to automatically for puppeteer to find an available port and connect to it ? – Taha Daboussi Jun 09 '21 at 07:19
2

I believe you need to connect to an address ended with an id:

ws://127.0.0.1:9222/devtools/browser/{id}

When you launch Chrome with --remote-debugging-port, you'll see something like

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222   [17:57:55]

...

DevTools listening on ws://127.0.0.1:9222/devtools/browser/44b3c476-5524-497e-9918-d73fa39e40cf

The address on the last line is what you need, i.e.

const browser = await puppeteer.connect({
    browserWSEndpoint: "ws://127.0.0.1:9222/devtools/browser/44b3c476-5524-497e-9918-d73fa39e40cf"
});
laike9m
  • 18,344
  • 20
  • 107
  • 140
  • I found that running the command from @hardkoded answer multiple times would fail randomly. It turned out that id at the end of the url was changing every time I executed the terminal command. Sometimes the puppeteer call to connect to the browserURL would guess the wrong ID. Supplying that id (44b3..) via the browserWEEndpoint was necessary for multiple sequential attempts to always work. – NicoWheat Jul 11 '23 at 20:35
0

Above the previous comment you have to write in options browserURL:

const browserUrl = 'http://127.0.0.1:9222';

const browser = await puppeteer.connect({browserURL: browserUrl});