Using a JavaScript callback function as a parameter for the addJavascriptInterface method in Java

Can Java interact with arbitrary functional objects in JavaScript by calling them as callbacks?

For example, if we have a function called 'access' that is registered to invoke a Java function:

access(function(blabla){
    ...
});

Are there effective techniques for handling anonymous callback functions in Java?

Answer №1

One way to manage individual callback anonymous functions is by using a key for reference, similar to how jsonp operates at times.

JavaScript:

var callbacks = [];
function registerCallback(callback)
{
   callbacks.push(callback);
   return callbacks.length - 1;
}

function getCallback(index)
{
   var callback = callbacks[index];
   callbacks[index] = null;

   TryGCCallbacks();

   return callbacks;
}

//Ensuring preservation of array index positions and resetting the array when empty
function TryGCCallbacks()
{
   var isCallbackRemaining = false;
   for (var i = 0; i < callbacks.length; i++)
   {
      if (callbacks[i] == null) {
         continue;
      }

      isCallbackRemaining = true;
      break;
   }
   if (isCallbackRemaining == false)
   {
      callbacks = []; //reset
   }
}

Java:

@org.xwalk.core.JavascriptInterface
public String TestCallback(String someData, String onSuccess, String onError){
   xwalk.evaluateJavascript("getCallback(" + onSuccess + ")('success');", null);
}

Using this with JavaScript:

var onSuccess = registerCallback(function(r) {
   console.log(r);
});

TestCallback('lalala', onSuccess, null);

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 various ways to encapsulate Vue.js components

I am currently in the process of developing a website that utilizes classic multiple pages powered by blade templates. However, I am looking to incorporate vuejs2 components for more dynamic functionalities. Although things are running smoothly, I am faci ...

Having difficulty refreshing metadata on the client side within Next.js through client-side data retrieval

Having some trouble with updating metadata using NextSeo when fetching data on the client side. useEffect(()=>{ fetch(assetURL) .then((res) => res.json()) .then((data) => { console.log(data); }) .catch((error) => { console.err ...

Ensure that each function is completed before proceeding to the next one

I've encountered an issue with my react app. After a user submits a form, I need a modal to open and the user's response to be stored in state. Then, based on this response, I have to execute some business logic before finally submitting the form ...

Deconstructing a JSON Structure

I'm currently developing a D3 damage per second (DPS) calculator and encountering an issue with a JSON object. The JSON object I receive looks like this: {"Sockets":{"min":1,"max":1}, "Dexterity_Item":{"min":165,"max":165}, "Durability_Cur":{"min":58 ...

Having trouble accessing undefined properties in ReactJs? Specifically, encountering issues when trying to read the property "name"?

I am facing an issue with using the data in my console even though I can log it. The structure of my data object is as follows: {_id: '616bf82d16a2951e53f10da4', name: 'abd', email: '[email protected]', phone: '123456789 ...

Stop the setTimeout function after redirecting in the controller

I am experiencing an issue with my AJAX call as it keeps triggering my controller repeatedly. AJAX function <script type="text/javascript> var stopTime =0; var scoreCheck = function () { $.ajax({ url: "<?php echo 'http:// ...

Is there a way for me to replicate the reloading problem that occurs when a button is clicked within an HTML

Recently, I encountered a problem with our company's Web product where pressing a certain button resulted in the entire page being reloaded. This issue reminded me of a similar situation described on this website. Following the solution provided there ...

What is the best way to retrieve the current value of a header cell, including any nested headers?

My handsontable has headers that include checkboxes and select boxes. How can I access the headers to check the value of a select/checkbox inside the header cell? You can view an example in this JSFiddle (with nested headers - same as my project): http:/ ...

How to validate a <select> element with parsley.js when it is dynamically populated with an object?

I'm struggling to validate a <select> element in my form. With the help of knockout.js, I select a location which then populates the Service Point based on the Location chosen. However, when I try to validate the form using parsley.js after pres ...

How can I access the feed of a single user using the Facebook API

I have yet to experience working with Facebook APIs, but I am interested in developing a basic app that will display posts from a specific Facebook user. I would prefer not to enable login for multiple users, just keep it simple. My goal is to create an a ...

Pass on the touchmove event from the panel to the content using jQueryMobile

Within my interface, I have a link labeled myLink located in a side panel labeled myPanel, along with some content labeled myContent. My goal is to: Tap and hold on the link myLink within the panel myPanel Have the panel myPanel close immediately Add an ...

Strategies for re-rendering a React component when the useState value remains the same or retains its previous value

I am currently using a useState hook to store the value of selectFolderId: const [selectFolderId, useSelectFolderId] = React.useState(documentStore.id) Despite trying to update selectFolderId with the new value from DocumentStore by using a useEffect hook ...

Organizing month and year in angularjs: A step-by-step guide

I have a table with a column for month and year. I need to sort the dates by year. Can someone please help me with this? You can view the code in the provided fiddle. In my case, the date format is "MMMM yyyy". For example, if I have "August 2016", "Septe ...

Issue with displaying marker information on Angular Google Maps

https://i.stack.imgur.com/qUyRo.png I'm in a bit of a pickle trying to figure out how to properly display the information when clicking on a marker. I attempted to include $scope.info in the onClick function, but it still refuses to show up. Could s ...

Encountering a Django Channels issue while loading the JavaScript wrapper

After successfully running the server, the following appeared in my cmd prompt: System check identified no issues (0 silenced). January 21, 2020 - 17:43:42 Django version 3.0.2, using settings 'crm.settings' Starting ASGI/Channels version 2.4.0 ...

Can someone guide me on how to locate and access the port number?

In my Reactjs project root directory, I've created a .env file. This is what's inside my .env file: PORT = 30001 ... In my App.tsx file, I'm trying to access the port like this: const PORT_NUMBER = process.env.PORT; When I run yarn start ...

Inspecting Facebook links

Currently working on a website and interested in incorporating a feature similar to what Facebook has. I'm referring to the link inspector, but I'm not entirely sure if that's its official name. Allow me to provide an example to clarify my r ...

Attempting to dynamically add an image to a template snippet

Struggling with inserting images dynamically from database paths in templates. How can I display them when a user clicks the Show More button on an expense page? New to templates and unsure about syntax. Show More Button displayed in the HTML template sho ...

Retrieve items from a JSON file based on the user input ID in a React project

Hi there, I'm looking for guidance on how to extract items by name from a JSON file based on user input. The JSON file contains both an id and name for each item. My goal is for the user to enter a number, which will then display the corresponding ite ...

Displaying the fields of the selected [object Object] in the console.log

Currently, I am utilizing "express": "3.2.6",, nodeJS v0.10.25, and "express-myconnection": "1.0.4",. The database connection appears to be functioning properly. However, when attempting to query in my view: console.log("Data: " + rows); The output rece ...