Saturday, April 18, 2020

Added Text in label using JavascriptExecutor in Selenium WebDriver

Here we will discuss how we can put some text in html field. It is require to add some data within html field.

Steps: 1 

                JavascriptExecutor executor = (JavascriptExecutor)driver;

 Steps: 2

            executor.executeScript("arguments[0].innerHTML = '" + text +"';", element);

Here we set the innerHTML value and added some extra text.


public static void addText(WebElement element, String text) {
        try
        {
            JavascriptExecutor executor = (JavascriptExecutor)driver;
            executor.executeScript("arguments[0].innerHTML = '" + text +"';", element);
        }
        catch (Exception e)
        {
            log.error("Couldnot able to send text on element: " + element);
            throw e;
        }
    }

Remove Readonly attribute using JavascriptExecutor in Selenium WebDriver

   
In automation we need to type some value in readonly field. Though we should not do that for proper validation but to achieving some goal or to reducing the line of code or may be to be over sure those steps will never fail.


It can be achieved using the following line

Steps: 1
             JavascriptExecutor executor = (JavascriptExecutor)driver;

Step: 2
            executor.executeScript("arguments[0].removeAttribute('readonly',0);", element); 

Here we are using removeAttribute('readonly',0) method to remove the attribute from html element


We are trying to make our element editable so 'readonly' field removed from here.

Second parameter of removeAttribute method of java script is optional we are mentioning it as '0' here for non case sensitive search, meaning of the different values are described below.

0      It is the default value and performs the non case sensitive search
1      It performs the case sensitive property search
2      It returns the property value as it is set in the script or html code

public static void removeReadOnly(WebElement element) {
        try
        {
            JavascriptExecutor executor = (JavascriptExecutor)driver;
            executor.executeScript("arguments[0].removeAttribute('readonly',0);", element);
        }
        catch (Exception e)
        {
            log.error("Couldnot able to remove readonly from element: " + element);
            throw e;
        }
    }