wuying-agentbay-sdk 0.10.2 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-E7QC5S76.mjs +3143 -0
- package/dist/chunk-E7QC5S76.mjs.map +1 -0
- package/dist/chunk-ZUB35HKV.cjs +3134 -0
- package/dist/chunk-ZUB35HKV.cjs.map +1 -0
- package/dist/index.cjs +3588 -3921
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +2088 -687
- package/dist/index.d.ts +2088 -687
- package/dist/index.mjs +3556 -3889
- package/dist/index.mjs.map +1 -1
- package/dist/key-normalizer-AF7APGQZ.cjs +136 -0
- package/dist/key-normalizer-AF7APGQZ.cjs.map +1 -0
- package/dist/key-normalizer-QDBRLFHF.mjs +145 -0
- package/dist/key-normalizer-QDBRLFHF.mjs.map +1 -0
- package/dist/model-2G37RFQQ.cjs +188 -0
- package/dist/model-2G37RFQQ.cjs.map +1 -0
- package/dist/model-ZFTLKEMC.mjs +197 -0
- package/docs/api/README.md +26 -0
- package/docs/api/browser-use/browser.md +177 -0
- package/docs/api/browser-use/extension.md +284 -0
- package/docs/api/codespace/code.md +77 -0
- package/docs/api/common-features/advanced/agent.md +84 -0
- package/docs/api/common-features/advanced/oss.md +221 -0
- package/docs/api/common-features/basics/agentbay.md +181 -0
- package/docs/api/common-features/basics/command.md +83 -0
- package/docs/api/common-features/basics/context-manager.md +130 -0
- package/docs/api/common-features/basics/context-sync.md +51 -0
- package/docs/api/common-features/basics/context.md +348 -0
- package/docs/api/common-features/basics/filesystem.md +499 -0
- package/docs/api/common-features/basics/logging.md +77 -0
- package/docs/api/common-features/basics/session.md +412 -0
- package/docs/api/computer-use/computer.md +786 -0
- package/docs/api/mobile-use/mobile.md +395 -0
- package/docs/examples/README.md +332 -0
- package/docs/examples/basic-usage.ts +86 -0
- package/docs/examples/browser-use/browser/README.md +356 -0
- package/docs/examples/browser-use/browser/basic-usage.ts +136 -0
- package/docs/examples/browser-use/browser/browser-command-args.ts +117 -0
- package/docs/examples/browser-use/browser/browser-context-cookie-persistence.ts +348 -0
- package/docs/examples/browser-use/browser/browser-fingerprint-basic-usage.ts +121 -0
- package/docs/examples/browser-use/browser/browser-fingerprint-construct.ts +114 -0
- package/docs/examples/browser-use/browser/browser-fingerprint-local-sync.ts +98 -0
- package/docs/examples/browser-use/browser/browser-fingerprint-persistence.ts +242 -0
- package/docs/examples/browser-use/browser/browser-proxies.ts +149 -0
- package/docs/examples/browser-use/browser/browser-type-example.ts +266 -0
- package/docs/examples/browser-use/browser/browser-viewport.ts +129 -0
- package/docs/examples/browser-use/browser/call_for_user_jd.ts +184 -0
- package/docs/examples/browser-use/browser/captcha_tongcheng.ts +151 -0
- package/docs/examples/browser-use/browser/run-2048.ts +209 -0
- package/docs/examples/browser-use/browser/run-sudoku.ts +150 -0
- package/docs/examples/browser-use/browser/screenshot-example.ts +132 -0
- package/docs/examples/browser-use/extension-example/README.md +252 -0
- package/docs/examples/browser-use/extension-example/extension-example.ts +380 -0
- package/docs/examples/codespace/automation/automation-example.ts +322 -0
- package/docs/examples/common-features/advanced/agent-module-example/README.md +40 -0
- package/docs/examples/common-features/advanced/agent-module-example.ts +66 -0
- package/docs/examples/common-features/advanced/archive-upload-mode-example/README.md +212 -0
- package/docs/examples/common-features/advanced/archive-upload-mode-example/archive-upload-mode-example.ts +213 -0
- package/docs/examples/common-features/advanced/vpc-session-example/README.md +47 -0
- package/docs/examples/common-features/advanced/vpc-session-example.ts +106 -0
- package/docs/examples/common-features/basics/archive-upload-mode-example/README.md +236 -0
- package/docs/examples/common-features/basics/archive-upload-mode-example/main.ts +236 -0
- package/docs/examples/common-features/basics/command-example/README.md +47 -0
- package/docs/examples/common-features/basics/command-example/command-example.ts +153 -0
- package/docs/examples/common-features/basics/context-management/README.md +55 -0
- package/docs/examples/common-features/basics/context-management/context-management.ts +140 -0
- package/docs/examples/common-features/basics/data-persistence/README.md +129 -0
- package/docs/examples/common-features/basics/data-persistence/context-sync-demo.md +144 -0
- package/docs/examples/common-features/basics/data-persistence/context-sync-demo.ts +275 -0
- package/docs/examples/common-features/basics/data-persistence/data-persistence.ts +259 -0
- package/docs/examples/common-features/basics/data-persistence/recycle-policy-example.ts +294 -0
- package/docs/examples/common-features/basics/filesystem-example/README.md +57 -0
- package/docs/examples/common-features/basics/filesystem-example/filesystem-example.ts +164 -0
- package/docs/examples/common-features/basics/filesystem-example/filesystem-filetransfer-example.ts +153 -0
- package/docs/examples/common-features/basics/filesystem-example/watch-directory-example.ts +168 -0
- package/docs/examples/common-features/basics/get/README.md +136 -0
- package/docs/examples/common-features/basics/get/main.ts +79 -0
- package/docs/examples/common-features/basics/list_sessions/README.md +54 -0
- package/docs/examples/common-features/basics/list_sessions/main.ts +258 -0
- package/docs/examples/common-features/basics/mcp_tool_direct_call/README.md +142 -0
- package/docs/examples/common-features/basics/mcp_tool_direct_call/main.ts +135 -0
- package/docs/examples/common-features/basics/session-creation/README.md +28 -0
- package/docs/examples/common-features/basics/session-creation/session-creation.ts +295 -0
- package/docs/examples/mobile-use/mobile-get-adb-url/README.md +92 -0
- package/docs/examples/mobile-use/mobile-get-adb-url/index.ts +80 -0
- package/docs/examples/mobile-use/mobile-get-adb-url/package-lock.json +279 -0
- package/docs/examples/mobile-use/mobile-get-adb-url/package.json +18 -0
- package/package.json +18 -11
- package/dist/application-KZWXH46T.mjs +0 -17
- package/dist/application-LMA7KSRH.cjs +0 -8
- package/dist/application-LMA7KSRH.cjs.map +0 -1
- package/dist/chunk-BQNGKBQF.mjs +0 -386
- package/dist/chunk-BQNGKBQF.mjs.map +0 -1
- package/dist/chunk-IOVGAAJL.cjs +0 -558
- package/dist/chunk-IOVGAAJL.cjs.map +0 -1
- package/dist/chunk-UF2TC2R4.mjs +0 -567
- package/dist/chunk-UF2TC2R4.mjs.map +0 -1
- package/dist/chunk-X6MS7Z5L.cjs +0 -377
- package/dist/chunk-X6MS7Z5L.cjs.map +0 -1
- package/dist/window-DH37ZDD5.mjs +0 -17
- package/dist/window-DH37ZDD5.mjs.map +0 -1
- package/dist/window-U7N3H735.cjs +0 -8
- package/dist/window-U7N3H735.cjs.map +0 -1
- /package/dist/{application-KZWXH46T.mjs.map → model-ZFTLKEMC.mjs.map} +0 -0
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser Context Cookie Persistence Example (TypeScript)
|
|
3
|
+
*
|
|
4
|
+
* This example demonstrates how to use Browser Context to persist cookies
|
|
5
|
+
* across multiple sessions in TypeScript. It shows the complete workflow of:
|
|
6
|
+
* 1. Creating a session with Browser Context
|
|
7
|
+
* 2. Setting cookies in the browser
|
|
8
|
+
* 3. Deleting the session with context synchronization
|
|
9
|
+
* 4. Creating a new session with the same Browser Context
|
|
10
|
+
* 5. Verifying that cookies persist across sessions
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { AgentBay, newCreateSessionParams, BrowserOptionClass, BrowserContext } from 'wuying-agentbay-sdk';
|
|
14
|
+
import { chromium } from 'playwright';
|
|
15
|
+
|
|
16
|
+
async function main(): Promise<void> {
|
|
17
|
+
// Get API key from environment
|
|
18
|
+
const apiKey = process.env.AGENTBAY_API_KEY;
|
|
19
|
+
if (!apiKey) {
|
|
20
|
+
console.error("Error: AGENTBAY_API_KEY environment variable not set");
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Initialize AgentBay client
|
|
25
|
+
const agentBay = new AgentBay({ apiKey });
|
|
26
|
+
console.log("AgentBay client initialized");
|
|
27
|
+
|
|
28
|
+
// Create a unique context name for this demo
|
|
29
|
+
const contextName = `browser-cookie-demo-${Date.now()}`;
|
|
30
|
+
|
|
31
|
+
try {
|
|
32
|
+
// Step 1: Create or get a persistent context for browser data
|
|
33
|
+
console.log(`Step 1: Creating context '${contextName}'...`);
|
|
34
|
+
const contextResult = await agentBay.context.get(contextName, true);
|
|
35
|
+
|
|
36
|
+
if (!contextResult.success || !contextResult.context) {
|
|
37
|
+
console.log(`Failed to create context: ${contextResult.errorMessage}`);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const context = contextResult.context;
|
|
42
|
+
console.log(`Context created with ID: ${context.id}`);
|
|
43
|
+
|
|
44
|
+
// Step 2: Create first session with Browser Context
|
|
45
|
+
console.log("Step 2: Creating first session with Browser Context...");
|
|
46
|
+
const browserContext = new BrowserContext(context.id, true);
|
|
47
|
+
|
|
48
|
+
const params = newCreateSessionParams()
|
|
49
|
+
.withImageId("browser_latest") // Browser image ID
|
|
50
|
+
.withBrowserContext(browserContext);
|
|
51
|
+
|
|
52
|
+
const sessionResult = await agentBay.create(params);
|
|
53
|
+
if (!sessionResult.success || !sessionResult.session) {
|
|
54
|
+
console.log(`Failed to create first session: ${sessionResult.errorMessage}`);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const session1 = sessionResult.session;
|
|
59
|
+
console.log(`First session created with ID: ${session1.sessionId}`);
|
|
60
|
+
|
|
61
|
+
// Step 3: Initialize browser and set cookies with enhanced error handling
|
|
62
|
+
console.log("Step 3: Initializing browser and setting test cookies...");
|
|
63
|
+
|
|
64
|
+
// Initialize browser with retry logic
|
|
65
|
+
console.log("Initializing browser...");
|
|
66
|
+
const browserOptions = new BrowserOptionClass();
|
|
67
|
+
const initSuccess = await session1.browser.initializeAsync(browserOptions);
|
|
68
|
+
|
|
69
|
+
if (!initSuccess) {
|
|
70
|
+
console.log("❌ Failed to initialize browser");
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
console.log("✅ Browser initialized successfully");
|
|
75
|
+
|
|
76
|
+
// Wait a moment for browser to be fully ready
|
|
77
|
+
await new Promise(resolve => setTimeout(resolve, 2000));
|
|
78
|
+
|
|
79
|
+
// Get endpoint URL with validation
|
|
80
|
+
const endpointUrl = await session1.browser.getEndpointUrl();
|
|
81
|
+
console.log(`Raw endpoint URL: ${JSON.stringify(endpointUrl)}`);
|
|
82
|
+
|
|
83
|
+
if (!endpointUrl) {
|
|
84
|
+
console.log("❌ Failed to get browser endpoint URL - browser may not be ready");
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (!endpointUrl.startsWith('ws://') && !endpointUrl.startsWith('wss://')) {
|
|
88
|
+
console.log(`❌ Invalid endpoint URL format: ${endpointUrl}`);
|
|
89
|
+
console.log("Expected WebSocket URL starting with ws:// or wss://");
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
console.log(`✅ Browser endpoint URL obtained: ${endpointUrl}`);
|
|
94
|
+
|
|
95
|
+
// Test data
|
|
96
|
+
const testUrl = "https://www.aliyun.com";
|
|
97
|
+
const testDomain = "aliyun.com";
|
|
98
|
+
|
|
99
|
+
// Define test cookies
|
|
100
|
+
const testCookies = [
|
|
101
|
+
{
|
|
102
|
+
name: "demo_cookie_1",
|
|
103
|
+
value: "demo_value_1",
|
|
104
|
+
domain: testDomain,
|
|
105
|
+
path: "/",
|
|
106
|
+
httpOnly: false,
|
|
107
|
+
secure: false,
|
|
108
|
+
expires: Math.floor(Date.now() / 1000) + 3600 // 1 hour from now
|
|
109
|
+
},
|
|
110
|
+
{
|
|
111
|
+
name: "demo_cookie_2",
|
|
112
|
+
value: "demo_value_2",
|
|
113
|
+
domain: testDomain,
|
|
114
|
+
path: "/",
|
|
115
|
+
httpOnly: false,
|
|
116
|
+
secure: false,
|
|
117
|
+
expires: Math.floor(Date.now() / 1000) + 3600 // 1 hour from now
|
|
118
|
+
}
|
|
119
|
+
];
|
|
120
|
+
|
|
121
|
+
// Connect with Playwright with enhanced error handling
|
|
122
|
+
let browser, cdpSession;
|
|
123
|
+
try {
|
|
124
|
+
console.log("Attempting to connect via CDP...");
|
|
125
|
+
browser = await chromium.connectOverCDP(endpointUrl);
|
|
126
|
+
console.log("✅ Successfully connected to browser via CDP");
|
|
127
|
+
} catch (error) {
|
|
128
|
+
console.log(`❌ Failed to connect via CDP: ${error}`);
|
|
129
|
+
console.log("This could be due to:");
|
|
130
|
+
console.log("1. Network connectivity issues");
|
|
131
|
+
console.log("2. Browser process not fully ready");
|
|
132
|
+
console.log("3. Firewall blocking WebSocket connections");
|
|
133
|
+
console.log("4. Invalid endpoint URL format");
|
|
134
|
+
|
|
135
|
+
// Try to get more information about the session
|
|
136
|
+
console.log("Session details for debugging:");
|
|
137
|
+
console.log(`Session ID: ${session1.sessionId}`);
|
|
138
|
+
console.log(`Endpoint URL: ${endpointUrl}`);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
try {
|
|
143
|
+
cdpSession = await browser.newBrowserCDPSession()
|
|
144
|
+
const contextP = browser.contexts()[0] || await browser.newContext();
|
|
145
|
+
const page = await contextP.newPage();
|
|
146
|
+
|
|
147
|
+
// Navigate to test URL first (required before setting cookies)
|
|
148
|
+
console.log(`Navigating to ${testUrl}...`);
|
|
149
|
+
await page.goto(testUrl);
|
|
150
|
+
console.log(`✅ Successfully navigated to ${testUrl}`);
|
|
151
|
+
await page.waitForTimeout(2000);
|
|
152
|
+
|
|
153
|
+
// Add test cookies
|
|
154
|
+
await contextP.addCookies(testCookies);
|
|
155
|
+
console.log(`✅ Added ${testCookies.length} test cookies`);
|
|
156
|
+
|
|
157
|
+
// Verify cookies were set
|
|
158
|
+
const cookies = await contextP.cookies();
|
|
159
|
+
const cookieDict: Record<string, string> = {};
|
|
160
|
+
cookies.forEach((cookie: any) => {
|
|
161
|
+
if (cookie.name) {
|
|
162
|
+
cookieDict[cookie.name] = cookie.value || '';
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
console.log(`Total cookies in first session: ${cookies.length}`);
|
|
166
|
+
|
|
167
|
+
// Check our test cookies
|
|
168
|
+
for (const testCookie of testCookies) {
|
|
169
|
+
const cookieName = testCookie.name;
|
|
170
|
+
if (cookieName in cookieDict) {
|
|
171
|
+
console.log(`✓ Test cookie '${cookieName}' set successfully: ${cookieDict[cookieName]}`);
|
|
172
|
+
} else {
|
|
173
|
+
console.log(`✗ Test cookie '${cookieName}' not found`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
await cdpSession.send('Browser.close')
|
|
177
|
+
console.log("First session browser operations completed")
|
|
178
|
+
|
|
179
|
+
// Wait for browser to save cookies to file
|
|
180
|
+
console.log("Waiting for browser to save cookies to file...")
|
|
181
|
+
await new Promise(resolve => setTimeout(resolve, 2000));
|
|
182
|
+
console.log("Wait completed")
|
|
183
|
+
|
|
184
|
+
await browser.close()
|
|
185
|
+
console.log("First session browser operations completed")
|
|
186
|
+
|
|
187
|
+
} finally {
|
|
188
|
+
if (browser) {
|
|
189
|
+
await browser.close();
|
|
190
|
+
console.log("✅ Browser connection closed");
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
console.log("First session browser operations completed");
|
|
195
|
+
|
|
196
|
+
// Step 4: Delete first session with context synchronization
|
|
197
|
+
console.log("Step 4: Deleting first session with context synchronization...");
|
|
198
|
+
const deleteResult = await agentBay.delete(session1, true); // syncContext = true
|
|
199
|
+
|
|
200
|
+
if (!deleteResult.success) {
|
|
201
|
+
console.log(`Failed to delete first session: ${deleteResult.errorMessage}`);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
console.log(`First session deleted successfully (RequestID: ${deleteResult.requestId})`);
|
|
206
|
+
|
|
207
|
+
// Wait for context sync to complete
|
|
208
|
+
console.log("Waiting for context synchronization to complete...");
|
|
209
|
+
await new Promise(resolve => setTimeout(resolve, 3000));
|
|
210
|
+
|
|
211
|
+
// Step 5: Create second session with same Browser Context
|
|
212
|
+
console.log("Step 5: Creating second session with same Browser Context...");
|
|
213
|
+
const sessionResult2 = await agentBay.create(params);
|
|
214
|
+
|
|
215
|
+
if (!sessionResult2.success || !sessionResult2.session) {
|
|
216
|
+
console.log(`Failed to create second session: ${sessionResult2.errorMessage}`);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const session2 = sessionResult2.session;
|
|
221
|
+
console.log(`Second session created with ID: ${session2.sessionId}`);
|
|
222
|
+
|
|
223
|
+
// Step 6: Verify cookie persistence
|
|
224
|
+
console.log("Step 6: Verifying cookie persistence in second session...");
|
|
225
|
+
|
|
226
|
+
// Initialize browser in second session
|
|
227
|
+
const initSuccess2 = await session2.browser.initializeAsync(new BrowserOptionClass());
|
|
228
|
+
if (!initSuccess2) {
|
|
229
|
+
console.log("Failed to initialize browser in second session");
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
console.log("Second session browser initialized successfully");
|
|
234
|
+
|
|
235
|
+
// Wait for browser to be ready
|
|
236
|
+
await new Promise(resolve => setTimeout(resolve, 2000));
|
|
237
|
+
|
|
238
|
+
// Get endpoint URL for second session
|
|
239
|
+
const endpointUrl2 = await session2.browser.getEndpointUrl();
|
|
240
|
+
if (!endpointUrl2) {
|
|
241
|
+
console.log("Failed to get browser endpoint URL for second session");
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
console.log(`Second session browser endpoint URL: ${endpointUrl2}`);
|
|
246
|
+
|
|
247
|
+
// Check cookies in second session with error handling
|
|
248
|
+
let browser2;
|
|
249
|
+
try {
|
|
250
|
+
browser2 = await chromium.connectOverCDP(endpointUrl2);
|
|
251
|
+
|
|
252
|
+
let context2;
|
|
253
|
+
if (browser2.contexts().length > 0) {
|
|
254
|
+
context2 = await browser2.contexts()[0];
|
|
255
|
+
} else {
|
|
256
|
+
context2 = await browser2.newContext();
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Read cookies directly from context (without opening any page)
|
|
260
|
+
const cookies2 = await context2.cookies();
|
|
261
|
+
const cookieDict2: Record<string, string> = {};
|
|
262
|
+
cookies2.forEach((cookie: any) => {
|
|
263
|
+
console.log(`Cookie name: ${cookie.name}, value: ${cookie.value}`);
|
|
264
|
+
if (cookie.name) {
|
|
265
|
+
cookieDict2[cookie.name] = cookie.value || '';
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
console.log(`Total cookies in second session: ${cookies2.length}`);
|
|
270
|
+
|
|
271
|
+
// Check if our test cookies persisted
|
|
272
|
+
const expectedCookieNames = new Set(["demo_cookie_1", "demo_cookie_2"]);
|
|
273
|
+
const foundCookieNames = new Set(Object.keys(cookieDict2));
|
|
274
|
+
console.log("Found cookie names:", foundCookieNames);
|
|
275
|
+
console.log("Checking cookie persistence...");
|
|
276
|
+
const missingCookies = [...expectedCookieNames].filter(name => !foundCookieNames.has(name));
|
|
277
|
+
|
|
278
|
+
if (missingCookies.length > 0) {
|
|
279
|
+
console.log(`✗ Missing test cookies: ${missingCookies.join(', ')}`);
|
|
280
|
+
console.log("Cookie persistence test FAILED");
|
|
281
|
+
} else {
|
|
282
|
+
// Verify cookie values
|
|
283
|
+
let allValuesMatch = true;
|
|
284
|
+
for (const testCookie of testCookies) {
|
|
285
|
+
const cookieName = testCookie.name;
|
|
286
|
+
const expectedValue = testCookie.value;
|
|
287
|
+
const actualValue = cookieDict2[cookieName] || "";
|
|
288
|
+
|
|
289
|
+
if (expectedValue === actualValue) {
|
|
290
|
+
console.log(`✓ Cookie '${cookieName}' persisted correctly: ${actualValue}`);
|
|
291
|
+
} else {
|
|
292
|
+
console.log(`✗ Cookie '${cookieName}' value mismatch. Expected: ${expectedValue}, Actual: ${actualValue}`);
|
|
293
|
+
allValuesMatch = false;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (allValuesMatch) {
|
|
298
|
+
console.log("🎉 Cookie persistence test PASSED! All cookies persisted correctly across sessions.");
|
|
299
|
+
} else {
|
|
300
|
+
console.log("Cookie persistence test FAILED due to value mismatches");
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
} catch (error) {
|
|
305
|
+
console.log(`❌ Failed to connect to second session browser: ${error}`);
|
|
306
|
+
} finally {
|
|
307
|
+
if (browser2) {
|
|
308
|
+
await browser2.close();
|
|
309
|
+
console.log("Second session browser operations completed");
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// Step 7: Clean up second session
|
|
314
|
+
console.log("Step 7: Cleaning up second session...");
|
|
315
|
+
const deleteResult2 = await agentBay.delete(session2);
|
|
316
|
+
|
|
317
|
+
if (deleteResult2.success) {
|
|
318
|
+
console.log(`Second session deleted successfully (RequestID: ${deleteResult2.requestId})`);
|
|
319
|
+
} else {
|
|
320
|
+
console.log(`Failed to delete second session: ${deleteResult2.errorMessage}`);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
} catch (error) {
|
|
324
|
+
console.log(`❌ Error during demo: ${error}`);
|
|
325
|
+
console.log("\nDebugging information:");
|
|
326
|
+
console.log(`Error type: ${typeof error}`);
|
|
327
|
+
console.log(`Error message: ${error instanceof Error ? error.message : String(error)}`);
|
|
328
|
+
if (error instanceof Error && error.stack) {
|
|
329
|
+
console.log(`Error stack: ${error.stack}`);
|
|
330
|
+
}
|
|
331
|
+
} finally {
|
|
332
|
+
// Clean up context
|
|
333
|
+
try {
|
|
334
|
+
const contextResult = await agentBay.context.get(contextName, false);
|
|
335
|
+
if (contextResult.success && contextResult.context) {
|
|
336
|
+
await agentBay.context.delete(contextResult.context);
|
|
337
|
+
console.log(`Context '${contextName}' deleted`);
|
|
338
|
+
}
|
|
339
|
+
} catch (error) {
|
|
340
|
+
console.log(`Warning: Failed to delete context: ${error}`);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
console.log("\nBrowser Context Cookie Persistence Demo completed!");
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// Run the example
|
|
348
|
+
main().catch(console.error);
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Example demonstrating Browser Fingerprint basic usage with AgentBay SDK.
|
|
3
|
+
*
|
|
4
|
+
* This example shows how to use browser with random fingerprint to avoid detection
|
|
5
|
+
* by anti-bot services. It will generate a random, realistic browser fingerprint
|
|
6
|
+
* and make the browser behave more like a real user.
|
|
7
|
+
*
|
|
8
|
+
* This example will:
|
|
9
|
+
* 1. Create AIBrowser session with random fingerprint and simulate a Windows desktop browser.
|
|
10
|
+
* 2. Use playwright to connect to AIBrowser instance through CDP protocol
|
|
11
|
+
* 3. Verify user agent and navigator properties
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
// @ts-nocheck
|
|
15
|
+
import { AgentBay, CreateSessionParams } from 'wuying-agentbay-sdk';
|
|
16
|
+
import { BrowserOption, BrowserFingerprint } from 'wuying-agentbay-sdk';
|
|
17
|
+
import { chromium } from 'playwright';
|
|
18
|
+
|
|
19
|
+
async function main(): Promise<void> {
|
|
20
|
+
// Get API key from environment variable
|
|
21
|
+
const apiKey = process.env.AGENTBAY_API_KEY;
|
|
22
|
+
if (!apiKey) {
|
|
23
|
+
console.log("Error: AGENTBAY_API_KEY environment variable not set");
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
try {
|
|
28
|
+
// Initialize AgentBay client
|
|
29
|
+
console.log("Initializing AgentBay client...");
|
|
30
|
+
const agentBay = new AgentBay({ apiKey });
|
|
31
|
+
|
|
32
|
+
// Create a session
|
|
33
|
+
console.log("Creating a new session...");
|
|
34
|
+
const params: CreateSessionParams = {
|
|
35
|
+
imageId: "browser_latest",
|
|
36
|
+
};
|
|
37
|
+
const sessionResult = await agentBay.create(params);
|
|
38
|
+
|
|
39
|
+
if (!sessionResult.success) {
|
|
40
|
+
console.log("Failed to create session");
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const session = sessionResult.session;
|
|
45
|
+
console.log(`Session created with ID: ${session.sessionId}`);
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Create browser fingerprint option
|
|
49
|
+
* - devices: desktop or mobile
|
|
50
|
+
* - operatingSystems: windows, macos, linux, android, ios
|
|
51
|
+
*
|
|
52
|
+
* You can specify one or multiple values for each parameter.
|
|
53
|
+
* But if you specify devices as desktop and operatingSystems as android/ios,
|
|
54
|
+
* the fingerprint feature will not work.
|
|
55
|
+
*/
|
|
56
|
+
const browserFingerprint: BrowserFingerprint = {
|
|
57
|
+
devices: ["desktop"],
|
|
58
|
+
operatingSystems: ["windows"],
|
|
59
|
+
locales: ["zh-CN", "zh"]
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// Create browser option with stealth mode and fingerprint option limit.
|
|
63
|
+
// Stealth mode helps to avoid detection by anti-bot services. It will
|
|
64
|
+
// generate a random, realistic browser fingerprint and make the browser
|
|
65
|
+
// behave more like a real user.
|
|
66
|
+
const browserOption: BrowserOption = {
|
|
67
|
+
useStealth: true,
|
|
68
|
+
fingerprint: browserFingerprint
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const initialized = await session.browser.initializeAsync(browserOption);
|
|
72
|
+
if (!initialized) {
|
|
73
|
+
console.log("Failed to initialize browser");
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const endpointUrl = await session.browser.getEndpointUrl();
|
|
78
|
+
console.log("endpoint_url =", endpointUrl);
|
|
79
|
+
|
|
80
|
+
// Connect to browser using Playwright
|
|
81
|
+
const browser = await chromium.connectOverCDP(endpointUrl);
|
|
82
|
+
const context = browser.contexts()[0];
|
|
83
|
+
const page = await context.newPage();
|
|
84
|
+
|
|
85
|
+
// Check user agent
|
|
86
|
+
console.log("\n--- Check User Agent ---");
|
|
87
|
+
await page.goto("https://httpbin.org/user-agent");
|
|
88
|
+
|
|
89
|
+
const response = await page.evaluate(() => JSON.parse(document.body.textContent));
|
|
90
|
+
const userAgent = response["user-agent"] || "";
|
|
91
|
+
console.log(`User Agent: ${userAgent}`);
|
|
92
|
+
|
|
93
|
+
// Check navigator properties
|
|
94
|
+
console.log("\n--- Check Navigator Properties ---");
|
|
95
|
+
const navInfo = await page.evaluate(() => ({
|
|
96
|
+
platform: navigator.platform,
|
|
97
|
+
language: navigator.language,
|
|
98
|
+
languages: navigator.languages,
|
|
99
|
+
webdriver: navigator.webdriver
|
|
100
|
+
}));
|
|
101
|
+
|
|
102
|
+
console.log(`Platform: ${navInfo.platform}`);
|
|
103
|
+
console.log(`Language: ${navInfo.language}`);
|
|
104
|
+
console.log(`Languages: ${navInfo.languages}`);
|
|
105
|
+
console.log(`WebDriver: ${navInfo.webdriver}`);
|
|
106
|
+
|
|
107
|
+
await page.waitForTimeout(3000);
|
|
108
|
+
await browser.close();
|
|
109
|
+
|
|
110
|
+
// Clean up session
|
|
111
|
+
await agentBay.delete(session);
|
|
112
|
+
console.log("Session cleaned up successfully");
|
|
113
|
+
|
|
114
|
+
} catch (error) {
|
|
115
|
+
console.error("Error in main function:", error);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (require.main === module) {
|
|
120
|
+
main().catch(console.error);
|
|
121
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Example demonstrating Browser Fingerprint construct feature with AgentBay SDK.
|
|
3
|
+
*
|
|
4
|
+
* This example shows how to construct browser fingerprint from file and sync it to remote browser.
|
|
5
|
+
* FingerprintFormat can be loaded from file and then used to sync to remote browser fingerprint
|
|
6
|
+
* by using BrowserOption.fingerprintFormat.
|
|
7
|
+
*
|
|
8
|
+
* This example will:
|
|
9
|
+
* 1. Load fingerprint format from file
|
|
10
|
+
* 2. Sync fingerprint format to remote browser fingerprint
|
|
11
|
+
* 3. Verify remote browser fingerprint
|
|
12
|
+
* 4. Clean up session
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
// @ts-nocheck
|
|
16
|
+
import { AgentBay, CreateSessionParams } from 'wuying-agentbay-sdk';
|
|
17
|
+
import { BrowserOption, FingerprintFormat } from 'wuying-agentbay-sdk';
|
|
18
|
+
import { chromium } from 'playwright';
|
|
19
|
+
import * as fs from 'fs';
|
|
20
|
+
import * as path from 'path';
|
|
21
|
+
|
|
22
|
+
async function generateFingerprintByFile(): Promise<FingerprintFormat> {
|
|
23
|
+
/**
|
|
24
|
+
* Generate fingerprint by file.
|
|
25
|
+
*/
|
|
26
|
+
const fingerprintPath = path.join(__dirname, "../../../../../resource/fingerprint.example.json");
|
|
27
|
+
const fingerprintData = fs.readFileSync(fingerprintPath, 'utf8');
|
|
28
|
+
return FingerprintFormat.load(fingerprintData);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function main(): Promise<void> {
|
|
32
|
+
const apiKey = process.env.AGENTBAY_API_KEY;
|
|
33
|
+
if (!apiKey) {
|
|
34
|
+
console.log("Error: AGENTBAY_API_KEY environment variable not set");
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
// Initialize AgentBay client
|
|
40
|
+
console.log("Initializing AgentBay client...");
|
|
41
|
+
const agentBay = new AgentBay({ apiKey });
|
|
42
|
+
|
|
43
|
+
// Create a session
|
|
44
|
+
console.log("Creating a new session...");
|
|
45
|
+
const params: CreateSessionParams = {
|
|
46
|
+
imageId: "browser_latest",
|
|
47
|
+
};
|
|
48
|
+
const sessionResult = await agentBay.create(params);
|
|
49
|
+
|
|
50
|
+
if (!sessionResult.success) {
|
|
51
|
+
console.log("Failed to create session");
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const session = sessionResult.session;
|
|
56
|
+
console.log(`Session created with ID: ${session.sessionId}`);
|
|
57
|
+
|
|
58
|
+
// You can generate fingerprint by file or construct FingerprintFormat by yourself totally.
|
|
59
|
+
const fingerprintFormat = await generateFingerprintByFile();
|
|
60
|
+
|
|
61
|
+
// Create browser option with fingerprint format.
|
|
62
|
+
// Fingerprint format is loaded from file by generateFingerprintByFile()
|
|
63
|
+
// automatically, you can use it to sync to remote browser fingerprint.
|
|
64
|
+
const browserOption: BrowserOption = {
|
|
65
|
+
useStealth: true,
|
|
66
|
+
fingerprintFormat: fingerprintFormat
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const initialized = await session.browser.initializeAsync(browserOption);
|
|
70
|
+
if (!initialized) {
|
|
71
|
+
console.log("Failed to initialize browser");
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const endpointUrl = await session.browser.getEndpointUrl();
|
|
76
|
+
console.log("endpoint_url =", endpointUrl);
|
|
77
|
+
|
|
78
|
+
// Connect to browser using Playwright
|
|
79
|
+
const browser = await chromium.connectOverCDP(endpointUrl);
|
|
80
|
+
const context = browser.contexts()[0];
|
|
81
|
+
const page = await context.newPage();
|
|
82
|
+
|
|
83
|
+
// Check user agent
|
|
84
|
+
console.log("\n--- Check User Agent ---");
|
|
85
|
+
await page.goto("https://httpbin.org/user-agent");
|
|
86
|
+
|
|
87
|
+
const response = await page.evaluate(() => JSON.parse(document.body.textContent));
|
|
88
|
+
const userAgent = response["user-agent"] || "";
|
|
89
|
+
console.log(`User Agent: ${userAgent}`);
|
|
90
|
+
|
|
91
|
+
// Verify that the user agent matches the fingerprint format
|
|
92
|
+
if (fingerprintFormat.fingerprint?.navigator?.userAgent) {
|
|
93
|
+
if (userAgent === fingerprintFormat.fingerprint.navigator.userAgent) {
|
|
94
|
+
console.log("User Agent constructed correctly");
|
|
95
|
+
} else {
|
|
96
|
+
console.log("User Agent mismatch");
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
await page.waitForTimeout(3000);
|
|
101
|
+
await browser.close();
|
|
102
|
+
|
|
103
|
+
// Clean up session
|
|
104
|
+
await agentBay.delete(session);
|
|
105
|
+
console.log("Session cleaned up successfully");
|
|
106
|
+
|
|
107
|
+
} catch (error) {
|
|
108
|
+
console.error("Error in main function:", error);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (require.main === module) {
|
|
113
|
+
main().catch(console.error);
|
|
114
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Example demonstrating Browser Fingerprint local sync feature with AgentBay SDK.
|
|
3
|
+
*
|
|
4
|
+
* This example shows how to sync local browser fingerprint to remote browser fingerprint.
|
|
5
|
+
* BrowserFingerprintGenerator has ability to dump local installed chrome browser fingerprint,
|
|
6
|
+
* and then you can sync it to remote browser fingerprint by using BrowserOption.fingerprintFormat.
|
|
7
|
+
*
|
|
8
|
+
* This example will:
|
|
9
|
+
* 1. Generate local chrome browser fingerprint by BrowserFingerprintGenerator
|
|
10
|
+
* 2. Sync local browser fingerprint to remote browser fingerprint
|
|
11
|
+
* 3. Verify remote browser fingerprint
|
|
12
|
+
* 4. Clean up session
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
// @ts-nocheck
|
|
16
|
+
import { AgentBay, CreateSessionParams } from 'wuying-agentbay-sdk';
|
|
17
|
+
import { BrowserOption, BrowserFingerprintGenerator } from 'wuying-agentbay-sdk';
|
|
18
|
+
import { chromium } from 'playwright';
|
|
19
|
+
|
|
20
|
+
async function main(): Promise<void> {
|
|
21
|
+
const apiKey = process.env.AGENTBAY_API_KEY;
|
|
22
|
+
if (!apiKey) {
|
|
23
|
+
console.log("Error: AGENTBAY_API_KEY environment variable not set");
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
try {
|
|
28
|
+
// Initialize AgentBay client
|
|
29
|
+
console.log("Initializing AgentBay client...");
|
|
30
|
+
const agentBay = new AgentBay({ apiKey });
|
|
31
|
+
|
|
32
|
+
// Create a session
|
|
33
|
+
console.log("Creating a new session...");
|
|
34
|
+
const params: CreateSessionParams = {
|
|
35
|
+
imageId: "browser_latest",
|
|
36
|
+
};
|
|
37
|
+
const sessionResult = await agentBay.create(params);
|
|
38
|
+
|
|
39
|
+
if (!sessionResult.success) {
|
|
40
|
+
console.log("Failed to create session");
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const session = sessionResult.session;
|
|
45
|
+
console.log(`Session created with ID: ${session.sessionId}`);
|
|
46
|
+
|
|
47
|
+
// Generate fingerprint from local chrome browser
|
|
48
|
+
const fingerprintGenerator = new BrowserFingerprintGenerator();
|
|
49
|
+
const fingerprintFormat = await fingerprintGenerator.generateFingerprint();
|
|
50
|
+
console.log(`Fingerprint format: ${JSON.stringify(fingerprintFormat)}`);
|
|
51
|
+
|
|
52
|
+
// Create browser option with fingerprint format.
|
|
53
|
+
// Fingerprint format is dumped from local chrome browser by BrowserFingerprintGenerator
|
|
54
|
+
// automatically, you can use it to sync to remote browser fingerprint.
|
|
55
|
+
const browserOption: BrowserOption = {
|
|
56
|
+
useStealth: true,
|
|
57
|
+
fingerprintFormat: fingerprintFormat
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const initialized = await session.browser.initializeAsync(browserOption);
|
|
61
|
+
if (!initialized) {
|
|
62
|
+
console.log("Failed to initialize browser");
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const endpointUrl = await session.browser.getEndpointUrl();
|
|
67
|
+
console.log("endpoint_url =", endpointUrl);
|
|
68
|
+
|
|
69
|
+
// Connect to browser using Playwright
|
|
70
|
+
const browser = await chromium.connectOverCDP(endpointUrl);
|
|
71
|
+
const context = browser.contexts()[0];
|
|
72
|
+
const page = await context.newPage();
|
|
73
|
+
|
|
74
|
+
// Check user agent
|
|
75
|
+
console.log("\n--- Check User Agent ---");
|
|
76
|
+
await page.goto("https://httpbin.org/user-agent");
|
|
77
|
+
|
|
78
|
+
const response = await page.evaluate(() => JSON.parse(document.body.textContent));
|
|
79
|
+
const userAgent = response["user-agent"] || "";
|
|
80
|
+
console.log(`User Agent: ${userAgent}`);
|
|
81
|
+
|
|
82
|
+
console.log("Please check if User Agent is synced correctly by visiting https://httpbin.org/user-agent in local chrome browser.");
|
|
83
|
+
|
|
84
|
+
await page.waitForTimeout(3000);
|
|
85
|
+
await browser.close();
|
|
86
|
+
|
|
87
|
+
// Clean up session
|
|
88
|
+
await agentBay.delete(session);
|
|
89
|
+
console.log("Session cleaned up successfully");
|
|
90
|
+
|
|
91
|
+
} catch (error) {
|
|
92
|
+
console.error("Error in main function:", error);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (require.main === module) {
|
|
97
|
+
main().catch(console.error);
|
|
98
|
+
}
|