Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paste text from clipboard through selenium-webdriver and Java?

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
like image 478
Ashvitha Avatar asked Nov 07 '16 07:11

Ashvitha


People also ask

How to get clipboard content in selenium?

Get Clipboards content in Java : While performing automation in Selenium we need to access Systems clipboard to copy something and again fetching data from Systems Clipboard. Java provides many Classes to do it.Clipboard Class is also one of them.We can access the clipboards content directly by accessing this class.

How to simulate copy paste action in Selenium WebDriver?

This can be done using Clipboard class — Simulates copy paste action. //Use Robot class instance to simulate CTRL+C and CTRL+V key events : Basically this is quite helpful to handle window events those can not be handled by Selenium WebDriver. Appium with iOS 8 and XCode 6 : What’s new?

How to extract text from a webpage using Selenium WebDriver?

We can extract text from a webpage using Selenium webdriver and save it as a text file using the getText method. It can extract the text for an element which is displayed (and not hidden by CSS). We have to locate the element on the page using any of the locators like id, class, name, xpath, css, tag name, link text or partial link text.

How to copy clipboard content in a string?

Below is the function which can be used to Copy Clipboards content in a String. Clipboard clipboard = Toolkit.getDefaultToolkit ().getSystemClipboard (); This will initialize the clipboard object with default systems clipboard. It checks for transferrable content on the clipboard first then saves it in Result variable.


4 Answers

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();
like image 50
optimistic_creeper Avatar answered Nov 15 '22 08:11

optimistic_creeper


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
like image 21
undetected Selenium Avatar answered Nov 15 '22 10:11

undetected Selenium


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);
        }
    }
}
like image 42
Charlie Avatar answered Nov 15 '22 08:11

Charlie


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.

like image 36
kashgo Avatar answered Nov 15 '22 08:11

kashgo