workspace workspace - 4 months ago 25
Java Question

How to check if a text is highlighted on the page using Selenium?

1> What does highlighted text means?
Suppose you browse any page , select any text on that page using mouse or some other means. Let say "Hello" , "Sign Up "text is highlighted. Please correct my understanding if its wrong.

2> I tried the below code to get CssValue of color and background-color.
Using the given code:

String textColor = driver.findElement(By.xpath("//*[@id='pageFooter']/div[3]/div/span")).getCssValue("color");
String bkgColor = driver.findElement(By.xpath("//*[@id='pageFooter']/div[3]/div/span")).getCssValue("background-color");
System.out.println("TextColor : " + textColor );
System.out.println("Background Color : " + bkgColor);


TextColor : rgba(115, 115, 115, 1)
Background Color : transparent

*TextColor gives the color of text.

** For highlighting i am using Robot class to send Ctrl+A , though its selecting entire page, but it should output some different value. In that case also it's giving the text color only as above output.

Please let me know if i am doing right or is my understanding about highlighted text is correct.


You cannot do it with Selenium by itself, but you can do it executing javascript with Selenium. Js is pretty simple:


enter image description here

So just:

((JavascriptExecutor)driver).executeScript("return window.getSelection().toString();");

PS will not work in <=IE8 (will provide how if you'll need)