简体   繁体   English

如何使onFocus()与Selenium一起触发

[英]How to get onFocus() to fire with Selenium

I'm trying to test an HTML form using Selenium. 我正在尝试使用Selenium测试HTML表单。 The page authenticates the input data by using javascript's onFocus() event on each text field (which is an input tag in HTML ). 该页面通过在每个文本字段(这是HTML的输入标记onFocus()上使用javascript的onFocus()事件来对输入数据进行身份验证。 As such, my code needs to make sure onFocus() get fired whenever I interact with the text field, just as it would if a real user were filling out the form. 这样,我的代码需要确保在我与文本字段进行交互时onFocus() ,就像真实用户在填写表单时一样。

I would expect the following code to fire this event: 我希望以下代码会触发此事件:

this.textfield.clear();
if (value != null) {
    this.textfield.sendKeys(value);
}

However, the onFocus() event doesn't fire. 但是, onFocus()事件不会触发。 I've tried manually clicking the element 我尝试手动单击元素

this.textfield.click()

But that also doesn't work. 但这也不起作用。 I've also tried using the Actions Class 我也尝试过使用动作类

this.textfield.clear();
Actions action = new Actions(driver);
action.moveToElement(this.textfield).click().sendKeys(value.toString()).perform();

But this too hasn't given me any luck. 但这也没有给我任何运气。

Is there any way in Selenium to ensure that the onFocus() event is executed? Selenium中有什么方法可以确保执行onFocus()事件?

You can execute JavaScript in your browser session to explicitly fire onFocus(). 您可以在浏览器会话中执行JavaScript以显式触发onFocus()。 This code is in C#, but there must be something similar in Java bindings too. 这段代码在C#中,但是Java绑定中也必须有类似的东西。

((IJavaScriptExecutor)driver).ExecuteScript(string.Format("$('#{0}').onFocus()", elementId));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM