如何通过编程获取Chrome模拟设备列表并提前校验设备有效性?
Hey there! Smart move pre-validating your target device names before kicking off automation tests—this saves you from messy runtime errors down the line. Let's walk through how to programmatically fetch the full list of emulated devices from Chrome's DevTools, so you can check if your config's device exists upfront.
Core Approach: Use Chrome DevTools Protocol (CDP)
Chrome exposes its DevTools functionality via the Chrome DevTools Protocol (CDP), and there's a specific method Emulation.getEmulatedDevices that returns the exact same list of devices you see in the "Device Toolbar" of Chrome DevTools. This is the most reliable way to get the official, up-to-date device list.
Example 1: Python (Selenium + CDP)
If you're using Selenium for your automation, you can directly execute CDP commands through the WebDriver instance.
First, install dependencies:
pip install selenium
Then the code:
from selenium import webdriver from selenium.webdriver.chrome.options import Options def fetch_chrome_emulated_devices(): # Configure Chrome options (headless mode is optional but useful for CI/CD) chrome_options = Options() chrome_options.add_argument("--headless=new") # Initialize Chrome driver driver = webdriver.Chrome(options=chrome_options) # Execute CDP command to get all emulated devices cdp_response = driver.execute_cdp_cmd("Emulation.getEmulatedDevices", {}) # Clean up the driver driver.quit() # Extract just the device names (or return full device objects if you need more data) device_names = [device["name"] for device in cdp_response["devices"]] return device_names # Usage: Validate your target device if __name__ == "__main__": all_devices = fetch_chrome_emulated_devices() target_device = "iPhone 14" if target_device in all_devices: print(f"✅ Success: '{target_device}' is a valid Chrome emulated device!") else: print(f"❌ Error: '{target_device}' not found.") print(f"Sample available devices: {', '.join(all_devices[:5])}...")
Example 2: JavaScript (Puppeteer)
For Node.js/Puppeteer-based automation, you can use Puppeteer's built-in CDP session support.
First, install dependencies:
npm install puppeteer
Then the code:
const puppeteer = require('puppeteer'); async function fetchChromeEmulatedDevices() { // Launch Chrome (headless mode optional) const browser = await puppeteer.launch({ headless: 'new' }); const page = await browser.newPage(); // Create a CDP session and fetch devices const cdpSession = await page.target().createCDPSession(); const { devices } = await cdpSession.send('Emulation.getEmulatedDevices'); // Clean up await browser.close(); // Extract device names (or keep full device objects for extra metadata) const deviceNames = devices.map(device => device.name); return deviceNames; } // Usage: Validate your target device (async () => { const allDevices = await fetchChromeEmulatedDevices(); const targetDevice = "Pixel 7"; if (allDevices.includes(targetDevice)) { console.log(`✅ Success: '${targetDevice}' is a valid Chrome emulated device!`); } else { console.log(`❌ Error: '${targetDevice}' not found.`); console.log(`Sample available devices: ${allDevices.slice(0,5).join(', ')}...`); } })();
Extra Notes
- Full Device Data: The
devicesarray from the CDP response includes more than just names—you can accesswidth,height,deviceScaleFactor,userAgent, andtouchsupport status if you need that for your tests. - Version Compatibility: Make sure your Chrome version matches the version of Selenium/Puppeteer you're using. CDP methods can change between Chrome versions, so sticking to compatible versions avoids unexpected issues.
- Custom Devices: If you've added custom emulated devices to Chrome, this method will return those too—perfect for validating custom configurations as well.
内容的提问来源于stack exchange,提问作者Raj

