browser-use-typescript
Version:
A TypeScript-based browser automation framework
91 lines • 3.15 kB
JavaScript
import * as playwright from "playwright";
import { BrowserContext, BrowserContextConfig } from "./browserContext";
import { DEFAULT_CHROME_CONFIG, getChromeArgs } from "./chrome";
export class BrowserConfig {
headless = false;
disable_security = true;
//extra_browser_args: string[] = [];
wss_url = null;
//cdp_url: string | null = null;
browser_instance_path = null;
//proxy: ProxySettings | null = null;
new_context_config = new BrowserContextConfig();
_force_keep_browser_alive = false;
constructor(param) {
this.headless = param?.headless ? param.headless : false;
this.wss_url = param?.wss_url ? param.wss_url : null;
}
}
export class Browser {
config;
//playwright: typeof playwright | null;
playwright_browser;
constructor(config = new BrowserConfig()) {
this.config = config;
this.playwright_browser = null;
console.log("Starting new browser ");
}
async new_context(config = new BrowserContextConfig()) {
return new BrowserContext({ config: config });
}
async get_playwright_browser() {
if (this.playwright_browser === null) {
return await this._init();
}
return this.playwright_browser;
}
async _init() {
if (this.playwright_browser === null) {
this.playwright_browser = await this.setupBrowser();
}
return this.playwright_browser;
}
async close() {
if (this.playwright_browser !== null) {
await this.playwright_browser.close();
this.playwright_browser = null;
}
}
async setupBrowser() {
try {
if (this.config.wss_url) {
return await this.setup_remote_wss_browser();
}
if (this.config.headless) {
console.log("Setting up headless browser");
}
return await this.setup_builtin_browser();
}
catch (error) {
console.error("Failed to setup browser", error);
throw error;
}
}
async setup_remote_wss_browser() {
if (!this.config.wss_url) {
throw new Error("WSS URL is required");
}
return await playwright.chromium.connect(this.config.wss_url);
}
async setup_builtin_browser() {
try {
console.log(this.config.headless);
const chromeArgs = await getChromeArgs(DEFAULT_CHROME_CONFIG);
// Filter out headless arguments if we're not in headless mode
const filteredArgs = this.config.headless
? chromeArgs
: chromeArgs.filter(arg => !arg.includes('--headless'));
this.playwright_browser = await playwright.chromium.launch({
headless: this.config.headless,
args: filteredArgs,
});
console.log("Browser initialized");
return this.playwright_browser;
}
catch (error) {
console.error("Failed to setup browser", error);
throw error;
}
}
}
//# sourceMappingURL=browserService.js.map