Skip to content

Commit 02974f0

Browse files
authored
Merge pull request #14 from browserbase/anirudh/add-examples
Add examples from core
2 parents b201252 + ba41701 commit 02974f0

32 files changed

+10149
-837
lines changed

.env.example

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
BROWSERBASE_API_KEY="your-api-key-here"
2+
BROWSERBASE_PROJECT_ID="your-project-id-here"

.github/workflows/ci.yml

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ jobs:
1212
lint:
1313
name: lint
1414
runs-on: ubuntu-latest
15-
1615

1716
steps:
1817
- uses: actions/checkout@v4
@@ -31,7 +30,6 @@ jobs:
3130
build:
3231
name: build
3332
runs-on: ubuntu-latest
34-
3533

3634
steps:
3735
- uses: actions/checkout@v4
@@ -63,4 +61,3 @@ jobs:
6361

6462
- name: Run tests
6563
run: ./scripts/test
66-

.github/workflows/release-doctor.yml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,3 @@ jobs:
1919
bash ./bin/check-release-environment
2020
env:
2121
NPM_TOKEN: ${{ secrets.BROWSERBASE_NPM_TOKEN || secrets.NPM_TOKEN }}
22-

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,4 @@ dist
88
/*.tgz
99
.idea/
1010

11+
.env
6 KB
Binary file not shown.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
*.zip
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<html>
2+
<body>
3+
<h1>Hello Extensions</h1>
4+
</body>
5+
</html>
Loading
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"manifest_version": 3,
3+
"name": "Browserbase Extension Test",
4+
"description": "Test extension for browserbase",
5+
"version": "1.0",
6+
"action": {
7+
"default_popup": "hello.html"
8+
},
9+
"content_scripts": [
10+
{
11+
"matches": ["https://www.browserbase.com/*"],
12+
"js": ["scripts/content.js"]
13+
}
14+
],
15+
"web_accessible_resources": [
16+
{
17+
"resources": ["images/logo.png"],
18+
"matches": ["https://www.browserbase.com/*"]
19+
}
20+
]
21+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/* eslint-disable prettier/prettier */
2+
const imageUrl = chrome.runtime.getURL('images/logo.png');
3+
window
4+
.fetch(imageUrl)
5+
.then((response) => {
6+
if (response.ok) {
7+
console.log('browserbase test extension image loaded');
8+
}
9+
})
10+
.catch((error) => {
11+
console.log(error);
12+
});

examples/packages/logo.png

5.81 KB
Loading

examples/playwright-basic.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { chromium } from 'playwright-core';
2+
import Browserbase from 'browserbase/index';
3+
4+
const BROWSERBASE_API_KEY = process.env['BROWSERBASE_API_KEY']!;
5+
const BROWSERBASE_PROJECT_ID = process.env['BROWSERBASE_PROJECT_ID']!;
6+
7+
const bb = new Browserbase({
8+
apiKey: BROWSERBASE_API_KEY,
9+
});
10+
11+
(async () => {
12+
// Create a new session
13+
const session = await bb.sessions.create({
14+
projectId: BROWSERBASE_PROJECT_ID,
15+
});
16+
17+
// Connect to the session
18+
const browser = await chromium.connectOverCDP(session.connectUrl);
19+
20+
// Getting the default context to ensure the sessions are recorded.
21+
const defaultContext = browser.contexts()[0];
22+
const page = defaultContext?.pages()[0];
23+
24+
await page?.goto('https://browserbase.com/');
25+
await page?.close();
26+
await browser.close();
27+
console.log(`Session complete! View replay at https://browserbase.com/sessions/${session.id}`);
28+
})().catch((error) => console.error(error.message));

examples/playwright-captcha.ts

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import Browserbase from 'browserbase/index';
2+
import { chromium } from 'playwright-core';
3+
4+
// Configuration
5+
const DEFAULT_CAPTCHA_URL = 'https://2captcha.com/demo/recaptcha-v2';
6+
const OVERRIDE_TIMEOUT = 60_000; // 1 minute in milliseconds
7+
const BROWSERBASE_PROJECT_ID = process.env['BROWSERBASE_PROJECT_ID']!;
8+
const BROWSERBASE_API_KEY = process.env['BROWSERBASE_API_KEY']!;
9+
10+
const bb = new Browserbase({
11+
apiKey: BROWSERBASE_API_KEY,
12+
});
13+
14+
async function solveCaptcha() {
15+
// Create a session with captcha solving enabled
16+
const session = await bb.sessions.create({
17+
projectId: BROWSERBASE_PROJECT_ID,
18+
browserSettings: {
19+
solveCaptchas: true,
20+
},
21+
proxies: true,
22+
});
23+
try {
24+
// Connect to the browser
25+
const browser = await chromium.connectOverCDP(session.connectUrl);
26+
27+
const context = browser.contexts()[0]!;
28+
const page = context.pages()[0]!;
29+
30+
let captchaSolvingStarted = false;
31+
let captchaSolvingFinished = false;
32+
33+
// Listen for console messages
34+
page.on('console', (msg) => {
35+
if (msg.text() === 'browserbase-solving-started') {
36+
captchaSolvingStarted = true;
37+
console.log('Captcha solving started...');
38+
page.evaluate(() => {
39+
// @ts-ignore
40+
window.captchaSolvingFinished = false;
41+
});
42+
} else if (msg.text() === 'browserbase-solving-finished') {
43+
captchaSolvingFinished = true;
44+
console.log('Captcha solving finished!');
45+
page.evaluate(() => {
46+
// @ts-ignore
47+
window.captchaSolvingFinished = true;
48+
});
49+
}
50+
});
51+
52+
// Navigate to the captcha page
53+
console.log('Navigating to captcha page...');
54+
await page.goto(DEFAULT_CAPTCHA_URL, { waitUntil: 'networkidle' });
55+
56+
// Wait for captcha to be solved
57+
// @ts-ignore
58+
await page.waitForFunction(() => window.captchaSolvingFinished === true, null, {
59+
timeout: OVERRIDE_TIMEOUT,
60+
});
61+
62+
// Cleanup
63+
await page.close();
64+
await browser.close();
65+
66+
console.log('Captcha solving started:', captchaSolvingStarted);
67+
console.log('Captcha solving finished:', captchaSolvingFinished);
68+
} catch (error) {
69+
console.error('An error occurred:', error);
70+
process.exit(1);
71+
} finally {
72+
console.log(`View replay at https://browserbase.com/sessions/${session.id}`);
73+
}
74+
}
75+
76+
// Run the script
77+
solveCaptcha();

