Is the return type for EvaluateJavaScript restricted to only String values?

One of the challenges I faced was creating a common function in Kotlin that could invoke a JavaScript function based on the command provided.

    fun evaluateJsFromNative(command: String, 
        webView: WebView, function: (value : String) -> Unit ) {
        webView.evaluateJavascript("(function() { return $command; })();") {
            s -> function(s)
        }
    }

However, this function only allows a value of type String to be returned. If I wanted to make it more generic and allow for Boolean, Int, or no return type at all, how could I achieve that?

For example, attempting to change the return type to Boolean resulted in an error in the function(s) section due to the requirement of s being a String.

    fun evaluateJsFromNative(command: String, 
        webView: WebView, function: (value : Boolean) -> Unit ) {
        webView.evaluateJavascript("(function() { return $command; })();") {
            s -> function(s)
        }
    }

Answer №1

The issue you're encountering stems from the fact that your function is set up to accept a Boolean parameter, yet you're passing it a String parameter at s -> function(s). This discrepancy arises because WebView.evaluateJavascript() defines its input as a String.

You are unable to alter the type of function that webView.evaluateJavascript() accepts. However, you can convert the String parameter to a Boolean before invoking your function.

Here's an example utilizing your second implementation which accepts a Boolean:

fun evaluateJsFromNative(command: String, 
    webView: WebView, function: (value : Boolean) -> Unit ) {
    webView.evaluateJavascript("(function() { return $command; })();") {
        s -> function(s.toBoolean())
    }
}

// usage
evaluateJsFromNative(mycommand, mywebview) {
    Log.d("SomeTag", "Value=$it")
}

However, this approach is quite straightforward and limited since you could provide any string as a command, not just valid Javascript. The documentation states that evaluateJavascript() will only execute the function parameter if the Javascript evaluation results in something other than null (if Javascript is disabled in your WebView, it will pass 'null' to your function). Therefore, even with correct Javascript input, there may still be issues converting s to a Boolean. Handling unexpected inputs and types requires significant effort.

If you require a more generic solution, consider the following code snippet, where you need to expand the when statement to support all relevant types (and implement error handling):

fun <T : Any> evaluateJsFromNative(command: String,
                             webView: WebView, klass: Class<T>, function: (value : Any?) -> Unit ) {
    webView.evaluateJavascript("(function() { return $command; })();") {
        s -> if (s.convert(klass) != null) function(s.convert(klass)!!)
    }
}

fun <T> String.convert(klass: Class<T>) : Any? {
    when (klass.name.toString()) {
        "boolean" -> return this.toBoolean()
        else -> return null
    }
}

// usage
evaluateJsFromNative(mycommand, mywebview, Boolean::class.java) {
    Log.d("SomeTag", "Value=$it")
}

In this illustration, you must specify the expected output type from the Javascript, and subsequently parse the result from a string to the specified type. Defining the supported types in advance is necessary. While a simpler conversion method would be preferable, Kotlin lacks such functionality according to discussions on the Kotlin forums.

I trust this clarifies things for you.

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

What is the best way to determine if a text matches any of the elements in

Seeking assistance with a demo I am working on. How can I perform a precise comparison between test and the elements in an array arr1? var arr1 = ['noël','noel']; var test = 'noel; if(){ } <script src="https://ajax.google ...

How do I initiate a custom button click event in React from an event handler in another component?

I have a unique React application that utilizes the Material UI framework for its user interface design. Specifically, I have developed a specialized button component that customizes the default Material UI button and integrates with Redux. Within the ren ...

What is the process for forming a series of arrays from one singular array?

