How do you execute javascript element using PageObjects and @FindBy in java selenium

Viewed 709

I am creating page objects for navigating through a site and refactoring hashed together Java project. I have a piece of code which invokes a JavaScript button. However, I can't work out how to set this up to be used in page object format with @FindBy

Current page object is:

public CustomerLogin(WebDriver driver) {
        PageFactory.initElements(driver, this);
    }


    @FindBy(how = How.ID, using = "username")
    private WebElement userName;

    @FindBy(how = How.ID, using = "password")
    private WebElement password;

    @FindBy(how = How.XPATH, using = "//*[@id=\\\"loginPage\\\"]/div[2]/div/div/div[1]/form/div[3]/div/input[1]")
    private WebElement login;

    public void logIn(String userName, String password) {
        this.userName.sendKeys(userName);
        this.password.sendKeys(password);

}}

The part that I can't get in is:

WebElement element = webDriver.findElement(By.xpath("//*@id=\"loginPage\"]/div[2]/div/div/div[1]/form/div[3]/div/input[1]"));

JavascriptExecutor executor = (JavascriptExecutor) webDriver;
executor.executeScript("arguments[0].click();", element);

This works if I put it in the test script but can't work out how to convert that into a page object version.

1 Answers

Initialize the Javascript Executor in the constructor

    public class CustomerLogin{

    WebDriver driver;
    JavascriptExecutor executor;


    public CustomerLogin(WebDriver driver) {
        this.driver = driver;
        this.executor = (JavascriptExecutor) this.driver;
        PageFactory.initElements(driver, this);
        }

    @FindBy(xpath = "//*@id=\"loginPage\"]/div[2]/div/div/div[1]/form/div[3]/div/input[1]")
    private WebElement loginButton

    //method, for clicking loginButton  with JS Executor
    public void clickLoginButton() {
        executor.executeScript("arguments[0].click();", loginButton);
    }
}
Related