import dotenv from "dotenv";
import https from "https";
import { Builder, WebDriver } from "selenium-webdriver";
import fs from "fs";
import { Options } from "selenium-webdriver/chrome";
import { Hyperbrowser } from "@hyperbrowser/sdk";
// Load environment variables from .env file
dotenv.config();
const client = new Hyperbrowser({ apiKey: process.env.HYPERBROWSER_API_KEY });
async function main() {
const session = await client.sessions.create();
if (!session.webdriverEndpoint) {
await client.sessions.stop(session.id);
throw new Error("No webdriver endpoint found");
}
const customHttpsAgent = new https.Agent({});
(customHttpsAgent as any).addRequest = (req: any, options: any) => {
req.setHeader("x-hyperbrowser-token", session.token);
(https.Agent.prototype as any).addRequest.call(
customHttpsAgent,
req,
options
);
};
const driver: WebDriver = await new Builder()
.forBrowser("chrome")
.usingHttpAgent(customHttpsAgent)
.usingServer(session.webdriverEndpoint)
.setChromeOptions(new Options())
.build();
try {
// Navigate to a URL
await driver.get("https://www.google.com");
console.log("Navigated to Google");
// Search
const searchBox = await driver.findElement({ name: "q" });
await searchBox.sendKeys("Selenium WebDriver");
await searchBox.submit();
console.log("Performed search");
// Screenshot
await driver.takeScreenshot().then((data) => {
fs.writeFileSync("search_results.png", data, "base64");
});
console.log("Screenshot saved");
} finally {
await driver.quit();
await client.sessions.stop(session.id);
}
}
main().catch(console.error);