browser-commander 0.10.8

Universal browser automation library that supports multiple browser engines with a unified API
Documentation
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
import readline from "node:readline";

let engineName = null;
let browser = null;
let context = null;
let page = null;
let verbose = false;

const rl = readline.createInterface({
  input: process.stdin,
  crlfDelay: Infinity,
});

function log(message) {
  if (verbose) {
    console.error(`[browser-commander:${engineName ?? "bridge"}] ${message}`);
  }
}

function serializeResult(value) {
  return value === undefined ? null : value;
}

function compactObject(value) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return value;
  }

  const entries = Object.entries(value)
    .filter(([, entryValue]) => entryValue !== null && entryValue !== undefined)
    .map(([key, entryValue]) => [key, compactObject(entryValue)])
    .filter(([, entryValue]) => {
      return (
        !entryValue ||
        typeof entryValue !== "object" ||
        Array.isArray(entryValue) ||
        Object.keys(entryValue).length > 0
      );
    });

  return Object.fromEntries(entries);
}

function send(response) {
  process.stdout.write(`${JSON.stringify(response)}\n`);
}

function ensurePage() {
  if (!page) {
    throw new Error("Browser page is not initialized. Send launch or connect first.");
  }
  return page;
}

function chromeArgs(params) {
  const args = [...(params.args ?? [])];
  if (params.sandbox === false) {
    for (const flag of ["--no-sandbox", "--disable-setuid-sandbox"]) {
      if (!args.includes(flag)) {
        args.push(flag);
      }
    }
  }
  return args;
}

function ignoredDefaultArgs(params, includeEnableAutomation = false) {
  if (params.ignoreDefaultArgs === true) {
    return true;
  }
  const ignored = [...(params.ignoreDefaultArgs ?? [])];
  if (includeEnableAutomation && !ignored.includes("--enable-automation")) {
    ignored.unshift("--enable-automation");
  }
  return ignored;
}

function elementInfo(selector) {
  const el = document.querySelector(selector);
  if (!el) {
    return null;
  }

  const rect = el.getBoundingClientRect();
  const style = window.getComputedStyle(el);
  const isVisible =
    style.display !== "none" &&
    style.visibility !== "hidden" &&
    rect.width > 0 &&
    rect.height > 0;

  return {
    tagName: el.tagName,
    textContent: el.textContent,
    isVisible,
    isEnabled: !el.disabled,
    boundingBox: isVisible ? [rect.x, rect.y, rect.width, rect.height] : null,
  };
}

async function launchPlaywright(params) {
  const { chromium } = await import("playwright");
  const contextOptions = {
    headless: params.headless,
    slowMo: params.slowMo,
    chromiumSandbox: params.sandbox !== false,
    viewport: null,
    args: chromeArgs(params),
    ignoreDefaultArgs: ignoredDefaultArgs(params, true),
  };

  if (params.colorScheme !== null && params.colorScheme !== undefined) {
    contextOptions.colorScheme = params.colorScheme;
  }
  if (params.channel !== null && params.channel !== undefined) {
    contextOptions.channel = params.channel;
  }
  if (params.executablePath !== null && params.executablePath !== undefined) {
    contextOptions.executablePath = params.executablePath;
  }

  context = await chromium.launchPersistentContext(
    params.userDataDir,
    contextOptions,
  );
  const pages = context.pages();
  page = pages[0] ?? (await context.newPage());
  browser = context;
}

async function launchPuppeteer(params) {
  const puppeteer = await import("puppeteer");
  const launchOptions = {
    headless: params.headless,
    slowMo: params.slowMo,
    defaultViewport: null,
    args: ["--start-maximized", ...chromeArgs(params)],
    userDataDir: params.userDataDir,
  };
  const ignoredArgs = ignoredDefaultArgs(params);
  if (ignoredArgs === true || ignoredArgs.length > 0) {
    launchOptions.ignoreDefaultArgs = ignoredArgs;
  }
  if (params.channel !== null && params.channel !== undefined) {
    launchOptions.channel = params.channel;
  }
  if (params.executablePath !== null && params.executablePath !== undefined) {
    launchOptions.executablePath = params.executablePath;
  }
  browser = await puppeteer.default.launch(launchOptions);
  const pages = await browser.pages();
  page = pages[0] ?? (await browser.newPage());

  if (params.colorScheme !== null && params.colorScheme !== undefined) {
    await applyColorScheme(params.colorScheme);
  }
}

