Issue
I want to get the return value of a javascript function inside Android webview to be made accessible to the android application and get it converted to a string.
So I put this code:
String fileName = MyWebView.loadUrl("javascript:android.onData(returnFileName())");
But then it shows this error: Incompatible types. Found: 'void', required: 'java.lang.String'.
How to fix this?
Edit: Actually I have an input field where the user can enter the name of a file generated as base64(data:)(which was actually a blob but I converted it). On Firefox and Chrome the downloaded file have the name user entered (I used a.download=document.getElementById.value for that) but on webview while downloading(by setting Download listener) the file I had to process the (data:) to a working URI. Now I would like to add the name entered by User to the downloaded file. For that I need to get the value of input field inside webview to Android application.
Thanks in advance.
Solution
So this is what worked for me after experimenting with the answer by @Introspective; I am posting here because any future visitors may find it helpful.
Instead of onPageFinished()
, I put evaluateJavascript()
inside download listener. A JsonReader was required as the result is a JSON value.
MyWebView.setDownloadListener((url, userAgent, contentDisposition, mimeType, contentLength) -> {
if (url.startsWith("data:")) {
MyWebView.evaluateJavascript("returnfileName()", string -> {
JsonReader jsonReader = new JsonReader(new StringReader(string));
jsonReader.setLenient(true);//this is needed because I am returning a single value
if(jsonReader.peek() != JsonToken.NULL) {
String fileName = jsonReader.nextString();
//Now I can use the String fileName as I wish.
//Rest of the code
}
}
Javascript function returnFileName()
function returnfileName(){
var fileName;
if (document.getElementById("id of input field").value===""){
fileName = "Default file name in case user didn't enter any filename";
}
else{
fileName = document.getElementById("id of input field").value;}
}
return fileName;
}
Since evaluateJavascript()
is a void, I had to put rest of the code to download the file inside the evaluateJavascript()
itself, because otherwise String fileName will not be accessible for them (void doesn't have a return value).
Answered By - ADasGH
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.