If I have a large array consisting of numbers from 1 to 18, is there a simple method to split it into pairs like [1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [13,14] for n=2? The special case of n=2 is all I need. ...

Customize a div's background color with an Angular directive

Imagine having a div element: <div id="wrapper"> some text </div> How can you create an angular directive that changes the background based on user input? For instance, you might have tried: <div id="wrapper" color temperature="51"> ...

Mutating properties in VueJs

When I attempted to move a section for filtering from the parent component to a child component, I encountered this error message: "Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a ...

I am experiencing issues with the middleware not functioning properly after implementing a custom application with Next.js

I'm currently diving into Next.js version 13 and attempting to customize the app based on the standard documentation. However, it seems that the middleware isn't being invoked as expected. I suspect there might be something wrong with my implemen ...

Utilizing a combination of HTML, AJAX, and PHP, transfer an HTML input array via AJAX to a PHP webpage

Despite trying numerous similar solutions, none of them have proven effective for my issue. Within a form, users can input an unspecified amount of select options that can be added as needed using AJAX. My goal is to post this array to a PHP page via AJAX ...

Locate commas within quotation marks using regex and replace them with their corresponding HTML entity

When dealing with a string like this: "Hello, Tim" Land of the free, and home of the brave I want it to be transformed into: "Hello&#44; Tim" Land of the free, and home of the brave This should be a simple task, but I'm struggling to find th ...

Utilizing custom i18n blocks for Vue 3 and Vuetify 3 to enhance locale messages

Looking to localize messages separately for each component? Check out this example for Vue 2. But how can it be done for Vue 3 and Vuetify 3? Here's what I've tried: package.json "dependencies": { "@mdi/font": "6.5 ...

The error message `java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.getParts()` indicates that the

I have included the Maven dependencies servlet-api 2.5 and javaee-web-api 6.0, but I am still encountering exceptions. Any assistance in resolving this issue would be greatly appreciated! Thanks. java.lang.NoSuchMethodError: javax.servlet.http.H ...

Python-JavaScript Integration Problem

I'm a beginner when it comes to Javascript, Python, and PHP. In my Javascript program, I have a button that triggers a Python script and displays the returned value on the screen. My goal is to steer clear of using Jquery and Json. Here are the snipp ...

Javascript continues to execute even after the designated element has been eliminated or substituted

I'm currently working on a WordPress auction site using WooCommerce that needs a countdown timer to display when a specific product auction is ending. Below is the JavaScript code for the countdown timer: const getElem = elem => document.q ...

How does Java justify permitting arrays with zero length indices in the middle?

javac permits the following syntax: int[][][] i = new int[4][0][2]; with a zero-length index that restricts access beyond it. 1) It is impossible to access the third dimension. A zero length dimension as the last dimension (int[][][] i = new int[4][2][0 ...

Retrieving the event name from a CustomEvent instance

Looking to retrieve the name of a CustomEvent parameter in a function, which is basically the string it was created with (new CustomEvent('foo')) If you need a reference, check out https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent ...

Problem with ngStyle: Error indicating that the expected '}' is missing

I encountered an error in the Chrome console when trying to interpret the code below: <div [ngStyle]="{'width': '100%'; 'height': '100%'; 'background-size': 'cover'; 'background-repeat&ap ...

Traditional Javascript is unable to add elements to the DOM

I am currently facing an issue with my website that is built in Expression Engine. The back-end of the website contains a code snippet responsible for handling a JavaScript request and generating a page based on that request. One of the challenges I am en ...

Combine strings in PHP with an alert box in JavaScript

Is there a way to concatenate a string in a JavaScript alert box? I want the first part of the alert box to be a simple text, while the second part is a string retrieved from a MySQL table. $myname = $row["name"]; echo ' <scri ...

What is the best way to create a selection input using buttons and save the chosen option in the state?

Check out this snippet showcasing 3 buttons const [role, setRole] = React.useState('') const [active, setActive] = React.useState(false) <Grid container spacing={1}> <Grid item xs={4}> <Button variant='plain&apos ...

Ways to navigate a JSON file and automatically populate an ImageView based on the JSON data

Hello, I need help figuring out how to dynamically load ImageView based on the data received from JSON. Sometimes I receive 8 images to display, other times it's 17. The challenge is loading the correct number of ImageViews based on the JSON data. Cur ...

Comparison Between Web Applications and Smartphone Applications (iPhone, Windows Mobile, Android/Nexus Applications)

Q: What sets apart Web Applications from SmartPhone Applications (such as Iphone, Windows Mobile, Android/Nexus Application) and in what specific ways do they distinguish themselves? For instance, Q: Why is there a need for a mobile version of Web Applic ...