async function connectPlaywright(params) {
  const { chromium } = await import("playwright");
  browser = await chromium.connectOverCDP(
    params.cdpEndpoint ?? params.wsEndpoint,
    compactObject({
      slowMo: params.slowMo,
      timeout: params.timeout,
    }),
  );
  context = browser.contexts()[0];
  if (!context) {
    throw new Error("Connected browser did not expose a default context");
  }
  const pages = context.pages();
  page = pages[0] ?? (await context.newPage());
  if (params.seedCookies?.length) {
    await context.addCookies(params.seedCookies);
  }
}

async function connectPuppeteer(params) {
  const puppeteer = await import("puppeteer");
  browser = await puppeteer.default.connect(
    compactObject({
      browserURL: params.cdpEndpoint,
      browserWSEndpoint: params.wsEndpoint,
      defaultViewport: null,
      slowMo: params.slowMo,
      protocolTimeout: params.protocolTimeout,
    }),
  );
  const pages = await browser.pages();
  page = pages[0] ?? (await browser.newPage());
  if (params.seedCookies?.length) {
    await page.setCookie(...params.seedCookies);
  }
}

async function applyColorScheme(colorScheme) {
  const currentPage = ensurePage();
  if (engineName === "playwright") {
    await currentPage.emulateMedia({ colorScheme });
  } else {
    await currentPage.emulateMediaFeatures(
      colorScheme === null
        ? []
        : [{ name: "prefers-color-scheme", value: colorScheme }],
    );
  }
}

async function handleLaunch(params) {
  engineName = params.engine;
  verbose = Boolean(params.verbose);

  process.env.GOOGLE_API_KEY = "no";
  process.env.GOOGLE_DEFAULT_CLIENT_ID = "no";
  process.env.GOOGLE_DEFAULT_CLIENT_SECRET = "no";

  if (engineName === "playwright") {
    await launchPlaywright(params);
  } else if (engineName === "puppeteer") {
    await launchPuppeteer(params);
  } else {
    throw new Error(`Unsupported bridge engine: ${engineName}`);
  }

  try {
    await page.bringToFront();
  } catch (error) {
    log(`bringToFront failed: ${error.message}`);
  }

  return { engine: engineName };
}

async function handleConnect(params) {
  engineName = params.engine;
  verbose = Boolean(params.verbose);

  if (engineName === "playwright") {
    await connectPlaywright(params);
  } else if (engineName === "puppeteer") {
    await connectPuppeteer(params);
  } else {
    throw new Error(`Unsupported bridge engine: ${engineName}`);
  }

  try {
    await page.bringToFront();
  } catch (error) {
    log(`bringToFront failed: ${error.message}`);
  }

  return { engine: engineName };
}

