Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 57 additions & 8 deletions src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,14 @@ import type {
ChromeReleaseChannel,
LaunchOptions,
Target,
BrowsersChromeReleaseChannel,
} from './third_party/index.js';
import {
puppeteer,
resolveDefaultUserDataDir,
detectBrowserPlatform,
BrowserEnum,
} from './third_party/index.js';
import {puppeteer} from './third_party/index.js';

let browser: Browser | undefined;

Expand Down Expand Up @@ -49,6 +55,7 @@ export async function ensureBrowserConnected(options: {
wsHeaders?: Record<string, string>;
devtools: boolean;
channel?: Channel;
userDataDir?: string;
}) {
const {channel} = options;
if (browser?.connected) {
Expand All @@ -68,15 +75,57 @@ export async function ensureBrowserConnected(options: {
}
} else if (options.browserURL) {
connectOptions.browserURL = options.browserURL;
} else if (channel) {
const puppeteerChannel =
channel !== 'stable'
? (`chrome-${channel}` as ChromeReleaseChannel)
: 'chrome';
connectOptions.channel = puppeteerChannel;
} else if (channel || options.userDataDir) {
let userDataDir = options.userDataDir;
if (!userDataDir) {
if (!channel) {
throw new Error('Channel must be provided if userDataDir is missing');
}
const platform = detectBrowserPlatform();
if (!platform) {
throw new Error('Could not detect required browser platform');
}
userDataDir = resolveDefaultUserDataDir(
BrowserEnum.CHROME,
platform,
(channel === 'stable'
? 'chrome'
: `chrome-${channel}`) as BrowsersChromeReleaseChannel,
);
}

// TODO: re-expose this logic via Puppeteer.
const portPath = path.join(userDataDir, 'DevToolsActivePort');
try {
const fileContent = await fs.promises.readFile(portPath, 'utf8');
const [rawPort, rawPath] = fileContent
.split('\n')
.map(line => {
return line.trim();
})
.filter(line => {
return !!line;
});
if (!rawPort || !rawPath) {
throw new Error(`Invalid DevToolsActivePort '${fileContent}' found`);
}
const port = parseInt(rawPort, 10);
if (isNaN(port) || port <= 0 || port > 65535) {
throw new Error(`Invalid port '${rawPort}' found`);
}
const browserWSEndpoint = `ws://127.0.0.1:${port}${rawPath}`;
connectOptions.browserWSEndpoint = browserWSEndpoint;
} catch (error) {
throw new Error(
`Could not connect to Chrome in ${userDataDir}. Check if Chrome is running and remote debugging is enabled.`,
{
cause: error,
},
);
}
} else {
throw new Error(
'Either browserURL, wsEndpoint or channel must be provided',
'Either browserURL, wsEndpoint, channel or userDataDir must be provided',
);
}

Expand Down
2 changes: 1 addition & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const cliOptions = {
type: 'boolean',
description:
'If specified, automatically connects to a browser (Chrome 145+) running in the user data directory identified by the channel param.',
conflicts: ['isolated', 'executablePath', 'userDataDir'],
conflicts: ['isolated', 'executablePath'],
default: false,
coerce: (value: boolean | undefined) => {
if (!value) {
Expand Down
1 change: 1 addition & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ async function getContext(): Promise<McpContext> {
wsHeaders: args.wsHeaders,
// Important: only pass channel, if autoConnect is true.
channel: args.autoConnect ? (args.channel as Channel) : undefined,
userDataDir: args.userDataDir,
devtools,
})
: await ensureBrowserLaunched({
Expand Down
6 changes: 6 additions & 0 deletions src/third_party/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,9 @@ export {
export {default as puppeteer} from 'puppeteer-core';
export type * from 'puppeteer-core';
export type {CdpPage} from 'puppeteer-core/internal/cdp/Page.js';
export {
resolveDefaultUserDataDir,
detectBrowserPlatform,
Browser as BrowserEnum,
type ChromeReleaseChannel as BrowsersChromeReleaseChannel,
} from '@puppeteer/browsers';
25 changes: 24 additions & 1 deletion tests/browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {describe, it} from 'node:test';

import {executablePath} from 'puppeteer';

import {launch} from '../src/browser.js';
import {ensureBrowserConnected, launch} from '../src/browser.js';

describe('browser', () => {
it('cannot launch multiple times with the same profile', async () => {
Expand Down Expand Up @@ -73,4 +73,27 @@ describe('browser', () => {
await browser.close();
}
});
it('connects to an existing browser with userDataDir', async () => {
const tmpDir = os.tmpdir();
const folderPath = path.join(tmpDir, `temp-folder-${crypto.randomUUID()}`);
const browser = await launch({
headless: true,
isolated: false,
userDataDir: folderPath,
executablePath: executablePath(),
devtools: false,
args: ['--remote-debugging-port=0'],
});
try {
const connectedBrowser = await ensureBrowserConnected({
userDataDir: folderPath,
devtools: false,
});
assert.ok(connectedBrowser);
assert.ok(connectedBrowser.isConnected());
connectedBrowser.disconnect();
} finally {
await browser.close();
}
});
});
Loading