Saturday, April 18, 2020

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;
        }
    }

No comments:

Post a Comment