0

I am successully calling a javascript within Vaadin. However how could we pass some parameters to this javascript file.

E.g: below I pass the variable num to the JS file but it does not work.

JAVA:

Div myDiv = new Div();
int num = 1000;
UI.getCurrent().getPage().addJavaScript("src/functparam.js", LoadMode.LAZY);
add(myDiv);

JS file content (functparam.js):

alert('This is a number: ' + num);
soulemane moumie
  • 1,005
  • 1
  • 14
  • 26
  • How would you pass the parameter to that file in JavaScript? – ollitietavainen Jan 10 '23 at 10:11
  • @ollitietavainen that is the question that I have asked and want to know how to achieve it. – soulemane moumie Jan 10 '23 at 13:16
  • When you load a script file, the code inside it gets parsed and executed. You can't pass a parameter to a file from JavaScript, because the file itself is not an entity JavaScript understands. What you might do is create a _function_ that accepts parameters; this function will be stored in the browser's memory and it can be invoked once or many times. – ollitietavainen Jan 11 '23 at 08:37

1 Answers1

1

use GraalVM. The reason is that it enable JS-Java interoperability. you have to download the graalVM via adding as dependency in maven (that's if you use maven build). Then do something like the following to use it:

ScriptEngine scriptEngine = new 
ScriptEngineManager().getEngineByName("javascript");
Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("polyglot.js.allowHostAccess", true);
bindings.put("polyglot.js.allowHostClassLookup", (Predicate<String>) 
YourClass -> true);

scriptEngine.eval("print('hello world')");
scriptEngine.eval("var page = Packages.YourPackage(e.g.: 
com.payments.weeklypayments).YourClass;"+ "print('hello world')");

For external js file:

scriptEngine.eval(new FileReader("src/functparam.js""));

Then in the 'functparam.js', do something like the following:

var  sumOfTwoNumbers = function(){
var variableName = Packages.com.payments.weeklypayments.YourClass;
     print('summing method from java: '+ variableName.summing());
}

Meanwhile, in YourClass.java, you should have a method 'summing()'

@HostAccess.Export
public static int summing(){
    return 112;
}

So, to pass in parameters: you can add params into the method like the following:

@HostAccess.Export
public static int summing(int a, int b){
    return a+b;
}

And then, from 'functparam.js', do something like the following:

var  sumOfTwoNumbers = function(){
var variableName = 
Packages.com.payments.weeklypayments.YourClass;
print ('summing method from java: '+ variableName.summing(3+7));
}
Vincent
  • 41
  • 4