How do I enter text in textfield with onkeyup/onfocus javascript?

后端 未结 1 552
一向
一向 2021-01-24 18:28

We have a web application that I am trying to automate testing for, using Java, Web Driver and TestNG. The biggest challenge I\'m facing (failing at) is to stay ahead of develop

相关标签:
1条回答
  • 2021-01-24 19:11

    And I found the answer after a day of digging.

    To enter text in text-fields with an onfocus Javascript, I need to click() the text-field webelement:

    driver.findElement(By.id("my_budget")).click();
    

    This worked - the Javascript executed upon entering the value.

    To make entering text + generating events a little easier, I have created a method:

    To call this:

    sendKeysWithEvent(driver, driver.findElement(By.id("my_budget")), "50000", "onfocus");
    

    Methods:

    public static void sendKeysWithEvent(WebDriver driver, WebElement element, String text, String event) throws Exception {
        element.sendKeys(text);
        switch(event) {
        case "keyup":
            new Actions(driver).keyDown(element, Keys.CONTROL).keyUp(element, Keys.CONTROL).perform();
            break;
        case "onblurJS":
            doJavascriptOnElement(driver, element, element.getAttribute("onblur"));
            break;
        case "onfocus":
            element.click();
            break;
        case "keyupJS": 
            doJavascriptOnElement(driver, element, element.getAttribute("onkeyup"));
            break;
        case "keyupTAB":
            element.sendKeys(Keys.TAB);
            break;
        }
    
    }
    public static void doJavascriptOnElement(WebDriver driver, WebElement element, String javascript) throws Exception {
        ApiHelper.doLog("Running Javascript: " + javascript);
        ((JavascriptExecutor) driver).executeScript(javascript, element);
    
    }
    
    0 讨论(0)
提交回复
热议问题