'How to get the text of a popup notification using selenium java that disappears within 2 or 3 seconds

I am getting a pop up notification on a button click. PFA example

I need to get text of notification which is same as the image given. The issue is, I can't able to get the text using .getText() or any other related methods as this pop will appear after 2 or 3 seconds(Which may vary) and disappears in next 2 seconds.

If I use implicit wait, it fails because the popup will be disappeared before getting the text. If I don't use wait, it still fails as the getText() methods will be executed before the popup comes on UI.



Solution 1:[1]

Unconventional approach: decleare an empty String variable, make a while loop that will try to get the text, all of this inside a try - catch block. The catch block shall remain empty, its only purpose is to manage element not found (since the popup can disappear)

public static void t() {
        try {
            String text = "";
            while (text.isBlank())
                text = driver.findElement(By.xpath("xpath")).getText();
        } catch (Exception e) {
            // do nothing
        }

    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CCC