You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Selenium WebDriver的createSession()同步启动Chrome?

How to Wait for Chrome to Fully Launch Before Running Code with Selenium WebDriver

Ah, I get it—you’re running into a classic async timing issue here! The problem is that Driver.createSession() in Selenium’s JavaScript library doesn’t block execution until Chrome is fully up and running. Instead, it returns a Promise that resolves only once the browser session is successfully established. Since you’re not waiting for that Promise to complete, your console.log fires right away, before the browser window even appears.

The Fix: Use Async/Await (or Promise Chaining)

To make sure your code waits for Chrome to launch before printing your message, you need to handle the asynchronous nature of createSession(). Here are two clean ways to do this:

Option 1: Async/Await (Recommended for Readability)

Wrap your code in an async function and use the await keyword to pause execution until the session is created:

import { Driver } from 'selenium-webdriver/chrome';

async function launchAndVerifyChrome() {
  try {
    // Wait for the browser session to be fully established
    const driver = await Driver.createSession();
    
    // This line will only run AFTER Chrome has launched successfully
    console.log("I've launched!");

    // Add your subsequent browser operations here (e.g., navigating to a URL)
    // await driver.get('https://www.example.com');
  } catch (error) {
    // Handle any errors that occur during launch
    console.error('Failed to start Chrome:', error);
  }
}

// Call the async function
launchAndVerifyChrome();

Option 2: Promise Chaining

If you prefer not to use async/await, you can chain a .then() handler to the Promise returned by createSession():

import { Driver } from 'selenium-webdriver/chrome';

Driver.createSession()
  .then(driver => {
    // Runs only after the browser session is ready
    console.log("I've launched!");
    // Add your browser actions here
  })
  .catch(error => {
    console.error('Chrome launch failed:', error);
  });

Why This Works

Both approaches ensure that your console.log (or any subsequent code) only executes once the createSession() Promise resolves. That resolution happens after Selenium has successfully launched the Chrome instance and established a communication session with it—exactly what you need.

内容的提问来源于stack exchange,提问作者aBlaze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:45:44