Skip to content

Add examples from core #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 16 commits into from
Oct 28, 2024
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
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
BROWSERBASE_API_KEY="your-api-key-here"
BROWSERBASE_PROJECT_ID="your-project-id-here"
3 changes: 0 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ jobs:
lint:
name: lint
runs-on: ubuntu-latest


steps:
- uses: actions/checkout@v4
Expand All @@ -31,7 +30,6 @@ jobs:
build:
name: build
runs-on: ubuntu-latest


steps:
- uses: actions/checkout@v4
Expand Down Expand Up @@ -63,4 +61,3 @@ jobs:

- name: Run tests
run: ./scripts/test

1 change: 0 additions & 1 deletion .github/workflows/release-doctor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,3 @@ jobs:
bash ./bin/check-release-environment
env:
NPM_TOKEN: ${{ secrets.BROWSERBASE_NPM_TOKEN || secrets.NPM_TOKEN }}

1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ dist
/*.tgz
.idea/

.env
Binary file added examples/packages/extensions/.DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions examples/packages/extensions/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.zip
5 changes: 5 additions & 0 deletions examples/packages/extensions/browserbase-test/hello.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<html>
<body>
<h1>Hello Extensions</h1>
</body>
</html>
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
21 changes: 21 additions & 0 deletions examples/packages/extensions/browserbase-test/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"manifest_version": 3,
"name": "Browserbase Extension Test",
"description": "Test extension for browserbase",
"version": "1.0",
"action": {
"default_popup": "hello.html"
},
"content_scripts": [
{
"matches": ["https://www.browserbase.com/*"],
"js": ["scripts/content.js"]
}
],
"web_accessible_resources": [
{
"resources": ["images/logo.png"],
"matches": ["https://www.browserbase.com/*"]
}
]
}
12 changes: 12 additions & 0 deletions examples/packages/extensions/browserbase-test/scripts/content.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/* eslint-disable prettier/prettier */
const imageUrl = chrome.runtime.getURL('images/logo.png');
window
.fetch(imageUrl)
.then((response) => {
if (response.ok) {
console.log('browserbase test extension image loaded');
}
})
.catch((error) => {
console.log(error);
});
Binary file added examples/packages/logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
28 changes: 28 additions & 0 deletions examples/playwright-basic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { chromium } from 'playwright-core';
import Browserbase from 'browserbase/index';

const BROWSERBASE_API_KEY = process.env['BROWSERBASE_API_KEY']!;
const BROWSERBASE_PROJECT_ID = process.env['BROWSERBASE_PROJECT_ID']!;

const bb = new Browserbase({
apiKey: BROWSERBASE_API_KEY,
});

(async () => {
// Create a new session
const session = await bb.sessions.create({
projectId: BROWSERBASE_PROJECT_ID,
});

// Connect to the session
const browser = await chromium.connectOverCDP(session.connectUrl);

// Getting the default context to ensure the sessions are recorded.
const defaultContext = browser.contexts()[0];
const page = defaultContext?.pages()[0];

await page?.goto('https://browserbase.com/');
await page?.close();
await browser.close();
console.log(`Session complete! View replay at https://browserbase.com/sessions/${session.id}`);
})().catch((error) => console.error(error.message));
77 changes: 77 additions & 0 deletions examples/playwright-captcha.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import Browserbase from 'browserbase/index';
import { chromium } from 'playwright-core';

// Configuration
const DEFAULT_CAPTCHA_URL = 'https://2captcha.com/demo/recaptcha-v2';
const OVERRIDE_TIMEOUT = 60_000; // 1 minute in milliseconds
const BROWSERBASE_PROJECT_ID = process.env['BROWSERBASE_PROJECT_ID']!;
const BROWSERBASE_API_KEY = process.env['BROWSERBASE_API_KEY']!;

const bb = new Browserbase({
apiKey: BROWSERBASE_API_KEY,
});

async function solveCaptcha() {
// Create a session with captcha solving enabled
const session = await bb.sessions.create({
projectId: BROWSERBASE_PROJECT_ID,
browserSettings: {
solveCaptchas: true,
},
proxies: true,
});
try {
// Connect to the browser
const browser = await chromium.connectOverCDP(session.connectUrl);

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

let captchaSolvingStarted = false;
let captchaSolvingFinished = false;

// Listen for console messages
page.on('console', (msg) => {
if (msg.text() === 'browserbase-solving-started') {
captchaSolvingStarted = true;
console.log('Captcha solving started...');
page.evaluate(() => {
// @ts-ignore
window.captchaSolvingFinished = false;
});
} else if (msg.text() === 'browserbase-solving-finished') {
captchaSolvingFinished = true;
console.log('Captcha solving finished!');
page.evaluate(() => {
// @ts-ignore
window.captchaSolvingFinished = true;
});
}
});

// Navigate to the captcha page
console.log('Navigating to captcha page...');
await page.goto(DEFAULT_CAPTCHA_URL, { waitUntil: 'networkidle' });

// Wait for captcha to be solved
// @ts-ignore
await page.waitForFunction(() => window.captchaSolvingFinished === true, null, {
timeout: OVERRIDE_TIMEOUT,
});

// Cleanup
await page.close();
await browser.close();

console.log('Captcha solving started:', captchaSolvingStarted);
console.log('Captcha solving finished:', captchaSolvingFinished);
} catch (error) {
console.error('An error occurred:', error);
process.exit(1);
} finally {
console.log(`View replay at https://browserbase.com/sessions/${session.id}`);
}
}

