-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdriver.js
More file actions
933 lines (800 loc) · 26.7 KB
/
driver.js
File metadata and controls
933 lines (800 loc) · 26.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
/**
* Custom Browser Driver for OpenClaw
* Implements the BrowserDriver interface for custom browser automation
*/
const CDP = require('chrome-remote-interface');
const { spawn } = require('child_process');
const { promisify } = require('util');
const { chromium } = require('playwright-core');
const sleep = promisify(setTimeout);
class CustomBrowserDriver {
constructor() {
this.proc = null;
this.client = null;
this.profile = null;
this.tabs = new Map(); // targetId -> tab info
this.playwrightBrowser = null;
this.playwrightPages = new Map(); // targetId -> Playwright Page
this.consoleLogs = new Map(); // targetId -> array of console messages
this.networkLogs = new Map(); // targetId -> array of network requests
this.downloadPath = '/tmp/openclaw/downloads';
}
/**
* Start the browser with given profile configuration
* @param {Object} profile - Profile configuration
* @returns {Promise<void>}
*/
async start(profile) {
console.log('[CustomDriver] Starting browser with profile:', profile.name);
this.profile = profile;
// Default browser path - override in profile config
const browserPath = profile.executablePath || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
const cdpPort = profile.cdpPort || 19000;
const userDataDir = profile.userDataDir || `${process.env.HOME}/.openclaw/browser/${profile.name}`;
// Browser launch flags
const browserArgs = [
`--remote-debugging-port=${cdpPort}`,
`--user-data-dir=${userDataDir}`,
'--no-first-run',
'--no-default-browser-check',
// Custom flags
...(profile.customFlags || [])
];
console.log('[CustomDriver] Launching:', browserPath);
console.log('[CustomDriver] Args:', browserArgs);
// Spawn browser process
this.proc = spawn(browserPath, browserArgs, {
detached: false,
stdio: 'ignore'
});
this.proc.on('error', (err) => {
console.error('[CustomDriver] Browser process error:', err);
});
this.proc.on('exit', (code) => {
console.log(`[CustomDriver] Browser process exited with code ${code}`);
});
// Wait for CDP to be ready
console.log('[CustomDriver] Waiting for CDP...');
await sleep(3000);
// Connect to CDP
try {
this.client = await CDP({ port: cdpPort });
console.log('[CustomDriver] CDP connected');
// Enable necessary domains
await Promise.all([
this.client.Page.enable(),
this.client.Runtime.enable(),
this.client.Network.enable(),
this.client.DOM.enable()
]);
// Connect Playwright to the same CDP endpoint
console.log('[CustomDriver] Connecting Playwright...');
try {
this.playwrightBrowser = await chromium.connectOverCDP(`http://localhost:${cdpPort}`);
console.log('[CustomDriver] Playwright connected');
} catch (err) {
console.warn('[CustomDriver] Playwright connection failed:', err.message);
console.warn('[CustomDriver] Actions will not be available');
}
console.log('[CustomDriver] Browser started successfully');
} catch (error) {
console.error('[CustomDriver] Failed to connect to CDP:', error.message);
this.stop();
throw error;
}
}
/**
* Stop the browser
* @returns {Promise<void>}
*/
async stop() {
console.log('[CustomDriver] Stopping browser...');
// Close Playwright connections
if (this.playwrightBrowser) {
try {
await this.playwrightBrowser.close();
} catch (err) {
console.warn('[CustomDriver] Error closing Playwright browser:', err.message);
}
this.playwrightBrowser = null;
}
this.playwrightPages.clear();
if (this.client) {
try {
await this.client.close();
} catch (err) {
console.warn('[CustomDriver] Error closing CDP client:', err.message);
}
this.client = null;
}
if (this.proc) {
this.proc.kill('SIGTERM');
this.proc = null;
}
this.tabs.clear();
console.log('[CustomDriver] Browser stopped');
}
/**
* Get browser status
* @returns {Promise<Object>}
*/
async status() {
const running = this.client !== null && this.proc !== null;
return {
running,
profile: this.profile?.name || null,
cdpPort: this.profile?.cdpPort || null,
tabCount: this.tabs.size
};
}
/**
* List all open tabs
* @returns {Promise<Array>}
*/
async listTabs() {
if (!this.client) {
throw new Error('Browser not running');
}
try {
// Use CDP HTTP endpoint to list tabs
const http = require('http');
const port = this.profile.cdpPort;
return new Promise((resolve, reject) => {
http.get(`http://localhost:${port}/json/list`, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
try {
const targets = JSON.parse(data);
const tabs = targets
.filter(t => t.type === 'page')
.map(t => ({
targetId: t.id,
title: t.title,
url: t.url,
webSocketDebuggerUrl: t.webSocketDebuggerUrl
}));
// Update internal tabs map
for (const tab of tabs) {
this.tabs.set(tab.targetId, tab);
}
resolve(tabs);
} catch (e) {
reject(e);
}
});
}).on('error', reject);
});
} catch (error) {
console.error('[CustomDriver] Error listing tabs:', error.message);
return [];
}
}
/**
* Open a new tab with given URL
* @param {string} url - URL to open
* @returns {Promise<Object>}
*/
async openTab(url) {
if (!this.client) {
throw new Error('Browser not running');
}
console.log('[CustomDriver] Opening tab:', url);
// Use CDP HTTP endpoint to create new tab
const http = require('http');
const port = this.profile.cdpPort;
const encodedUrl = encodeURIComponent(url);
return new Promise((resolve, reject) => {
const req = http.request({
hostname: 'localhost',
port: port,
path: `/json/new?${encodedUrl}`,
method: 'PUT'
}, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
try {
const target = JSON.parse(data);
const tab = {
targetId: target.id,
url: target.url,
title: target.title || 'Loading...'
};
this.tabs.set(tab.targetId, tab);
resolve(tab);
} catch (e) {
console.error('[CustomDriver] Failed to parse response:', data.substring(0, 200));
reject(new Error(`Failed to parse CDP response: ${e.message}`));
}
});
});
req.on('error', reject);
req.end();
});
}
/**
* Focus a tab by targetId
* @param {string} targetId - Target ID
* @returns {Promise<void>}
*/
async focusTab(targetId) {
if (!this.client) {
throw new Error('Browser not running');
}
console.log('[CustomDriver] Focusing tab:', targetId);
// Use CDP HTTP endpoint to activate tab
const http = require('http');
const port = this.profile.cdpPort;
return new Promise((resolve, reject) => {
http.get(`http://localhost:${port}/json/activate/${targetId}`, (res) => {
if (res.statusCode === 200) {
resolve();
} else {
reject(new Error(`Failed to activate tab: ${res.statusCode}`));
}
}).on('error', reject);
});
}
/**
* Close a tab by targetId
* @param {string} targetId - Target ID
* @returns {Promise<void>}
*/
async closeTab(targetId) {
if (!this.client) {
throw new Error('Browser not running');
}
console.log('[CustomDriver] Closing tab:', targetId);
// Use CDP HTTP endpoint to close tab
const http = require('http');
const port = this.profile.cdpPort;
return new Promise((resolve, reject) => {
http.get(`http://localhost:${port}/json/close/${targetId}`, (res) => {
if (res.statusCode === 200) {
this.tabs.delete(targetId);
resolve();
} else {
reject(new Error(`Failed to close tab: ${res.statusCode}`));
}
}).on('error', reject);
});
}
/**
* Navigate to URL in specified tab
* @param {string} targetId - Target ID
* @param {string} url - URL to navigate to
* @returns {Promise<void>}
*/
async navigate(targetId, url) {
if (!this.client) {
throw new Error('Browser not running');
}
console.log('[CustomDriver] Navigating to:', url);
try {
// Use Playwright for navigation if available (more robust)
if (this.playwrightBrowser) {
const page = await this.getPlaywrightPage(targetId);
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
console.log('[CustomDriver] ✓ Navigation complete (Playwright)');
} else {
// Fallback to CDP
await this.client.Page.navigate({ url });
await sleep(2000);
console.log('[CustomDriver] ✓ Navigation complete (CDP)');
}
} catch (error) {
console.error('[CustomDriver] Navigation failed:', error.message);
throw error;
}
}
/**
* Take screenshot of current tab
* @param {string} targetId - Target ID
* @param {Object} options - Screenshot options
* @returns {Promise<Buffer>}
*/
async screenshot(targetId, options = {}) {
if (!this.client) {
throw new Error('Browser not running');
}
console.log('[CustomDriver] Taking screenshot of:', targetId);
const { data } = await this.client.Page.captureScreenshot({
format: options.format || 'png',
quality: options.quality || 90,
fromSurface: true,
captureBeyondViewport: options.fullPage || false
});
return Buffer.from(data, 'base64');
}
/**
* Get Playwright page for a given target
* @param {string} targetId - Target ID
* @returns {Promise<Page>}
*/
async getPlaywrightPage(targetId) {
if (!this.playwrightBrowser) {
throw new Error('Playwright not connected. Actions require Playwright.');
}
// Check if we already have a page reference
if (this.playwrightPages.has(targetId)) {
const page = this.playwrightPages.get(targetId);
// Verify page is still valid
if (!page.isClosed()) {
return page;
} else {
this.playwrightPages.delete(targetId);
}
}
// Wait a moment for Playwright to pick up the new tab
await sleep(500);
// Find the page in Playwright's context
const contexts = this.playwrightBrowser.contexts();
for (const context of contexts) {
const pages = context.pages();
// Try URL matching first (most reliable for newly opened tabs)
const tab = this.tabs.get(targetId);
if (tab) {
for (const page of pages) {
if (page.url() === tab.url) {
this.playwrightPages.set(targetId, page);
return page;
}
}
}
// If only one page and no mapping yet, use it
if (pages.length === 1 && this.playwrightPages.size === 0) {
const page = pages[0];
this.playwrightPages.set(targetId, page);
return page;
}
// Try to match the most recently created page
if (pages.length > 0) {
const page = pages[pages.length - 1];
if (!Array.from(this.playwrightPages.values()).includes(page)) {
this.playwrightPages.set(targetId, page);
return page;
}
}
}
throw new Error(`No Playwright page found for target ${targetId}. Open a tab first.`);
}
/**
* Get page snapshot (simplified version)
* @param {string} targetId - Target ID
* @param {Object} options - Snapshot options
* @returns {Promise<Object>}
*/
async snapshot(targetId, options = {}) {
if (!this.client) {
throw new Error('Browser not running');
}
console.log('[CustomDriver] Getting snapshot of:', targetId);
// ARIA snapshot (Playwright required)
if (options.format === 'aria' && this.playwrightBrowser) {
try {
const page = await this.getPlaywrightPage(targetId);
// Get accessibility tree from Playwright
const snapshot = await page.accessibility.snapshot();
return {
format: 'aria',
snapshot: JSON.stringify(snapshot, null, 2),
url: await page.url()
};
} catch (err) {
console.warn('[CustomDriver] ARIA snapshot failed:', err.message);
// Fall back to HTML
}
}
// HTML snapshot (CDP fallback)
const { root } = await this.client.DOM.getDocument({ depth: -1 });
const { outerHTML } = await this.client.DOM.getOuterHTML({ nodeId: root.nodeId });
return {
format: 'html',
html: outerHTML,
url: this.tabs.get(targetId)?.url || 'unknown'
};
}
/**
* Get cookies
* @param {string} targetId - Target ID
* @returns {Promise<Array>}
*/
async getCookies(targetId) {
if (!this.client) {
throw new Error('Browser not running');
}
const { cookies } = await this.client.Network.getCookies();
return cookies;
}
/**
* Set cookie
* @param {string} targetId - Target ID
* @param {Object} cookie - Cookie object
* @returns {Promise<void>}
*/
async setCookie(targetId, cookie) {
if (!this.client) {
throw new Error('Browser not running');
}
await this.client.Network.setCookie(cookie);
}
/**
* Evaluate JavaScript in page context
* @param {string} targetId - Target ID
* @param {string} expression - JavaScript expression
* @returns {Promise<any>}
*/
async evaluate(targetId, expression) {
if (!this.client) {
throw new Error('Browser not running');
}
console.log('[CustomDriver] Evaluating:', expression);
const { result } = await this.client.Runtime.evaluate({
expression,
returnByValue: true
});
return result.value;
}
/**
* Perform action (click/type/etc) using Playwright
* @param {string} targetId - Target ID
* @param {Object} action - Action object with { kind, ref, text, key, ... }
* @returns {Promise<void>}
*/
async act(targetId, action) {
if (!this.playwrightBrowser) {
throw new Error('Actions require Playwright. Playwright not connected.');
}
console.log('[CustomDriver] Performing action:', action.kind, 'on ref:', action.ref);
const page = await this.getPlaywrightPage(targetId);
// Get element by ref (assuming aria-ref or CSS selector)
let locator;
if (action.ref) {
// Try aria-ref first (numeric refs like "12")
if (/^\d+$/.test(action.ref)) {
locator = page.locator(`[aria-ref="${action.ref}"]`);
} else if (action.ref.startsWith('e')) {
// Role-based ref like "e12"
// This would need proper role mapping; simplified for now
locator = page.locator(`[ref="${action.ref}"]`);
} else {
// Treat as CSS selector fallback
locator = page.locator(action.ref);
}
}
switch (action.kind) {
case 'click':
if (!locator) throw new Error('Click action requires ref');
await locator.click({
button: action.button || 'left',
clickCount: action.doubleClick ? 2 : 1,
modifiers: action.modifiers || []
});
console.log('[CustomDriver] ✓ Clicked');
break;
case 'type':
if (!locator) throw new Error('Type action requires ref');
await locator.fill(action.text || '');
if (action.submit) {
await locator.press('Enter');
}
console.log('[CustomDriver] ✓ Typed:', action.text);
break;
case 'press':
if (action.key) {
await page.keyboard.press(action.key, {
delay: action.slowly ? 100 : undefined
});
}
console.log('[CustomDriver] ✓ Pressed key:', action.key);
break;
case 'hover':
if (!locator) throw new Error('Hover action requires ref');
await locator.hover();
console.log('[CustomDriver] ✓ Hovered');
break;
case 'drag':
if (!action.startRef || !action.endRef) {
throw new Error('Drag action requires startRef and endRef');
}
const startLoc = page.locator(`[aria-ref="${action.startRef}"]`);
const endLoc = page.locator(`[aria-ref="${action.endRef}"]`);
await startLoc.dragTo(endLoc);
console.log('[CustomDriver] ✓ Dragged');
break;
case 'select':
if (!locator) throw new Error('Select action requires ref');
await locator.selectOption(action.values || []);
console.log('[CustomDriver] ✓ Selected:', action.values);
break;
case 'fill':
// Batch form filling
if (action.fields && Array.isArray(action.fields)) {
for (const field of action.fields) {
const fieldLoc = page.locator(`[aria-ref="${field.ref}"]`);
await fieldLoc.fill(field.value || '');
}
console.log('[CustomDriver] ✓ Filled', action.fields.length, 'fields');
}
break;
case 'wait':
// Wait for various conditions
if (action.text) {
await page.waitForSelector(`text=${action.text}`, {
timeout: action.timeMs || 30000
});
console.log('[CustomDriver] ✓ Waited for text:', action.text);
} else if (action.ref) {
await locator.waitFor({ timeout: action.timeMs || 30000 });
console.log('[CustomDriver] ✓ Waited for element');
} else if (action.timeMs) {
await sleep(action.timeMs);
console.log('[CustomDriver] ✓ Waited', action.timeMs, 'ms');
}
break;
case 'resize':
await page.setViewportSize({
width: action.width || 1280,
height: action.height || 720
});
console.log('[CustomDriver] ✓ Resized viewport');
break;
case 'evaluate':
if (!action.fn) throw new Error('Evaluate requires fn');
// Support both string function and actual function
let evalFn = action.fn;
if (typeof evalFn === 'string') {
// If it's a string like "() => document.title", evaluate it
evalFn = eval(`(${evalFn})`);
}
const result = await page.evaluate(evalFn);
console.log('[CustomDriver] ✓ Evaluated, result:', result);
return result;
case 'close':
await page.close();
this.playwrightPages.delete(targetId);
console.log('[CustomDriver] ✓ Closed page');
break;
default:
throw new Error(`Unknown action kind: ${action.kind}`);
}
}
/**
* Setup console log capture for a page
* @param {string} targetId - Target ID
* @returns {Promise<void>}
*/
async setupConsoleCapture(targetId) {
if (!this.playwrightBrowser) return;
try {
const page = await this.getPlaywrightPage(targetId);
if (!this.consoleLogs.has(targetId)) {
this.consoleLogs.set(targetId, []);
}
page.on('console', msg => {
this.consoleLogs.get(targetId).push({
type: msg.type(),
text: msg.text(),
timestamp: Date.now()
});
});
console.log('[CustomDriver] Console capture enabled for', targetId);
} catch (err) {
console.warn('[CustomDriver] Console capture setup failed:', err.message);
}
}
/**
* Get console logs for a page
* @param {string} targetId - Target ID
* @param {Object} options - Options like level filter
* @returns {Promise<Array>}
*/
async getConsoleLogs(targetId, options = {}) {
const logs = this.consoleLogs.get(targetId) || [];
if (options.level) {
return logs.filter(log => log.type === options.level);
}
return logs;
}
/**
* Clear console logs for a page
* @param {string} targetId - Target ID
* @returns {Promise<void>}
*/
async clearConsoleLogs(targetId) {
this.consoleLogs.set(targetId, []);
console.log('[CustomDriver] Console logs cleared for', targetId);
}
/**
* Setup network request monitoring
* @param {string} targetId - Target ID
* @returns {Promise<void>}
*/
async setupNetworkMonitoring(targetId) {
if (!this.playwrightBrowser) return;
try {
const page = await this.getPlaywrightPage(targetId);
if (!this.networkLogs.has(targetId)) {
this.networkLogs.set(targetId, []);
}
page.on('request', request => {
this.networkLogs.get(targetId).push({
type: 'request',
url: request.url(),
method: request.method(),
timestamp: Date.now()
});
});
page.on('response', response => {
this.networkLogs.get(targetId).push({
type: 'response',
url: response.url(),
status: response.status(),
timestamp: Date.now()
});
});
console.log('[CustomDriver] Network monitoring enabled for', targetId);
} catch (err) {
console.warn('[CustomDriver] Network monitoring setup failed:', err.message);
}
}
/**
* Get network logs
* @param {string} targetId - Target ID
* @param {Object} options - Filter options
* @returns {Promise<Array>}
*/
async getNetworkLogs(targetId, options = {}) {
const logs = this.networkLogs.get(targetId) || [];
if (options.filter) {
return logs.filter(log => log.url.includes(options.filter));
}
return logs;
}
/**
* Clear network logs
* @param {string} targetId - Target ID
* @returns {Promise<void>}
*/
async clearNetworkLogs(targetId) {
this.networkLogs.set(targetId, []);
console.log('[CustomDriver] Network logs cleared for', targetId);
}
/**
* Setup file upload (arm file chooser)
* @param {string} targetId - Target ID
* @param {Array<string>} filePaths - Paths to files
* @returns {Promise<void>}
*/
async setupFileUpload(targetId, filePaths) {
if (!this.playwrightBrowser) {
throw new Error('File upload requires Playwright');
}
const page = await this.getPlaywrightPage(targetId);
// Arm the file chooser
page.once('filechooser', async fileChooser => {
await fileChooser.setFiles(filePaths);
console.log('[CustomDriver] ✓ Files uploaded:', filePaths);
});
console.log('[CustomDriver] File chooser armed');
}
/**
* Wait for and handle download
* @param {string} targetId - Target ID
* @param {string} saveAs - Optional filename
* @returns {Promise<string>} - Path to downloaded file
*/
async waitForDownload(targetId, saveAs) {
if (!this.playwrightBrowser) {
throw new Error('Download handling requires Playwright');
}
const page = await this.getPlaywrightPage(targetId);
const fs = require('fs');
const path = require('path');
// Ensure download directory exists
if (!fs.existsSync(this.downloadPath)) {
fs.mkdirSync(this.downloadPath, { recursive: true });
}
return new Promise((resolve, reject) => {
page.once('download', async download => {
try {
const suggestedFilename = download.suggestedFilename();
const filename = saveAs || suggestedFilename;
const savePath = path.join(this.downloadPath, filename);
await download.saveAs(savePath);
console.log('[CustomDriver] ✓ Download saved:', savePath);
resolve(savePath);
} catch (err) {
reject(err);
}
});
// Timeout after 30 seconds
setTimeout(() => reject(new Error('Download timeout')), 30000);
});
}
/**
* Emulate device
* @param {string} targetId - Target ID
* @param {string} deviceName - Device name from Playwright presets
* @returns {Promise<void>}
*/
async emulateDevice(targetId, deviceName) {
if (!this.playwrightBrowser) {
throw new Error('Device emulation requires Playwright');
}
const { devices } = require('playwright-core');
const deviceDescriptor = devices[deviceName];
if (!deviceDescriptor) {
throw new Error(`Unknown device: ${deviceName}. See playwright.dev/docs/emulation`);
}
const page = await this.getPlaywrightPage(targetId);
// Apply device settings manually
if (deviceDescriptor.viewport) {
await page.setViewportSize(deviceDescriptor.viewport);
}
if (deviceDescriptor.userAgent) {
await page.context().setExtraHTTPHeaders({
'User-Agent': deviceDescriptor.userAgent
});
}
console.log('[CustomDriver] ✓ Emulating device:', deviceName);
}
/**
* Set geolocation
* @param {string} targetId - Target ID
* @param {Object} location - { latitude, longitude, accuracy }
* @returns {Promise<void>}
*/
async setGeolocation(targetId, location) {
if (!this.playwrightBrowser) {
throw new Error('Geolocation requires Playwright');
}
const page = await this.getPlaywrightPage(targetId);
await page.context().setGeolocation(location);
console.log('[CustomDriver] ✓ Geolocation set:', location);
}
/**
* Clear geolocation
* @param {string} targetId - Target ID
* @returns {Promise<void>}
*/
async clearGeolocation(targetId) {
if (!this.playwrightBrowser) return;
const page = await this.getPlaywrightPage(targetId);
// Set geolocation to null to clear it
await page.context().clearPermissions();
console.log('[CustomDriver] ✓ Geolocation cleared');
}
/**
* Set timezone
* @param {string} targetId - Target ID
* @param {string} timezoneId - IANA timezone ID
* @returns {Promise<void>}
*/
async setTimezone(targetId, timezoneId) {
if (!this.playwrightBrowser) {
throw new Error('Timezone override requires Playwright');
}
const page = await this.getPlaywrightPage(targetId);
// Use CDP to set timezone via emulation
const session = await page.context().newCDPSession(page);
await session.send('Emulation.setTimezoneOverride', { timezoneId });
console.log('[CustomDriver] ✓ Timezone set:', timezoneId);
}
/**
* Set custom headers
* @param {string} targetId - Target ID
* @param {Object} headers - Headers object
* @returns {Promise<void>}
*/
async setExtraHTTPHeaders(targetId, headers) {
if (!this.playwrightBrowser) {
throw new Error('Custom headers require Playwright');
}
const page = await this.getPlaywrightPage(targetId);
await page.setExtraHTTPHeaders(headers);
console.log('[CustomDriver] ✓ Custom headers set');
}
}
module.exports = { CustomBrowserDriver };