0

I have a webpage with a "Copy Link" button, clicking on it copies some data from the text box. Also, these selenium tests will run on Linux machines (headless mode). I used awt Toolkit api and it failed with below stack trace because its running in Linux headless mode. Toolkit doesn't seen to be supported in Linux mode

Test Failed: {}[class: tests.AMUSanityTests, method: test, exception: java.awt.HeadlessException, message: 'No X11 DISPLAY variable was set, but this program performed an operation which requires it.', stack trace: 
sun.awt.HeadlessToolkit.getSystemClipboard(HeadlessToolkit.java:309)

I also tried using selenium sendKeys but this is a void method and hence i cannot fetch the content. There is no place on the webpage for me to paste the content and again copy it for verification.

I need a way to extract the copied content for verification purposes.

Does someone have a solution on how this can be achieved?

Thank you.

Vrushank Doshi
  • 2,428
  • 5
  • 20
  • 34

1 Answers1

0

I wrote a small class that does it in a way:

public class ClipboardUtil {

    public static String fetchClipboardContents() throws IOException {
        String contents = "";
        String command = "xclip --clipboard -o";
        Process process = Runtime.getRuntime().exec(command);
        try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            contents = br.readLine();
        }
        return contents;
    }

}

The static method executes a linux command xclip --clipboard -o, which outputs the clipboard's contents to the terminal. Java takes the output and returns it as a string.

You could execute some other command in linux that would get you the desired output and the java code should remain the same.

INFO:

I used Ubuntu to write this code. The example command returns the copied content or the currently selected content. Using a different linux command is a good idea.

Ivan Dimitrov
  • 332
  • 1
  • 10
  • Running this linux command throws following error on the terminal Error: Can't open display: (null) – Vrushank Doshi Nov 05 '20 at 18:34
  • One could find a different command that gets the job done, or write a custom shell script if everything else fails. If you could output your clipboard contents to the terminal, you could get the same info in java. – Ivan Dimitrov Nov 05 '20 at 19:34
  • @IvanDimitrov Are you sure this works in _headless_ mode? – RedYeti Dec 22 '22 at 11:10
  • @RedYeti Check this answer out: https://askubuntu.com/questions/305654/xclip-on-headless-server This explains the xclip stuff on headless servers. xclip is a utility that works as a terminal clipboard, which this java code runs. You need an x server running anyway. Let me know if this helps. – Ivan Dimitrov Jan 23 '23 at 13:35
  • @IvanDimitrov Thanks! Not sure if that works without having an X-server though. – RedYeti Jan 25 '23 at 09:13