Skip to end of metadata
Go to start of metadata

We have put together some examples of custom scripts that you can use in your recordings.

How to use a code sample?

When adding a custom script in your recording, proceed as follows.

  1. Add the Script action from the Custom Actions group in Actions Library to the Actions flow.
  2. Copy a code sample from this page and insert it into the Script area within the Script action.
  3. Create the input-output variables used in the script in the Recorder Variables tab.

If you have more than one custom script in the recording, you need to define a different method for each action, e.g., CustomScriptAction1 in the example below. The name of the class has to start with a letter.

@CustomScriptAction(
   input = ['my_timezone'],    
   output = 'resdate'
)

def CustomScriptAction1() {

def now = new Date()
resdate=RDateTime.fromRepresentation(now.format("yyyy-MM-dd HH:mm:ss", TimeZone.getTimeZone("${my_timezone}")), "yyyy-MM-dd HH:mm:ss;en-US;${my_timezone}")

}

General

Working with Logical Operators

Multiple If conditions COMMUNITY

The code sample has been shared by ivan.swiegers on the Community Forum. For more information, refer to this forum topic.

Variables (name – type)Code block 
  • failcheck1 – Boolean
  • failcheck2 – Boolean
  • failcheck3 – Boolean
  • failcheck4 – Boolean
  • failcheck5 – Boolean
  • finalfailcheck – Boolean
@CustomScriptAction(
	input = ['failcheck1','failcheck2','failcheck3','failcheck4','failcheck5'],
	output = 'finalfailcheck'
)

def customScript() {

	if( (failcheck1) == (RBoolean.fromCanonical('true')) || (failcheck2) == (RBoolean.fromCanonical('true'))
	 || (failcheck3) == (RBoolean.fromCanonical('true')) || (failcheck4) == (RBoolean.fromCanonical('true'))
	 || (failcheck5) == (RBoolean.fromCanonical('true'))) {

	   finalfailcheck = RBoolean.fromCanonical('true')

	} else {

	   finalfailcheck = RBoolean.fromCanonical('false')
	}

} 

Comparing more than one variable in If-Else condition COMMUNITY

The code sample has been shared by Bonnero on the Community Forum. For more information, refer to this forum topic.

This custom script is an example that does a comparison of arithmetic operations. You could also perform other operations, e.g. compare text, regexp, etc., and make as many logical operations as you want. The script outputs true if ALL conditions are true.Otherwise, it outputs false.

Variables (name – type)Code block
  • condition1 – Number
  • condition2 – Number
  • condition3 – Number
  • boolean_result – Boolean
@CustomScriptAction(
	input = ['condition1', 'condition2', 'condition3'],
	output = 'boolean_result'
)

def customScript() {

	def c1 = RNumber.of(condition1)
	def c2 = RNumber.of(condition2)
	def c3 = RNumber.of(condition3)

  
    if(
        (c1 < c2)  &&    // "&&" is the logical operator AND
        (c2 <c3)   &&    // This structure allows you avoid nested "IF" statements in recorder
        (c2*c3 < 10)     // by using one BOOLEAN result in one IF branch.
       ){
    
       def boolean_result = RBoolean.of(true)
     
     } else{
       
       def boolean_result = RBoolean.of(false)
       }

}

Working with Strings

Using regexp to create substring COMMUNITY

The code sample has been shared by tinwy on the Community Forum. For more information, refer to this forum topic.

The matcher object depends on the number of capturing groups inside the regexp that was used. For example, if you have three capturing groups denoted by the brackets ( … ):

  • matcher[0][0] refers to everything that matched the regexp
  • matcher[0][1] refers to the first capture in the match
  • matcher[0][2] refers to the second capture in this match
Variables (name – type)Code block
  • original_str – String
  • result_str – String
@CustomScriptAction(
        input = ['original_str'],
        output = 'result_str'
    )

    def regexSubstring() {
        def regex = /(\d\d\d\d)-(\d\d)(-\d\d[a-zA-Z])?/
        def matcher = (original_str =~ /$regex/)
        result_str = RString.of(matcher[0][0])
    }

Getting file name from path COMMUNITY

The code sample has been shared by tinwy on the Community Forum. For more information, refer to this forum topic.