// Run the script
solveCaptcha();
128 changes: 128 additions & 0 deletions examples/playwright-context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import Browserbase from 'browserbase/index';
import { chromium, type Browser, type Cookie } from 'playwright-core';

// Configuration
const CONTEXT_TEST_URL = 'https://www.browserbase.com';
const BROWSERBASE_PROJECT_ID = process.env['BROWSERBASE_PROJECT_ID']!;
const BROWSERBASE_API_KEY = process.env['BROWSERBASE_API_KEY']!;

const bb = new Browserbase({
apiKey: BROWSERBASE_API_KEY,
});

// Helper functions
function addHour(date: Date): number {
const SECOND = 1000;
return new Date(date.getTime() + 60 * 60 * 1000).getTime() / SECOND;
}

async function findCookie(browser: Browser, name: string): Promise<Cookie | undefined> {
const [defaultContext] = browser.contexts();
const cookies = await defaultContext?.cookies();
return cookies?.find((cookie) => cookie.name === name);
}

async function runSessionWithContextPersistence() {
let contextId: string;
let sessionId: string;
let testCookieName: string;
let testCookieValue: string;

try {
// Step 1: Create a context
console.log('Creating a new context...');
const context = await bb.contexts.create({
projectId: BROWSERBASE_PROJECT_ID,
});
contextId = context.id;
console.log(`Context created with ID: ${contextId}`);

// Step 2: Create a session with the context
console.log('Creating a session with the context...');
const session = await bb.sessions.create({
projectId: BROWSERBASE_PROJECT_ID,
browserSettings: {
context: {
id: contextId,
persist: true,
},
},
});
sessionId = session.id;
console.log(`Session created with ID: ${sessionId}`);

// Step 3: Populate and persist the context
console.log(`Populating context ${contextId} during session ${sessionId}`);
const browser = await chromium.connectOverCDP(session.connectUrl);
const browserContext = browser.contexts()[0]!;
const page = browserContext.pages()[0]!;

await page.goto(CONTEXT_TEST_URL, { waitUntil: 'domcontentloaded' });

// Set a random cookie on the page
const now = new Date();
testCookieName = `bb_${now.getTime().toString()}`;
testCookieValue = now.toISOString();

await browserContext.addCookies([
{
domain: '.browserbase.com',
expires: addHour(now),
name: testCookieName,
path: '/',
value: testCookieValue,
},
]);

console.log(`Set test cookie: ${testCookieName}=${testCookieValue}`);

// Validate cookie persistence between pages
await page.goto('https://www.google.com', { waitUntil: 'domcontentloaded' });
await page.goBack();

const cookie = await findCookie(browser, testCookieName);
console.log('Cookie persisted between pages:', !!cookie);

await page.close();
await browser.close();

// Wait for context to persist
console.log('Waiting for context to persist...');
await new Promise((resolve) => setTimeout(resolve, 5000));

// Step 4: Create another session with the same context
console.log('Creating a new session with the same context...');
const newSession = await bb.sessions.create({
projectId: BROWSERBASE_PROJECT_ID,
browserSettings: {
context: {
id: contextId,
},
},
});
sessionId = newSession.id;

// Step 5: Verify previous state
console.log(`Reusing context ${contextId} during session ${sessionId}`);
const newBrowser = await chromium.connectOverCDP(newSession.connectUrl);
const newPage = newBrowser.contexts()[0]!.pages()[0]!;

await newPage.goto(CONTEXT_TEST_URL, { waitUntil: 'domcontentloaded' });

const foundCookie = await findCookie(newBrowser, testCookieName);
console.log('Cookie found in new session:', !!foundCookie);
console.log('Cookie value matches:', foundCookie?.value === testCookieValue);

await newPage.close();
await newBrowser.close();

console.log('Context persistence test completed successfully!');
console.log(`View session replays at https://browserbase.com/sessions/${sessionId}`);
} catch (error) {
console.error('An error occurred:', error);
process.exit(1);
}
}

// Run the script
runSessionWithContextPersistence();
Loading