Selenium执行多参数脚本函数报错:ReferenceError: coords未定义
解决Selenium执行JS脚本时的ReferenceError: coords is not defined问题
你遇到的核心问题是Selenium的executeScript方法运行在独立的JavaScript上下文,导致你直接使用的this.activeCoords无法被正确识别——这里的this并不是页面中原本调用setNewCellType函数时的组件/实例上下文,所以抛出了"coords is not defined"的错误。
具体解决步骤:
1. 先获取activeCoords对象再传入
因为this.activeCoords在Selenium的执行上下文里无法直接访问,你可以先通过JS获取到这个对象,再作为参数传递给目标函数:
// 第一步:先从页面上下文获取activeCoords的值 Object activeCoords = ((JavascriptExecutor) driver).executeScript("return this.activeCoords;"); // 第二步:调用setNewCellType,用arguments[0]接收传入的activeCoords if (driver instanceof JavascriptExecutor) { ((JavascriptExecutor) driver) .executeScript("setNewCellType(new ZmianaTypuCommandFactory(), currentRozdzial, currentTable, arguments[0]);", activeCoords); }
注意:如果
this在页面中不是全局上下文(比如是某个组件实例的this),你需要调整获取语句,比如找到对应的组件实例:Object activeCoords = ((JavascriptExecutor) driver).executeScript("return window.yourComponentInstance.activeCoords;");你可以先在浏览器开发者工具的控制台里测试
return this.activeCoords或者对应的实例引用,确认能拿到正确的坐标对象后再放到Selenium代码里。
2. 确保其他变量的可访问性
如果currentRozdzial和currentTable也不是全局变量,而是属于某个上下文的属性,你需要用同样的方式先获取它们的值,再传入函数:
Object currentRozdzial = ((JavascriptExecutor) driver).executeScript("return currentRozdzial;"); Object currentTable = ((JavascriptExecutor) driver).executeScript("return currentTable;"); Object activeCoords = ((JavascriptExecutor) driver).executeScript("return this.activeCoords;"); ((JavascriptExecutor) driver) .executeScript("setNewCellType(new ZmianaTypuCommandFactory(), arguments[0], arguments[1], arguments[2]);", currentRozdzial, currentTable, activeCoords);
3. 匹配页面实际的调用参数
从你提供的信息看,页面实际调用setNewCellType时还传入了params参数,而函数定义里还有newState和mode可选参数。如果你的业务需要这些参数,也要补充进去,避免后续出现参数缺失的错误。
调试小技巧
- 先在浏览器控制台里完整模拟调用
setNewCellType,确认能正常执行后,再把对应的代码迁移到Selenium的executeScript中。 - 如果不确定变量的上下文,可以在控制台用
console.log()打印变量,比如console.log(this.activeCoords)、console.log(currentRozdzial),确认它们的存在和值。
内容的提问来源于stack exchange,提问作者Podolanka
相关产品推荐
相关产品推荐