import org.apache.commons.io.FilenameUtils

 @CustomScriptAction(
     input = ['input_str'],
     outout = 'output_str'
 )

 def getFileNameFromPath() {
     output_str = RString.of(FilenameUtils.getBaseName(input_str.toString()))
 }

Miscellaneous

Modifying time period WORKFUSION

To generate the date based on today's date, you can either modify the number of days or the number of months.

Variables (name – type)Code block
  • date1 – DateTime
  • date2 – DateTime
Modifying the day in the date
@CustomScriptAction(
	input = ['date1'],
	output = 'date1'
)
def customeScript() {
	date1 = date1.minus(java.time.Duration.ofDays(1))
}
Modifying the month in the date
@CustomScriptAction(
    input = ['date1'],
    output = 'date2'
)
def customeScript() {
    date2 = date1.plus(java.time.Period.ofMonths(1))
}

Downloading file from remote server WORKFUSION

Variables (name – type – default value)Code block
@CustomScriptAction(
    input = ['web_url'],
    output = 'local_file_link'
)

def customScript() {
	def link = downloadFileOnAgent(web_url.toString())
	local_file_link = RString.of(link)
}

Selecting text and copying to clipboard WORKFUSION

Variables (name – type – default value)Code block
@CustomScriptAction(
	input = ['form_url']
)

def customScript() {
	openAndFocus('notepad.exe', 3000, 250)
	sendKeys('New line')
	selectAllTextAndCopy()

	openIE(form_url.toString())
	$(byXpath('//div[8]/input')).pressCtrlV()
}

Clicking with some keyboard combination pressed WORKFUSION

@CustomScriptAction

def customScript() {

    // selecting multiple elements by SHIFT + DOWN
	sendKeys(Keys.chord(Keys.COMMAND, 'e'))
    keyboard().pressKey(Keys.SHIFT)
    sendKeys(Keys.DOWN, Keys.DOWN)
    keyboard().releaseKey(Keys.SHIFT)

}

Switching between windows/tabs

These custom scripts can be applied to both desktop and web automation scenarios when switching between the windows/tabs.

Switching to the last window
@CustomScriptAction(
)

def customScript() {
  driver().switchToLastWindow()
}
Switching to the next window
@CustomScriptAction(
)

def customScript() {
   switchToNextWindow()
}
Switching to the previous window
@CustomScriptAction(
)

def customScript() {
   switchToPrevWindow()
}

Getting table data based on index COMMUNITY

The code sample has been shared by Bonnero on the Community Forum. For more information, refer to this forum topic.

Variables (name – type)Code block
  • data_table – Table
  • row_pointer – Number
  • col_pointer – Number
  • cell_value – String
@CustomScriptAction(
	input = ['data_table','row_pointer','col_pointer'],
	output = 'cell_value'
)
	def customScript() {
		def cell_value = data_table.get(row_pointer,col_pointer)
}

Applying math functions and equations

Variables (name – type – default value)Code block
  • a – Number – 4
  • result – Number – 0
@CustomScriptAction(
	input = ['a'],
	output = 'result'
)

def customScript() {
	def b = RNumber.of(Math.min(12.123, 12.456))
	def c = RNumber.of(Math.pow(2, 3))
	result = a + b + c + Math.abs(-5.6) + Math.sqrt(4)
}

Color image detection COMMUNITY

The code sample has been shared by alasbleis on the Community Forum. For more information, refer to this forum topic.

Currently, Intelligent Automation Cloud does not support color image detection. This custom script works as a workaround returning the color under the mouse as (r,g,b,a) (int value between 0 and 255). You can easily change it to return the color at a desired location of the screen. At the final step, compare the color with the targeted one and click on the object (a regular mouse click) if the condition is fulfilled.

import java.awt.Robot
import java.awt.image.BufferedImage
import java.awt.Rectangle
import java.awt.PointerInfo
import java.awt.MouseInfo
import java.awt.Point
import java.awt.Color
import java.io.File
import javax.imageio.ImageIO
@CustomScriptAction(
    output = 'color_string'
)
  
