Ways to invoke Java function using Javascript (Client-side)

I have a Java Swing application that handles the User Interface, but requires JavaScript files for hardware testing. The application calls a JavaScript engine to execute functions using the `InvokeFunction()` method.

Currently, I am utilizing the LabJack API which is specifically designed for Java and not JavaScript. While I have already implemented a working code in Java, I now need JavaScript to trigger this Java method.

Is there a way to invoke a Java function from JavaScript code? In other words, is there an equivalent approach in JavaScript?

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");

// Define JavaScript code as a String
String script1 = (String)"function hello(name) {print ('Hello, ' + name);}";

// Evaluate the script
engine.eval(script1);

Invocable inv = (Invocable) engine;

inv.invokeFunction("hello", "Scripting!!" );

To provide further context, let's consider a practical example. Suppose the JavaScript code interacts with an IR Toy to send IR data to a light. My task is to capture the number of flashes generated by the light, a process that can only be achieved through Java implementation. Therefore, I require a way to call the Java method from JavaScript so that both functionalities can be integrated into a single test.

Answer №1

In the transition to Java 8, the JavaScript engine was switched from Rhino to Nashorn, resulting in a change in how Java objects are created.

A versatile method that is applicable to both engines involves passing a Java object to the script using Bindings. This allows the JavaScript code to access and utilize any public method of the object.

Alternatively, the object can be passed as a parameter directly into the script.

EXAMPLE utilizing Bindings

ArrayList<String> myList = new ArrayList<>();
myList.add("Hello");

Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("myList", myList);

String script1 = "function hello(name) {" +
                 "  myList.add(name);" +
                 "  print(myList);" +
                 "}";
engine.eval(script1);

Invocable inv = (Invocable)engine;
inv.invokeFunction("hello", "Scripting!!" );

EXAMPLE utilizing parameters

String script1 = "function hello(myList, name) {" +
                 "  myList.add(name);" +
                 "  print(myList);" +
                 "}";
engine.eval(script1);

ArrayList<String> myList = new ArrayList<>();
myList.add("Hello");

Invocable inv = (Invocable)engine;
inv.invokeFunction("hello", myList, "Scripting!!");

OUTPUT

[Hello, Scripting!!]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the maximum number of slots from a JSON file and implement them into the

I've encountered an issue with my upload form. After uploading and previewing an image, I want to add it to a list as long as the list still has available slots. Here's an example: If the maximum number of slots is set to 5, then you can add up ...

Exploring ways to retrieve information stored in localStorage within an android mobile application

I am currently developing an Android App using phonegap. The app is a simple game that generates random numbers for math problems. If the user answers correctly, their score increases, but if they lose, their name and current score are saved in localStor ...

Regex pattern to replace the zero preceding two times within a string based on distinct criteria

I need to transform the string XY4PQ43 using regex in JavaScript. The output should be XY04PQ0043. Specifically, I want to add a zero prefix to the first number if it is a single digit to ensure it has 2 digits, and for the second number in the string, I w ...

The presence of Vue refs is evident, though accessing refs[key] results in an

I am facing an issue with dynamically rendered checkboxes through a v-for loop. I have set the reference equal to a checkbox-specific id, but when I try to access this reference[id] in mounted(), it returns undefined. Here is the code snippet: let id = t ...

Exploring the benefits of WordPress integration with form caching and dynamic show/hide div

Within my Wordpress (3.8.1) website, I have created a form that includes a checkbox. When this checkbox is clicked, a hidden div appears on the screen, prompting users to provide additional information. The JavaScript code responsible for showing the hidd ...

Menu/navigation bar designed with floating lines and an array of color options

I'm currently working on implementing this specific menu into my Wordpress site. My main concern is figuring out how to customize the hover effect for each navigation item. Currently, the float line changes to red (background-color:#800; height:2px;) ...

Typescript encounters ERROR TS1128: Expecting a declaration or statement

Having trouble with a TypeScript error in my game-details.component.ts file that I've been trying to fix for a couple of hours. It's showing up at line 26, column 54 and everything seems correct to me. Interestingly, when I press CTRL + S in my ...

Implementing a click event listener on an iframe that has been dynamically generated within another iframe

Below is the code I used to attach a click event to an iframe: $("#myframe").load(function() { $(this.contentWindow.document).on('click', function() { alert("It's working properly"); }); }) Everything seems to be working co ...

Navigate through a filtered list of parent items with the use of cursor arrows in AngularJS

My form contains an input with a dropdown, where I display JSON data like this: { "title": "Parent #1", "child" : [ {"title": "Child ##1"}, {"title": "Child ##2"}, {"title": "Child ##3"}, {"title": "Child ##4"} ...

Having trouble running the testng.xml file using the command prompt window

Apologies for the repeated post, but I am struggling to resolve this issue. Despite my attempts to troubleshoot and follow various methods, I have been unable to successfully execute the testng.xml file in the command prompt window. Even after trying diffe ...

reducing the dimensions of the expanding panel in Material UI

I am facing a challenge which requires me to reduce the size of the expansion panel when it is open or expanded. I checked the elements and styles tab, but it seems that we need to override the styles. Has anyone dealt with this scenario before? Here is a ...

Navigating through dynamic elements using Selenium

I'm having trouble extracting boxer information from the flashcore.com website using Selenium. The code I've written doesn't seem to be working properly. Can anyone point out where the error might be? The expectation is that Selenium should ...

Discover the CSS auto height value using JavaScript

Is there a way to utilize JavaScript in determining the value set for auto height in CSS? My development stack includes Grails and jQuery. For instance, consider the following CSS: .tool-preview { height: auto; } ...

Struggling with certain aspects while learning Nodejs and ES6 technologies

Below is an example of using the ES6 method.call() method that is causing an error var obj = { name: "Hello ES6 call", greet: function(somedata) { this.somedata = somedata console.log(this.somedata) ...

Activate the 'swipe back' feature within ion-item upon selecting ion-option-button

In my Ionic project, I created an ion-list with ion-items and added ion-option-buttons: <ion-list> <ion-item class="item " ng-repeat="exercise in exercises" on-double-tap="sendToChangeExercise"> <p><h2>{{exercise. ...

JavaScript popup menu with a redirect URL

I utilized Tinybox from this source for launching a popup webpage. I am hoping that when I click the links on the webpage, the popup will close itself and redirect to the link's URL. Here are my JavaScript and HTML codes: <script type="text/java ...

Angular 8 experiencing unexpected collision issues

Currently, I am utilizing Angular 8 with "typescript": "~3.5.3". My objective is to handle the undefined collision in my code. const { testLocation } = this.ngr.getState(); this.step2 = testLocation && testLocation.step2 ? testLocat ...

Enhance the readability of your Angular/Ionic applications with proper hyphenation

In my Ionic 3 app, I am using an ion-grid. Some words do not fit within the columns and are cut off, continuing on the next row without any hyphens added for proper grammar context. See image https://i.stack.imgur.com/3Q9FX.png. This layout appears quite ...

Barba.js (Pjax.js) and the power of replacing the <head> tag

I have been using barba.js to smoothly transition between pages without having to reload the entire site. If you want to see an example, take a look here. Here is a snippet of code from the example: document.addEventListener("DOMContentLoaded", func ...

Automatically select a value in MUI AutoComplete and retrieve the corresponding object

I recently set up a list using the MUI (v4) Select component. I've received a feature request to make this list searchable due to its extensive length. Unfortunately, it appears that the only option within MUI library for this functionality is the Au ...