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

Java移动端测试如何切换横竖屏?DesiredCapabilities配置无效怎么解决

问题根因
  • Chrome移动模拟模式下,rotatable、deviceOrientation这两个配置不会读取DesiredCapabilities的顶层参数,必须放到mobileEmulation实验配置项内部才会生效
  • 最新版本Selenium已经不推荐直接使用DesiredCapabilities后再merge到ChromeOptions的写法,所有配置优先直接写到ChromeOptions中
启动时固定横竖屏的正确代码
Map<String, Object> mobileEmulator = new HashMap<>();
mobileEmulator.put("deviceName", deviceName);
// orientationMode可传入"portrait"(竖屏)或"landscape"(横屏)
mobileEmulator.put("deviceOrientation", orientationMode);

WebDriverManager.chromedriver().setup();

ChromeOptions chromeOption = new ChromeOptions();
chromeOption.setPageLoadStrategy(PageLoadStrategy.NONE);
chromeOption.setExperimentalOption("mobileEmulation", mobileEmulator);

// 无需额外定义DesiredCapabilities,直接传ChromeOptions即可
driver = new ChromeDriver(chromeOption);
运行时动态切换横竖屏的实现

如果需要在测试执行过程中切换横竖屏,可通过Chrome DevTools协议实现:

// 切换为横屏示例
Map<String, Object> params = new HashMap<>();
params.put("width", 1920);
params.put("height", 1080);
params.put("deviceScaleFactor", 100);
params.put("mobile", true);
params.put("screenOrientation", Map.of(
    "type", "landscapePrimary",
    "angle", 90
));
((ChromeDriver) driver).executeCdpCommand("Emulation.setDeviceMetricsOverride", params);

// 切换为竖屏示例
params.put("width", 1080);
params.put("height", 1920);
params.put("screenOrientation", Map.of(
    "type", "portraitPrimary",
    "angle", 0
));
((ChromeDriver) driver).executeCdpCommand("Emulation.setDeviceMetricsOverride", params);
注意事项
  • 确认orientationMode的取值拼写正确,必须是全小写的portrait或landscape
  • 如果你使用的是真机测试而非Chrome自带的移动端模拟功能,需要接入Appium对应的横竖屏切换API,ChromeDriver仅支持自身模拟的设备配置修改

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 18:36:04