Javascript Executor with PageFactory Selenium

Photo by Antonio Batiniu0107 on Pexels.com

Hello guys,

Today I am going to post another problem that cost me a lot of research time and pulling out my own hair.

This was the initial code:

    public void javascriptExecutor(String script, WebElement element) {
       WebDriver driver = new ChromeDriver();  
       JavascriptExecutor jse = (JavascriptExecutor) driver;  
       jse.executeScript(script, element);  
    }

If you ever encounter the error complaining Selenium couldn’t find the Webdriver instance, then check the complete explanation of the problem here.

TL;DR; Webdriver when using PageFactory needs to extract the underlying WebElement with WrapsElement and then the WebDriver from it. Basically, you need to get the real element and then you will be able to use javascript executor:

    public void javascriptExecutor(String script, WebElement element) {  
       WebDriver driver = ((WrapsDriver)((WrapsElement)element).getWrappedElement()).getWrappedDriver();
       JavascriptExecutor jse = (JavascriptExecutor) driver;  
       jse.executeScript(script, element);  
    }

So, next time this problem comes up it will be smooth to fix and not days of trying to figure out what is happening 😂