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

Discover the hidden content within a div by hovering over it

Here is an example of a div: <div style="width:500px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quis pulvinar dui. Nulla ut metus molestie, dignissim metus et, tinc ...

Filtering data in AngularJS by parsing JSON records

I have a JSON file containing restaurant information and I need to display the data by grouping them based on their respective address fields. For example, all restaurants with the address 'Delhi' should be shown first, followed by those from &ap ...

Creating a TypeScript rule/config to trigger an error when a React Functional Component does not return JSX

I've encountered a recurring issue where I forget to include a return statement when rendering JSX in a functional component. Here's an example of the mistake: const Greetings = function Greetings({name}) { <div>Greetings {name}</div& ...

What is the process for uploading a text file into JavaScript?

I'm currently facing an issue with importing a text file from my local computer into JavaScript in order to populate HTML dropdowns based on the content of the file. Despite spending considerable time searching for solutions on stack overflow, I haven ...

Decrease the height of a div element from the top with the use of jQuery

My goal is to manipulate the height of the div #target when a specific event is triggered, either by reducing/increasing its height from the top or by hiding/showing its content. However, I'm struggling to find a solution to achieve this. The current ...

Struggling with parsing JSON in Java?

I am working with a ListView that contains 3 TextView, each responsible for displaying the title, author, and published date of books from an API listing. The issue I am facing is related to extracting the authors' information from a JSONArray. My in ...

View a pink map on Openlayers 2 using an iPhone

I am currently working on a project where I am trying to track my location using my smartphone and display it on a map. To achieve this, I am utilizing openlayers 2. However, I am encountering an issue. When I implement the code below in a Chrome Browser ...

Steps for implementing a conditional statement to handle an empty string in HTML

I need to figure out how to display a different message if my string is empty. Can anyone help me with this? <div class="padding" id="dealBorder"> <pre id="informationDealText"><pan class="inner-pre" style="font-size: 24px; color: whi ...

Utilizing on() in conjunction with a map function

Currently, I am in the process of refactoring my code and have decided to revisit how I handle on events by utilizing mapping. Below is a snippet of what I currently have: $('img#sorc').on({ mousemove: function (e) { alert('tes ...

What is the best way to connect multiple web pages together?

Hello everyone, I could really use some assistance with a problem I'm facing. As a newcomer to web development, I have a question about navigation bars. I've successfully created a basic webpage with a navigation bar, but now I'm unsure how ...

working with the express locals function

I've been trying to come up with a function that can access local variables, such as this one: // Retrieve user data by ID res.locals.findUser = function(user_id) { models.user.findOne({ '_id': user_id }, function(err, user) ...

Allow images to be uploaded using the browser-policy package in Meteor

Can anyone help me figure out how to use Sir Trevor JS in Meteor for uploading images without encountering this error message? When attempting to load the image 'blob:http%3A//localhost%3A3000/a28ef7dc-ee51-4290-9941-6b8fc317e685', I am receivin ...

Is it possible for a script utilizing selenium grid to access and manipulate files within the node VM?

Currently, I am in the process of conducting tests on a website that is expected to send data to an installed program. To streamline this process, my plan involves utilizing Selenium grid to execute the script across multiple virtual machines. This will e ...

Pressing the button will add text into the input field

Below is a jsfiddle link showcasing the current issue I am trying to address: http://jsfiddle.net/YD6PL/61/ Here is the HTML code snippet: <input type="text> <input type="text> <input type="text> <div> <button class="buttons"& ...

Utilizing JavaScript to bring JSON image data to the forefront on the front-end

In my quest to utilize JavaScript and read values from a JSON file, I aim to showcase the image keys on the front-end. To provide clarity, here's an excerpt from the JSON dataset: { "products": {"asin": "B000FJZQQY", "related": {"also_bought": ...

Unable to retrieve the value stored in the global variable

I recently updated my code to use global variables for two select elements in order to simplify things. Previously, I had separate variables for values and innerHTML which felt redundant. Now, with global variables like user and group initialized at docum ...

Ways to stop user authentication in Firebase/Vue.js PRIOR to email verification

I am currently working on a Vue.js and Firebase authentication interface with an email verification feature. The setup is such that the user cannot log in until they click the verification link sent to the email address provided during the login process. ...

Is there a method to introduce a line break for each piece of data that is shown?

I am currently working with an array and have successfully displayed it on the screen. My inquiry is whether it is feasible to insert a line break for each of the data points it presents. { name: "cartItems", label: "Product Name ...

Identify data points on the line chart that fall outside the specified range with ng2-charts

I'm struggling to figure out how to highlight specific points on a line chart that fall outside a certain range. For instance, if the blood sugar level is below 120, I want to display that point as an orange dot. If it's above 180, I want to show ...

Incorporating Bootstrap Navbar into a create-react-app project

I recently created a new project using create-react-app. To incorporate Bootstrap into my project, I followed these steps: npm install --save bootstrap@3 Next, I imported Bootstrap in my root file index.js: import 'bootstrap/dist/css/bootstrap.css& ...