How To Use Inject JS Script Activity

How to use Inject JS Script Activity?

Preface: Inject JS Script activity is a very useful activity, but its use case and how to use may not be clear for those who have limited experience with JavaScript.

This guide will explain how to select multiple items using this Activity, which is one of the major use case of this activity (Select Multiple Items Activity should be the first choice and this can be used as a workaround).

How to use Inject JS Script Activity

In order to use Inject Java Script Activity, it is recommend to first create a JavaScript file. The code can be written directly in the ScriptCode property, but its easier to read from file, especially if the code becomes long.

The Javascript code will basically look like one of the two.

function(e){
////
}

OR

function(e,value){
////

}

The Javascript function will receive an variable for html element (e) as input. The Java file has to have 2 arguments in order to accept InputParameter property provided through the Inject Js Script Activity. InputParameter(which is received as value) is always a string.

The code to select multiple items in a multiple selection box is below

function(e, value){
var optionsToSelect = value.split(",");
for ( var i = 0, l = e.options.length, o; i < l; i++ )
{
o = e.options[i];
o.selected = false;
test = o.text;
for( var j = 0; j < optionsToSelect.length; j++){
if(optionsToSelect[j] == o.text){
o.selected = true;
break;
}
}
}
}

The code does below

  1. Splits the InputParameter with comma. Code is written this way because InputParameter has to be a string and it cannot be array of strings.

    1. If comma is used as part of text for the multiple select box of interest, please change the first row value.split(",") and split with something else.

  2. Looks through all the items in the multiple select box, and if it matches any of the value in optionsToSelect, it selects that value



In order for this code to work, the selector has to have webctrl tag='SELECT' in the bottom row. Sample selector being below



Selector should have select tag in the bottom row because this code assumes that the input html element e is "HTML DOM Select Object" and uses its properties. Detail of HTML DOM Select Object is in HTML DOM Select Object . In order to create HTML DOM Select Object, the selector needs to point to the SELECT tag.

3 Likes

I have an example:
1-) attach the browser where the script is going to run

2-)use activity Inject Js Script and write the JS code within quotes:
“function(e){
document.querySelectorAll(‘input’)[0].value = ‘Weather medellin’;
document.querySelector(‘button[aria-label='Buscar con Google']’).click();
return ‘Script Exitoso’
}”

2 Likes