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

Selenium 4.10.0切换子标签后操作元素抛出TypeError: JSON.stringify异常

问题

使用Java + Selenium 4.10.0做自动化测试,当前页面有两个标签页(父标签主页、子标签页),通过代码切换到子标签页时无异常,但在子窗口执行元素操作(如点击按钮)时抛出异常:TypeError: JSON.stringify is not a function

代码片段

//Loop through until we find a new window handle
for (String windowHandle : driver.getWindowHandles()) {
    
    if(!originalWindow.contentEquals(windowHandle)) {
        System.out.println("Child win : "+windowHandle);
        driver.switchTo().window(windowHandle);
        break;
    }
}
driver.findElement(By.name("aspnetForm")).click();

控制台日志

Child win : DEFC56C2E255CB00E7CF1C779B81E7EE
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Runtime.callFunctionOn threw exception: TypeError: JSON.stringify is not a function
at buildError (:323:18)
(Session info: chrome=114.0.5735.199)
Build info: version: '4.10.0', revision: 'c14d967899'
System info: os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '11.0.18'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Command: [748156ce82a3898c61c8bc461a5ecbbb, findElement {using=name, value=aspnetForm}]
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 114.0.5735.199, chrome: {chromedriverVersion: 114.0.5735.90 (386bc09e8f4f..., userDataDir: C:\Users\baluz\AppData\Loca...}, goog:chromeOptions: {debuggerAddress: localhost:58574}, networkConnectionEnabled: false, pageLoadStrategy: normal, platformName: windows, proxy: Proxy(), se:cdp: ws://localhost:58574/devtoo..., se:cdpVersion: 114.0.5735.199, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:extension:minPinLength: true, webauthn:extension:prf: true, webauthn:virtualAuthenticators: true}
Session ID: 748156ce82a3898c61c8bc461a5ecbbb
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:199)
at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:132)
at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:51)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:191)
at org.openqa.selenium.remote.service.DriverCommandExecutor.invokeExecute(DriverCommandExecutor.java:196)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:171)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:531)
at org.openqa.selenium.remote.ElementLocation$ElementFinder$2.findElement(ElementLocation.java:165)
at org.openqa.selenium.remote.ElementLocation.findElement(ElementLocation.java:66)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:350)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:344)
at com.basePage.EX3.main(EX3.java:91)

原因分析与解决方案

核心原因

  • 子页面未完全加载:切换窗口后立即执行操作,子页面的JavaScript环境还未初始化完成,原生的JSON.stringify方法未就绪,导致Selenium调用时出错。
  • 页面JS环境被篡改:部分网站会重写或覆盖全局JSON对象,导致原生方法丢失,引发该异常。

解决步骤

  1. 添加显式等待
    切换到子窗口后,等待目标元素可点击,确保页面DOM和JS环境加载完成:
// 切换到子窗口后
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// 等待目标元素可点击后再执行操作
wait.until(ExpectedConditions.elementToBeClickable(By.name("aspnetForm"))).click();
  1. 修复页面JS环境
    如果显式等待无效,说明页面JS环境存在问题,可通过Selenium注入脚本恢复JSON对象:
// 切换窗口后先执行脚本修复JSON环境
driver.executeScript("window.JSON = window.JSON || {}; window.JSON.stringify = window.JSON.stringify || function(obj){return JSON.stringify ? JSON.stringify(obj) : obj.toString();}");
// 再执行元素操作
driver.findElement(By.name("aspnetForm")).click();
  1. 优化窗口切换逻辑
    确保切换到的是目标子窗口,避免误切换:
Set<String> allWindows = driver.getWindowHandles();
allWindows.remove(originalWindow);
// 若只有一个新窗口,直接切换
if(allWindows.size() == 1) {
    driver.switchTo().window(allWindows.iterator().next());
}

内容的提问来源于stack exchange,提问作者Balaji Singh .Y

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 23:54:54