async function handleCommand(method, params) {
  switch (method) {
    case "launch":
      return await handleLaunch(params);
    case "connect":
      return await handleConnect(params);
    case "close":
      if (browser) {
        await browser.close();
      }
      return null;
    case "url":
      return ensurePage().url();
    case "goto":
      await ensurePage().goto(params.url, { waitUntil: "load" });
      return null;
    case "querySelector":
      return await ensurePage().evaluate(elementInfo, params.selector);
    case "querySelectorAll":
      return await ensurePage().evaluate((selector) => {
        return Array.from(document.querySelectorAll(selector), (el) => {
          const rect = el.getBoundingClientRect();
          const style = window.getComputedStyle(el);
          const isVisible =
            style.display !== "none" &&
            style.visibility !== "hidden" &&
            rect.width > 0 &&
            rect.height > 0;

          return {
            tagName: el.tagName,
            textContent: el.textContent,
            isVisible,
            isEnabled: !el.disabled,
            boundingBox: isVisible
              ? [rect.x, rect.y, rect.width, rect.height]
              : null,
          };
        });
      }, params.selector);
    case "count":
      return await ensurePage().evaluate(
        (selector) => document.querySelectorAll(selector).length,
        params.selector,
      );
    case "click":
      await ensurePage().click(params.selector);
      return null;
    case "fill":
      if (engineName === "playwright") {
        await ensurePage().fill(params.selector, params.text);
      } else {
        await ensurePage().$eval(
          params.selector,
          (el, text) => {
            el.value = text;
            el.dispatchEvent(new Event("input", { bubbles: true }));
            el.dispatchEvent(new Event("change", { bubbles: true }));
          },
          params.text,
        );
      }
      return null;
    case "typeText":
      await ensurePage().focus(params.selector);
      await ensurePage().keyboard.type(params.text);
      return null;
    case "textContent":
      return await ensurePage().evaluate((selector) => {
        const el = document.querySelector(selector);
        return el ? el.textContent : null;
      }, params.selector);
    case "inputValue":
      return await ensurePage().evaluate((selector) => {
        const el = document.querySelector(selector);
        return el && "value" in el ? el.value : null;
      }, params.selector);
    case "getAttribute":
      return await ensurePage().evaluate(
        ({ selector, attribute }) => {
          const el = document.querySelector(selector);
          return el ? el.getAttribute(attribute) : null;
        },
        { selector: params.selector, attribute: params.attribute },
      );
    case "isVisible":
      return Boolean(
        (await ensurePage().evaluate(elementInfo, params.selector))?.isVisible,
      );
    case "isEnabled":
      return await ensurePage().evaluate((selector) => {
        const el = document.querySelector(selector);
        return el ? !el.disabled : false;
      }, params.selector);
    case "waitForSelector":
      if (engineName === "playwright") {
        await ensurePage().waitForSelector(params.selector, {
          state: "visible",
          timeout: params.timeoutMs,
        });
      } else {
        await ensurePage().waitForSelector(params.selector, {
          visible: true,
          timeout: params.timeoutMs,
        });
      }
      return null;
    case "scrollIntoView":
      await ensurePage().evaluate((selector) => {
        const el = document.querySelector(selector);
        if (!el) {
          throw new Error(`Element not found: ${selector}`);
        }
        el.scrollIntoView({ block: "center", inline: "center" });
      }, params.selector);
      return null;
    case "evaluate":
      return serializeResult(await ensurePage().evaluate(params.script));
    case "screenshot":
      return Buffer.from(await ensurePage().screenshot()).toString("base64");
    case "pdf":
      return Buffer.from(
        await ensurePage().pdf(compactObject(params)),
      ).toString("base64");
    case "bringToFront":
      await ensurePage().bringToFront();
      return null;
    case "waitForNavigation":
      if (engineName === "playwright") {
        await ensurePage().waitForLoadState("load", {
          timeout: params.timeoutMs,
        });
      } else {
        await ensurePage().waitForNavigation({
          timeout: params.timeoutMs,
          waitUntil: "load",
        });
      }
      return null;
    case "keyboardPress":
      await ensurePage().keyboard.press(params.key);
      return null;
    case "keyboardType":
      await ensurePage().keyboard.type(params.text);
      return null;
    case "keyboardDown":
      await ensurePage().keyboard.down(params.key);
      return null;
    case "keyboardUp":
      await ensurePage().keyboard.up(params.key);
      return null;
    default:
      throw new Error(`Unknown bridge method: ${method}`);
  }
}

rl.on("line", async (line) => {
  let request;
  try {
    request = JSON.parse(line);
    const result = await handleCommand(request.method, request.params ?? {});
    send({ id: request.id, ok: true, result: serializeResult(result) });
  } catch (error) {
    send({
      id: request?.id ?? 0,
      ok: false,
      error: error?.stack ?? error?.message ?? String(error),
    });
  }
});

process.on("SIGTERM", async () => {
  try {
    if (browser) {
      await browser.close();
    }
  } finally {
    process.exit(0);
  }
});