def customScript() {
	//Get mouse position 
    Point mousePos = MouseInfo.getPointerInfo().getLocation();
	
	//Take a screenshot to be able to access pixel value
    Robot r = new Robot();
    Rectangle rect = new Rectangle((int)mousePos.x,(int)mousePos.y,1,1)
    BufferedImage im = r.createScreenCapture(rect);
	
	//Get the color of the screenshot. In that case we want the color at mousePos hence the coordinates (0,0) of the image
	//Change this to your desired location if you don't want the color under the mouse
    Color rgb_color = new Color(im.getRGB(0,0));
	
	//Convert the rgb int color to red,green,blue,alpha
    int red = rgb_color.getRed();
    int green = rgb_color.getGreen();
    int blue = rgb_color.getBlue();
    int alpha = rgb_color.getAlpha();
	
	//Store the result as a string to return multiple variable
    String color = "("+red+","+green+","+blue+","+alpha+")";
    
	//You can use this to save the screenshot taken for debugging purpose
    //File outputfile = new File("PATH_TO_SAVE_FOR_DEBUG/test_wf_im.jpg");
    //ImageIO.write(im, "jpg", outputfile);
    
	//return the color as a string
    color_string = RString.of(color)
}

Finding last date of previous month WORKFUSION

Variables (name – type)Code block

last_date – DateTime

import java.time.*

@CustomScriptAction(
   output = 'last_date'
)

def customScript() {

        ZonedDateTime zonedDateTime = RDateTime.now().asZonedDateTime();
        boolean isLeapYear = Year.isLeap(zonedDateTime.getYear());
        RDateTime.of(zonedDateTime.withDayOfMonth(ZonedDateTime.now().minusMonths(1).getMonth().length(isLeapYear)));            
}

Get current week number WORKFUSION

Variables (name – type)Code block

week_number – Number

@CustomScriptAction(
  output = 'week_number'
)
def WeekNumber() { 
   Calendar calendar = Calendar.getInstance();
   def WeekofYear = calendar.get(Calendar.WEEK_OF_YEAR);
   week_number = RNumber.of(WeekofYear)
}

Web Automation

Standard browser navigation WORKFUSION

Variables (name – type - default value)Code block
@CustomScriptAction(
	input = ['web_url_one', 'web_url_two'],
	output = 'page_headings' 
)

def customScript() {
	openIE(web_url_one.toString())
	driver().navigate().to(web_url_two.toString())
	back()
	forward()
	refresh()
	def headings = $$(byXpath('//h2')).getTexts().join(',')
	page_headings = RString.of(headings)
}

Sending GET request to any URL

Variables (name – type – default value)Code block
@CustomScriptAction(
    input = ['web_url'],
    output = 'content'
)

def customScript() {
	def html = web_url.toURL().text
	content = RString.of(html)
}

Sending GET request and parsing response COMMUNITY

The code sample has been shared by stuti.verma on the Community Forum. For more information, refer to this forum topic.

Variables (name – type – default value)Code block
	import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;

    @CustomScriptAction(
        input = ['web_url'],
        output = 'response_of_url'
    )
     
    def customScript() {
        URL obj = new URL(String.valueOf(web_url));
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        int responsecode = con.getResponseCode();
        if (responsecode == HttpURLConnection.HTTP_OK) { 
           BufferedReader in1 = new BufferedReader(new InputStreamReader(con.getInputStream()));
           String inputLine;
           StringBuffer response = new StringBuffer();
           while ((inputLine = in1.readLine()) != null) {
               response.append(inputLine);
           }
           in1.close();

           response_of_url = RString.of(response.toString());

        } else {
           response_of_url = RString.of("GET request not worked");
        }
    }

Hovering over element on web page

@CustomScriptAction(

)

def customScript() {
	$(byXpath('your-xpath-for-menu-item')).hover()
}

Using element selectors other than XPath to click

Variables (name – type – default value)Code block
  • link_text – String – Link Test
  • option_value – String – AFR

  • select_id – String – #continents
@CustomScriptAction(
	input = ['link_text', 'option_value', 'select_id'])

def customScript() {
	openIE('https://rpa-tutorial.s3.amazonaws.com/trainings/iframe/form.html')
	$(byLinkText(link_text.toString())).click()
	sleep(3000)
	back()

	// Select specific option by its value in dropdown selected by its id
	$(select_id.toString()).selectOptionByValue(option_value.toString())
	sleep(3000)
}

