9

I want have a text that is copied to the clipboard and would want to paste that into a text field.

Can someone please let me know how to do that

for ex:-

driver.get("https://mail.google.com/");

driver.get("https://www.guerrillamail.com/");
driver.manage().window().maximize();
driver.findElement(By.id("copy_to_clip")).click(); -->copied to clipboard
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.id("nav-item-compose")).click(); 

driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElement(By.name("to")).???;//i have to paste my text here that is copied from above
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Ashvitha
  • 5,836
  • 6
  • 18
  • 18
  • Did you google pasting from clipboard using Java? Seems pretty straightforward... what code have you tried and what was the result? – JeffC Nov 07 '16 at 14:31

7 Answers7

6

If clicking in the button with id 'copy_to_clip' really copies the content to clipboard then you may use keyboard shortcut option. I think, you might have not tried with simulating CTRL + v combination. Activate your destination text field by clicking on it and then use your shortcut. This may help.

Code Snippets:

driver.findElement(By.name("to")).click(); // Set focus on target element by clicking on it

//now paste your content from clipboard
Actions actions = new Actions(driver);
actions.sendKeys(Keys.chord(Keys.LEFT_CONTROL, "v")).build().perform();
optimistic_creeper
  • 2,739
  • 3
  • 23
  • 37
  • how do i perform the action on the element. for eg:- i have to paste the copied text into a field with name "to" – Ashvitha Nov 07 '16 at 17:34
  • Thank you so much. I have another ques too. 1) Copying by clicking on the button is for some reason not working, so I am trying to do it via the action builder as follows actions.contextClick(copy).sendKeys(Keys.chord(Keys.COMMAND, "c")).build().perform(); (Note:-copy-is my element name and 'command' as i am using a MAC) but this is not working. can you please help me here @optimist_creeper – Ashvitha Nov 07 '16 at 19:39
6

As per your question as you are already having some text within the clipboard to paste that into a text field you can use the getDefaultToolkit() method and you can use the following solution:

//required imports
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
//other lines of code
driver.findElement(By.id("copy_to_clip")).click(); //text copied to clipboard
String myText = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor); // extracting the text that was copied to the clipboard
driver.findElement(By.name("to")).sendKeys(myText);//passing the extracted text to the text field
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • After the click on one of the files, window popup will open and we need to provide the path of file location. how can i do this? for copy I've below code: Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); StringSelection str = new StringSelection(path); Thread.sleep(2000); clipboard.setContents(str, null); Can someone help me how can perform Contrl+V on window popup ? – Lokesh Reddy Jan 06 '23 at 12:12
  • @LokeshReddy Feel free to raise a new question as per your new requirement. – undetected Selenium Jan 10 '23 at 23:01
  • If I run this in remote desktop, it doesn't work. – Meghana Jul 12 '23 at 19:40
2

I came up with this to test pasting using the clipboard API. A big part of the problem was permissions that as of 12/2020 need to be kinda hacked in:

// Setup web driver
ChromeOptions options = new ChromeOptions();

Map<String, Object> prefs = new HashMap<>();
Map<String, Object> profile = new HashMap<>();
Map<String, Object> contentSettings = new HashMap<>();
Map<String, Object> exceptions = new HashMap<>();
Map<String, Object> clipboard = new HashMap<>();
Map<String, Object> domain = new HashMap<>();

// Enable clipboard permissions
domain.put("expiration", 0);
domain.put("last_modified", System.currentTimeMillis());
domain.put("model", 0);
domain.put("setting", 1);
clipboard.put("https://google.com,*", domain);      //   <- Replace with test domain
exceptions.put("clipboard", clipboard);
contentSettings.put("exceptions", exceptions);
profile.put("content_settings", contentSettings);
prefs.put("profile", profile);
options.setExperimentalOption("prefs", prefs);

// [...]
driver.executeScript("navigator.clipboard.writeText('sample text');");

pasteButton.click();

Javascript in running in browser:

// Button handler
navigator.clipboard.readText().then(t-> console.log("pasted text: " + t));

Though if you ever spawn another window or that window loses focus, you'll get a practically-silent JavaScript error:

