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

14,328

Solution 1

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

window.getSelection().toString();

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)

Solution 2

The CSS style of the element with the selected text would not change after you select it's text in the browser. What you can do is to get the current "active" element and see if it is the desired one:

WebElement desiredElement = driver.findElement(By.xpath("//*[@id='pageFooter']/div[3]/div/span"));
WebElement activeElement = driver.switchTo().activeElement();
Share:
14,328
workspace
Author by

workspace

Find me here @ http://qahumor.blogspot.com &amp; Subscribe my youtube channel @ https://www.youtube.com/channel/UCEUDm1ZxsX6teks8wM71bmQ/

Updated on June 26, 2022

Comments

  • workspace
    workspace almost 2 years

    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:

        driver.get("https://facebook.com");
        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);
    

    output:-

    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.