When incorporating
JavaScript into a CSPro application, it is possible to create function wrappers in CSPro logic that appear as
user-defined functions but call into JavaScript when invoked. To do this, use the
declare keyword to declare the function, specifying its return type and parameters. Using the
JS modifier after
function indicates that the function will be found in JavaScript's
global execution context, not in CSPro logic. For example:
In CSPro logic, you can now write function calls as if this were a CSPro logic function, with any CSPro arguments
converted to their JavaScript equivalents when the call is executed. If the JavaScript function returns a value, it is converted to the CSPro type specified in the function declaration. If the JavaScript function does not return a value, the CSPro function returns the default return value for
user-defined functions (
default or a blank string).
The JavaScript function's existence is not known until runtime. If the function does not exist when called, a runtime error is displayed and the function returns the default return value.
It is also possible to execute JavaScript functions using the
JS.invoke function.
When called from JavaScript, if the number of arguments is fewer than what the CSPro function requires, an exception is thrown. If too many arguments are provided, the additional arguments are ignored by CSPro. When the function is executed within the JavaScript environment, any arguments to the function are
converted to their CSPro equivalents, with exceptions thrown when no conversion routine exists, or if the conversion failed.
The CSPro function's return value is converted to its JavaScript equivalent when the function terminates.
function dateDifferenceInDays(dateFirst, dateLast) {
const millisecondsPerDay = 24 * 60 * 60 * 1000;
const dateDifference = new Date(dateLast) - new Date(dateFirst);
return Math.floor(dateDifference / millisecondsPerDay);
}
...it is possible to wrap it using
declare and
JS and execute it from CSPro logic:
PROC GLOBAL
declare function JS numeric dateDifferenceInDays(string dateFirst, string dateLast);
PROC DEMO
// execute the wrapped function as if it were a CSPro function
errmsg("%d", dateDifferenceInDays("2000-11-07", "2024-11-05"));
// execute the JavaScript function using JS.invoke
errmsg("%s", JS.invoke("dateDifferenceInDays", "2000-11-07", "2024-11-05"));
// execute the equivalent CSPro built-in function
errmsg("%d", datediff(20001107, 20241105, "d"));
This example uses
JS.setValue to add a function to JavaScript that, when executed, calls into CSPro logic to call the
accept function. The example uses
JS.eval to show how this could be executed from within JavaScript:
function getCSProVersion(diagnosticsCallback) {
return diagnosticsCallback("version");
}
...it is possible to call into JavaScript and then have JavaScript call back into CSPro.