// JS console in browser
"DOMException: Document is not focused."

// error thrown in promise
{name: "NotAllowedError", message: "Document is not focused."}

So we need to figure out some way to bring the window into focus. We also need to prevent any other test code from interfeering with the clipboard while we are using it, so I created a Reentrant Lock.

I'm using this code to update the clipboard:

Test code:

try {
    Browser.clipboardLock.lock();
    b.updateClipboard("Sample text");
    b.sendPaste();
}finally {
    Browser.clipboardLock.unlock();
}

Browser Class:

public static ReentrantLock clipboardLock = new ReentrantLock();

public void updateClipboard(String newClipboardValue) throws InterruptedException {
    if (!clipboardLock.isHeldByCurrentThread())
        throw new IllegalStateException("Must own clipboardLock to update clipboard");
    
    for (int i = 0; i < 20; i++) {
        webDriver.executeScript("" +
                "window.clipboardWritten = null;" +
                "window.clipboardWrittenError = null;" +
                "window.textToWrite=`" + newClipboardValue + "`;" +
                "navigator.clipboard.writeText(window.textToWrite)" +
                "   .then(()=>window.clipboardWritten=window.textToWrite)" +
                "   .catch(r=>window.clipboardWrittenError=r)" +
                ";"
        );
        
        while (!newClipboardValue.equals(webDriver.executeScript("return window.clipboardWritten;"))) {
            Object error = webDriver.executeScript("return window.clipboardWrittenError;");
            if (error != null) {
                String message = error.toString();
                try {
                    message = ((Map) error).get("name") + ": " + ((Map) error).get("message");
                } catch (Exception ex) {
                    log.debug("Could not get JS error string", ex);
                }
                if (message.equals("NotAllowedError: Document is not focused.")) {
                    webDriver.switchTo().window(webDriver.getWindowHandle());
                    break;
                } else {
                    throw new IllegalStateException("Clipboard could not be written: " + message);
                }
            }
            Thread.sleep(50);
        }
    }
}
Charlie
  • 8,530
  • 2
  • 55
  • 53
1

Pyperclip works great for getting text copied to the clipboard - https://pypi.org/project/pyperclip/

Once you have some text copied to the clipboard, use pyperclip.paste() to retrieve it.

kashgo
  • 141
  • 1
  • 6
0
This worked well for me when pasting emoji into a text box

    import java.awt.Toolkit;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.StringSelection;

    String emoji="☺️❤️";
    StringSelection stringSelection = new StringSelection(emoji);
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(stringSelection, null);
    WebElement input = your_driver.findElementByXPath(your_xpath);
    input.sendKeys(Keys.SHIFT, Keys.INSERT);
JackhammersForWeeks
  • 955
  • 1
  • 9
  • 21
0

The easiest way to do this using below code I derived from http://www.avajava.com/tutorials/lessons/how-do-i-get-a-string-from-the-clipboard.html

  private void copiedTextVerification() throws IOException, UnsupportedFlavorException {

        //Verify that text is copied when clicked on lnk_Copy_Permalink and stays on clipboard and not empty.
        driver.findElement(By.id("button_To_copy_Text")).click();
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Clipboard clipboard = toolkit.getSystemClipboard();
        String actualCopedText = (String) clipboard.getData(DataFlavor.stringFlavor);
        System.out.println("String from Clipboard:" + actualCopedText);
        //Assert the copied text contains the expected text.
        Assert.assertTrue(actualCopedText.startsWith("Expected Copied Text"));
        //Send the copied text to an element.
        driver.findElement(By.id("button_To_send_Text")).sendKeys(actualCopedText);

    }
Sameera De Silva
  • 1,722
  • 1
  • 22
  • 41
0

using System.Text; using System.Text.RegularExpressions;

Negut: TextCopy

public string GetClipboardText()
{
    var text = new TextCopy.Clipboard().GetText();
    return text;
}
danronmoon
  • 3,814
  • 5
  • 34
  • 56
Sam
  • 1
  • 1
  • am using this and it works perfectly to copy form clipboard to return me a string then use is for comparison or whatever. C# – Sam Jan 28 '22 at 20:48