0

Here is my Javascript interface:

class WebAppInterface(val context: Context){

    @JavascriptInterface
    fun provideAString():String{
        println("executed from js")
        println("this is text")
        return "this is text"
    }

    @JavascriptInterface
    fun printTheString(s:String){
        println(s)
    }
}

Here's how I add it to the WebView:

webView.addJavascriptInterface(WebAppInterface(this), "Android")

Here's how I call the two functions from JS:

function StringFromAndroid(){
    var string=Android.provideAString();
}

...
...

var currentString=new StringFromAndroid();
Android.printTheString(currentString.string);

Here are the print lines:

I/System.out: executed from js  
I/System.out: this is text
I/System.out: undefined

Expected behavior:

Print lines 1 and 2 demonstrate that provideAString() is being called correctly from JS. Print line 3 shows that printTheString(s) is being called correctly from JS, but that the value of currentString.string inside the WebView is "undefined". The expected behavior is that when var currentString=new StringFromAndroid(); forces a call to Android.provideAString(); via the line var string=Android.provideAString();, that call would return the string "this is text" and set var string to have that value so that resultingly, currentString.string would be "this is text" instead of "undefined".

1 Answer 1

1

Assign the value of Android.provideAString(); to this:

function StringFromAndroid() {
    this.string = Android.provideAString();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. I only work with js once every few months so I always have to relearn how properties work inside "classes". I'll leave the question up anyway.
...on the basis that the title is accurate and my template along with your answer gives a searcher sufficient material to implement this kind of workflow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.