Value from Clipboard (copied link) to be assigned to Groovy variable

Hello,

Please advise how I can assign the copied to buffer value to the variable? I have a ‘Copy Link’ functionality (button) in a target web app.

Thank you in advance!

You just want to read a text from the clipboard. For that, use this

You can execute any JavaScript from Katalon script using [WebUI] Execute JavaScript | Katalon Docs

1 Like

It is likely that you are blocked by a dialog:
dialogue

The following article tells us how to solve this problem: You want to configure the preference of Chrome browser:

Yes, I have faced this problem and got stuck here.
@kazurayam Could you please advise how to configure these preference of Chrome browser?

Thank you in advance!

import org.junit.Assert
import com.fasterxml.jackson.core.JsonProcessingException
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import com.neovisionaries.ws.client.WebSocketException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONObject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;


prefs.put("profile.content_settings.exceptions.clipboard", getClipBoardSettingsMap(1));

private static Map<String,Object> getClipBoardSettingsMap(int settingValue) throws JsonProcessingException {
	Map<String,Object> map = new HashMap<>();
	map.put("last_modified",String.valueOf(System.currentTimeMillis()));
	map.put("setting", settingValue);
	Map<String,Object> cbPreference = new HashMap<>();
	cbPreference.put("[*.],*",map);
	ObjectMapper objectMapper = new ObjectMapper();
	String json = objectMapper.writeValueAsString(cbPreference);
	logger.info("clipboardSettingJson: " + json);
	return cbPreference;
}


WebUI.executeJavaScript (" navigator.clipboard.readText().then((copiedText) => { 	console.log(copiedText);  });", null)

Sorry, I am busy now. I can’t do experiment for you.

Pragmatic solution: when you see that dialogue, you can just manually click the “Allow” button. Then your test script will happily continue running.

スクリーンショット 2023-01-25 20.58.58

@yakovlieva.olena as a side note, you should never use such approach in your tests (copy/paste from clipboard) unless you are prepared for serious headaches.

There are few discussions here and there but you should be aware that, the clipboard himself in is not a browser feature but an OS feature.

Therefore, altough some JS voodoo appears to work, in certain cases, from javascript side in browser, such is heavvily dependant on the underthehood OS.
And top of that on browser paranoid approaches on sandboxing (which is not a bad thing)

You have been warned!
Are you testing the AUT or … how the AUT is working on X OS running on Y browser?

The problem is that this alert can’t be processed. ‘No alert found’ in Katalon console

WebUI.acceptAlert()

driver.switchTo( ).alert( );
WebUI.acceptAlert()

this works only with the diaglog triggered by JavaScript’s alert statement: Window: alert() method - Web APIs | MDN

And the problem dialog is not the one triggered by JavaScript. It is displayed by the browser itself. So WebUI.acceptAlert can not work with it.

Such will ever evolve over time in new flakiness.

I do understand the scope of testing mentioned:

I have a ‘Copy Link’ functionality (button) in a target web app.

but, if i will be in your shoes, I will take out such from the scope of automated test.

yeah, we as QA engineers, sometime try to do more than developpers achieve and tend to automate everything.
but sometime we should simply stick with manual testing, do it some time to time and for the rest trigger the automation.

i will rather test in an automation what the button intend to do. the rest will be passed to the developper if is not working on a certain combination of OS/browser

just my two cents.

Thank you for your answer! I feel more confident now leaving (or postponing) this step.

You should do that.
And you should do a bit more.
In my ‘previous life’ as a QA engineer, I was always pressed to implement ‘End-To-End’ testing …

But I stand!
Why?
Because my vission of End-To-End was to test each and every step/resource needed, intensively.
And later, how they glue togheter (yet more tests)
The Businnes Analyst vision was to fully automated an user behavior, regardless of the platform used and some many other factors, from the moment the user wake-up from the bed until he get drunk later after a full day of work (or whatever else)

Guess who won?

I have done a development. See the following GitHub repository.

The repository is a Katalon project where I used my chromedriverfactory, v0.6.6. This jar enables you configure Chrome to grant javascript to read Clipboard. This project assumes you are a seasoned java programmer if you are to reuse it.

I have developed it for fun. I wanted to extend my chromedriverfactory capability. I haven’t used this in real business at all.

1 Like

@yakovlieva.olena

I changed the title of this discussion

“Value from buffer (copied link) to be assigned to Groovy variable”

to

“Value from Clipboard (copied link) to be assigned to Groovy variable”

to make it easier to search.

An alternative code. The behaviour is just the same as the previous code :

import com.kms.katalon.core.configuration.RunConfiguration
import com.kms.katalon.core.testobject.ConditionType
import com.kms.katalon.core.testobject.TestObject
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI

import groovy.json.JsonSlurper

TestObject makeTestObject(String xpath) {
	TestObject tObj = new TestObject(xpath)
	tObj.addProperty("xpath", ConditionType.EQUALS, xpath)
	return tObj
}

String url = "https://codepen.io/RevCred/pen/vxXrww"
TestObject locatorIFrame = makeTestObject("//iframe[@id='result']")
TestObject locatorButton = makeTestObject("//div[@id='copy']")

Object chromePrefs = new JsonSlurper().parseText("""
{
  "profile.content_settings.exceptions.clipboard" : {
    "[*.],*": {
      "last_modified": "1576491240619",
      "setting": 1
    }
  }
}
""")
RunConfiguration.setWebDriverPreferencesProperty('prefs', chromePrefs)

WebUI.openBrowser("")
WebUI.navigateToUrl(url)
WebUI.verifyElementPresent(locatorIFrame, 10)
WebUI.switchToFrame(locatorIFrame, 10)
WebUI.verifyElementPresent(locatorButton, 10)
WebUI.click(locatorButton)

// execute a JavaScript script in the Chrome browser, which will read a text
// from the clipboard and return it to the caller
String js = """
    return navigator.clipboard.readText();
"""
String text = WebUI.executeJavaScript(js, null)

WebUI.comment("text read from the clipboard: " + text)
assert text.startsWith("https://staging.revolutioncredit.com/signupc/")

WebUI.closeBrowser()

This code implements the Chrome preference as an inline JSON string.