如何验证 dir="auto" 自动识别方向?
解读
国内大型 Web 项目普遍需要兼容 阿拉伯语、希伯来语、维吾尔语 等 RTL 语言,同时又要保证中文、英文等 LTR 内容正常显示。
dir="auto" 是 HTML5 提供的“让浏览器自己判断方向”的标准写法,但浏览器并不会在 DOM 属性里把最终方向回写给你,因此 Selenium 无法像断言 class 那样直接取值。
面试官真正想考察的是:
- 你是否知道“方向”是渲染层概念,而不是 DOM 属性;
- 能否用 Selenium 拿到计算后样式或几何位置来做断言;
- 是否能在中文环境下构造 RTL 与 LTR 边界场景 并自动化验证。
知识点
- dir="auto" 算法:节点首个强方向字符(Strong Directional Character)决定整段方向;若不含,则继承父节点。
- Selenium 获取计算后样式:
((JavascriptExecutor)driver).executeScript("return window.getComputedStyle(arguments[0]).direction;", element),返回"ltr"或"rtl"。 - 国内主流浏览器内核:Chrome 122+、Edge 122+、Firefox 115 ESR 均支持该算法;**360 安全浏览器(极速内核)**与 Chrome 表现一致,可放心使用。
- CI 集成:在 Jenkins + TestNG 的并行管道里,用 Selenium Grid 4 同时拉起
chrome:latest与firefox:latest节点,可一次性验证两种内核。
答案
步骤 1:构造最小可重复页面
<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"></head>
<body>
<p id="lrtText" dir="auto">Hello 世界</p>
<p id="rtlText" dir="auto">مرحبا بالعالم</p>
</body>
</html>
步骤 2:用 Selenium 读取计算后方向
WebElement ltr = driver.findElement(By.id("lrtText"));
WebElement rtl = driver.findElement(By.id("rtlText"));
JavascriptExecutor js = (JavascriptExecutor) driver;
String ltrDir = (String) js.executeScript(
"return window.getComputedStyle(arguments[0]).direction;", ltr);
String rtlDir = (String) js.executeScript(
"return window.getComputedStyle(arguments[0]).direction;", rtl);
Assert.assertEquals(ltrDir, "ltr", "中文+英文应被判定为 LTR");
Assert.assertEquals(rtlDir, "rtl", "阿拉伯语应被判定为 RTL");
步骤 3:接入国内持续集成
将上述用例打包为 TestNG 测试类,通过 Maven Surefire 插件在 Jenkins 中触发;Grid 节点镜像使用 selenium/node-chrome:122-zh(官方已内置中文语言包),保证控制台日志可读。
拓展思考
- 如果产品需求要求 “混合文本方向分段显示”,
dir="auto"已无法满足,需要前端改用 Unicode 方向控制符(LRE、RLE、PDF)或 CSSunicode-bidi: plaintext;此时 Selenium 断言策略应改为 逐字符扫描 bounding rect,验证右侧对齐与左侧对齐交替出现。 - 在 微信小程序 WebView 中,X5 内核 8.3.19 以下版本对
dir="auto"支持不完整,需在 capabilities 里加"x5QueueEnabled": true并降级使用 TBS 调试内核;面试时可作为“国内兼容坑”亮点抛出。 - 若页面通过 Shadow DOM 封装组件,上述
window.getComputedStyle会失败,需先getShadowRoot()再执行脚本;可进一步展示你对 Selenium 4.8+ shadow root API 的掌握。