examples/playwright-context.ts

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
import Browserbase from 'browserbase/index';
2+
import { chromium, type Browser, type Cookie } from 'playwright-core';
3+
4+
// Configuration
5+
const CONTEXT_TEST_URL = 'https://www.browserbase.com';
6+
const BROWSERBASE_PROJECT_ID = process.env['BROWSERBASE_PROJECT_ID']!;
7+
const BROWSERBASE_API_KEY = process.env['BROWSERBASE_API_KEY']!;
8+
9+
const bb = new Browserbase({
10+
apiKey: BROWSERBASE_API_KEY,
11+
});
12+
13+
// Helper functions
14+
function addHour(date: Date): number {
15+
const SECOND = 1000;
16+
return new Date(date.getTime() + 60 * 60 * 1000).getTime() / SECOND;
17+
}
18+
19+
async function findCookie(browser: Browser, name: string): Promise<Cookie | undefined> {
20+
const [defaultContext] = browser.contexts();
21+
const cookies = await defaultContext?.cookies();
22+
return cookies?.find((cookie) => cookie.name === name);
23+
}
24+
25+
async function runSessionWithContextPersistence() {
26+
let contextId: string;
27+
let sessionId: string;
28+
let testCookieName: string;
29+
let testCookieValue: string;
30+
31+
try {
32+
// Step 1: Create a context
33+
console.log('Creating a new context...');
34+
const context = await bb.contexts.create({
35+
projectId: BROWSERBASE_PROJECT_ID,
36+
});
37+
contextId = context.id;
38+
console.log(`Context created with ID: ${contextId}`);
39+
40+
// Step 2: Create a session with the context
41+
console.log('Creating a session with the context...');
42+
const session = await bb.sessions.create({
43+
projectId: BROWSERBASE_PROJECT_ID,
44+
browserSettings: {
45+
context: {
46+
id: contextId,
47+
persist: true,
48+
},
49+
},
50+
});
51+
sessionId = session.id;
52+
console.log(`Session created with ID: ${sessionId}`);
53+
54+
// Step 3: Populate and persist the context
55+
console.log(`Populating context ${contextId} during session ${sessionId}`);
56+
const browser = await chromium.connectOverCDP(session.connectUrl);
57+
const browserContext = browser.contexts()[0]!;
58+
const page = browserContext.pages()[0]!;
59+
60+
await page.goto(CONTEXT_TEST_URL, { waitUntil: 'domcontentloaded' });
61+
62+
// Set a random cookie on the page
63+
const now = new Date();
64+
testCookieName = `bb_${now.getTime().toString()}`;
65+
testCookieValue = now.toISOString();
66+
67+
await browserContext.addCookies([
68+
{
69+
domain: '.browserbase.com',
70+
expires: addHour(now),
71+
name: testCookieName,
72+
path: '/',
73+
value: testCookieValue,
74+
},
75+
]);
76+
77+
console.log(`Set test cookie: ${testCookieName}=${testCookieValue}`);
78+
79+
// Validate cookie persistence between pages
80+
await page.goto('https://www.google.com', { waitUntil: 'domcontentloaded' });
81+
await page.goBack();
82+
83+
const cookie = await findCookie(browser, testCookieName);
84+
console.log('Cookie persisted between pages:', !!cookie);
85+
86+
await page.close();
87+
await browser.close();
88+
89+
// Wait for context to persist
90+
console.log('Waiting for context to persist...');
91+
await new Promise((resolve) => setTimeout(resolve, 5000));
92+
93+
// Step 4: Create another session with the same context
94+
console.log('Creating a new session with the same context...');
95+
const newSession = await bb.sessions.create({
96+
projectId: BROWSERBASE_PROJECT_ID,
97+
browserSettings: {
98+
context: {
99+
id: contextId,
100+
},
101+
},
102+
});
103+
sessionId = newSession.id;
104+
105+
// Step 5: Verify previous state
106+
console.log(`Reusing context ${contextId} during session ${sessionId}`);
107+
const newBrowser = await chromium.connectOverCDP(newSession.connectUrl);
108+
const newPage = newBrowser.contexts()[0]!.pages()[0]!;
109+
110+
await newPage.goto(CONTEXT_TEST_URL, { waitUntil: 'domcontentloaded' });
111+
112+
const foundCookie = await findCookie(newBrowser, testCookieName);
113+
console.log('Cookie found in new session:', !!foundCookie);
114+
console.log('Cookie value matches:', foundCookie?.value === testCookieValue);
115+
116+
await newPage.close();
117+
await newBrowser.close();
118+
119+
console.log('Context persistence test completed successfully!');
120+
console.log(`View session replays at https://browserbase.com/sessions/${sessionId}`);
121+
} catch (error) {
122+
console.error('An error occurred:', error);
123+
process.exit(1);
124+
}
125+
}
126+
127+
// Run the script
128+
runSessionWithContextPersistence();

0 commit comments

Comments
 (0)