如何在 Ruby 编写的 Webdriver 测试中执行 JavaScript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7565562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to execute JavaScript in Ruby written Webdriver test?
提问by Yulia
Is there a known solution to perform Eval (Javascript execution) in Webdriver, Ruby bindings?
是否有在 Webdriver、Ruby 绑定中执行 Eval(Javascript 执行)的已知解决方案?
The equivalent of the following example in Java.
等效于以下 Java 示例。
WebElement element = driver.findElement(By.id( "foo" ));
String name = (String) ((JavascriptExecutor) driver).executeScript(
"return arguments[0].tagName" , element)
回答by jarib
The equivalent Ruby would be:
等效的 Ruby 将是:
name = driver.execute_script("return arguments[0].tagName" , element)
(to get the tag name you could also just call element.tag_name)
(要获取标签名称,您也可以调用 element.tag_name)
回答by eyumay
Thank you for posting this answer. It helped me a lot. I was googling the whole day to figure out how to execute JavaScript code within Ruby.
感谢您发布此答案。这对我帮助很大。我在谷歌上搜索了一整天,想弄清楚如何在 Ruby 中执行 JavaScript 代码。
@driver.execute_script("arguments[0].scrollIntoView(true);", element )
@driver.execute_script("arguments[0].scrollIntoView(true);", element )
By doing so, I was able to scroll into the specific element before click event. This might help others a bit.
通过这样做,我能够在单击事件之前滚动到特定元素。这可能对其他人有所帮助。
I had to use JavaScript alternative because for some reason this wasn't: working for me element.location_once_scrolled_into_view
我不得不使用 JavaScript 替代方案,因为出于某种原因,这不是:对我来说有效 element.location_once_scrolled_into_view
Thanks.
谢谢。