Checking web page on HTTP status code WORKFUSION

Variables (name – type)Code block
  • url – String
  • code – String
@CustomScriptAction(
    input = ['url'],
    output = 'code'
)
 
def customScript() {
    def status_code = url.toURL().openConnection().responseCode
    code = RNumber.of(status_code)
    }

Assertions WORKFUSION

Variables (name – type – default value)Code block
  • element_id – String – #continent
  • element_class – String – .container__small
@CustomScriptAction(
    input = ['element_id', 'element_class']
)

def customScript() {
    $(element_id.toString()).should(APPEAR)

    // Wait until element with a specific class appears on the page
    $(element_class.toString()).waitUntil(EXIST)
}

Executing custom JavaScript WORKFUSION

Variables (name – type – default value)Code block
  • question – String – Do you like Groovy?
  • answer – String – Yes/No
  • user_choice – String
@CustomScriptAction(
	input = ['question', 'answer'],
	output = 'user_choice'
)

def customScript() {
	openIE('https://wikipedia.org')
	def choice = executeJavaScript("return prompt(arguments[0], arguments[1])", question as String, answer as String)
	user_choice = RString.of(choice)
}

Desktop Automation

Getting object value WORKFUSION

Variables (name – type)Code block
  • variable_name – String
@CustomScriptAction(
	output = 'variable_name'
)
def customScript() {
	variable_name = RString.of($("object_selector").getText())
}

Getting Excel cell coordinates based on cell text WORKFUSION

Variables (name – type)Code block
  • text – String
  • name – String
@CustomScriptAction(
input = ['text'],
output = 'name'
)

def customScript() {

name = RString.of($("[CLASS:DataItem; TEXT:${text}]").getAttribute('Name'))

}

Finding last modified file WORKFUSION

Variables (name – type)Code block

folder – String

file_name – String

@CustomScriptAction(
   input = ['folder'],
   output = 'file_name'
)

def customScript() { 
                        
        def File[] files = new File(folder.toString()).listFiles()
        Date dt = new Date(0);            
        
        for (File file : files) {
           if (file.isFile())
           {
             Date date = new Date(file.lastModified());      

             if (date.after(dt))
             {  
               dt = date;                      
               file_name = RString.of(file.getName().toString());     
             }
           }     
        }      
}

Renaming files COMMUNITY

The code sample has been shared by s_hagivara on the Community Forum. For more information, refer to this forum topic.

Variables (name – type – default value)Code block
  • file1 – String – path to the file to be renamed 
  • file2 – String – path to the renamed file
import java.io.File;

@CustomScriptAction(
        input = ['file1', 'file2']
    )

def customScript() {
 
def original_file = new File (file1.toString())
def new_file = new File (file2.toString())
original_file.renameTo(new_file);
}

Get User Desktop path COMMUNITY

The code sample has been shared by ShawnLi on the Community Forum. For more information, refer to this forum topic.

Variables (name – type – default value)Code block
  • result_str – String – path to the desktop folder
@CustomScriptAction(
    output = 'result_str'
)
def customScript() {
    def String desktop_path = System.properties.'user.home' + "\\Desktop"
    result_str = RString.of(desktop_path)
}

Get local Computer Name WORKFUSION

Variables (name – type – default value)Code block
  • computer_name – String – name of user local PC
import java.net.InetAddress

@CustomScriptAction(
	output = 'computer_name'
)
def FindComputerName() {
	def localhost = InetAddress.getLocalHost()
	computer_name = RString.of(localhost.getHostName().toString())
}

Get Excel Sheet name WORKFUSION

Variables (name – type – default value)Code block
  • sheet_index – Number – the index of the sheet which you want to get
  • sheet_name – String
@CustomScriptAction(
input = ['sheet_index'],
output = 'sheet_name'
)

def customScript() {

sheet_name = RString.of($("[CLASS:TabItem;INSTANCE:${sheet_index}]").getAttribute('Text'))
sheet_name = sheet_name.replaceIgnoreCase("Sheet tab", "")
}
  • No labels