User Agents

Web browsers and everyday web tech, explained

Automate Browser Actions: Playwright, Selenium, and CDP

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Automating browser actions allows you to programmatically control a web browser to perform repetitive tasks, test web applications, or scrape data. By using tools like Playwright, Selenium, or the Chrome DevTools Protocol (CDP), you can simulate clicks, keystrokes, and navigation, and even interact with Chrome extensions that would otherwise be inaccessible to standard automation scripts. This guide covers how to implement these tools to achieve full control over the Chrome browser environment.

What You'll Need

  • Node.js (for Playwright) or Python (for Selenium/Playwright) installed on your system.
  • Google Chrome or Chromium browser.
  • A code editor such as Visual Studio Code.
  • The unpacked folder of the Chrome extension you intend to automate.
  • Basic knowledge of CSS selectors or XPath for element targeting.

Step-by-Step

  1. Choose Your Framework: Determine which tool fits your needs. Use Playwright for modern, fast, and reliable end-to-end testing with built-in auto-waiting. Use Selenium if you require legacy browser support or a wider range of language bindings. Use CDP directly for low-level browser control, such as network interception or performance profiling.
  2. Install Dependencies: For Playwright, run npm init playwright@latest. For Selenium in Python, run pip install selenium and ensure you have the corresponding ChromeDriver version that matches your Chrome installation.
  3. Configure Chrome Extension Loading: Browser automation tools typically start a fresh profile. To automate an extension, you must load it during the browser launch phase. In Playwright, use the args array in launchPersistentContext to include --disable-extensions-except=/path/to/extension and --load-extension=/path/to/extension.
  4. Initialize the Browser Session: Write the startup script. Ensure you launch the browser in a non-headless mode if you need to see the extension's popup or interact with the browser UI, as many extensions do not function in headless mode.
  5. Target Extension Background Pages: Extensions often run background scripts. To interact with them, find the background page ID using CDP or the browser's internal chrome://extensions page. In Playwright, you can use browserContext.backgroundPages() to access these frames.
  6. Perform Browser Actions: Use the framework's API to interact with the DOM. For example, use page.click('.submit-button') in Playwright or driver.find_element(By.CSS_SELECTOR, '.submit-button').click() in Selenium to trigger actions.
  7. Implement CDP for Advanced Control: If standard APIs fail (e.g., for simulating geolocation or modifying network requests), connect to the CDP. In Playwright, use page.context().newCDPSession(page). You can then send raw commands like Network.emulateNetworkConditions to simulate slow connections.
  8. Handle Asynchronous Events: Web pages and extensions load dynamically. Use explicit waits (e.g., waitForSelector) rather than hard-coded sleep timers to ensure the element is interactable before the script attempts an action.
  9. Clean Up and Close: Always include a closing command browser.close() or driver.quit() to prevent zombie browser processes from consuming system memory.

Common Mistakes

  • Using Headless Mode: Many Chrome extensions do not load or function correctly in headless: true mode. Always test in headed mode first.
  • Incorrect Extension Paths: Providing a relative path to the extension folder often fails. Always use absolute paths to ensure the browser can locate the manifest file.
  • Ignoring Frame Contexts: Extension popups and iframes are separate documents. Trying to find an element in the main page context when it exists inside an extension popup will result in a "node not found" error.
  • Over-reliance on Sleep: Using time.sleep() or setTimeout() leads to flaky tests. Use event-based waiting.

Tips

  • Use Persistent Contexts: Instead of a fresh session, use a persistent user data directory. This allows the browser to remember extension settings and login states between runs.
  • Debug with Inspector: Launch the browser with the --remote-debugging-port=9222 flag. You can then open a separate Chrome window and navigate to localhost:9222 to inspect the automation session in real-time.
  • Optimize Selectors: Use data-attributes (e.g., [data-testid="submit"]) instead of volatile CSS classes that might change during a site update.
  • CDP for Network Mocking: Use CDP to block unnecessary resources (like ads or tracking scripts) to speed up the automation process.

Troubleshooting

If the browser fails to launch, check that your ChromeDriver version exactly matches your Chrome browser version. A mismatch is the most common cause of SessionNotCreatedException in Selenium.

If the extension is not loading, verify that the folder you are pointing to contains the manifest.json file directly in the root. If the manifest is in a subfolder, the extension will not load.

When elements are not clickable, check if they are inside a Shadow DOM. Standard CSS selectors cannot penetrate Shadow roots; you will need to use a JavaScript execution script via page.evaluate() to access these elements.

If the script hangs, check for unexpected alerts or modals that may have appeared. Use a global handler to dismiss alerts or set the browser's default alert handling strategy to "accept".

Frequently Asked Questions

Can I automate an extension installed from the Chrome Web Store?

It is difficult to automate store-installed extensions because their paths are managed by Chrome. It is much easier to download the extension source code and load it as an "unpacked" extension via the command line arguments.

What is the difference between Playwright and Selenium for extensions?

Playwright generally offers better native support for modern browser contexts and faster execution. Selenium is more mature and supports a wider variety of browsers beyond Chromium.

How do I interact with a Chrome extension popup?

Popups are transient. You must trigger the popup (e.g., by clicking the extension icon via CDP or a keyboard shortcut) and then locate the target window or frame that represents the popup's HTML.

Can CDP be used without Playwright or Selenium?

Yes, you can communicate with CDP using WebSockets directly. However, using a library like Playwright is recommended as it provides a high-level wrapper around the complex JSON-RPC messages required by CDP.

Will automation be detected by websites?

Yes, many sites detect the navigator.webdriver flag. To minimize this, you can use CDP to remove the webdriver property or use specialized stealth plugins that mask automation signatures.