Reputation: 961
I am creating an Android App and I have the following javascript which is within "str8red.com" loaded from a webview:
<script>var name = "bob", age = 30;</script>
I have a textbox that I can set using:
textView.setText("Static Text")
I would like to set my textbox to the variable from the javascript var name
. I have tried to utilise webview.loadUrl("javascript:Android.getIds(Ids);");
and evaluateJavascript
with no success. I have also tried to follow numerous guides on stack overflow and the the web without success.
Below is the code for loading the webview:
wv = (WebView) findViewById(R.id.wv);
//Enable JavaScript
wv.getSettings().setJavaScriptEnabled(true);
wv.setFocusable(true);
wv.setFocusableInTouchMode(true);
//Set Render Priority To High
wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
wv.getSettings().setDomStorageEnabled(true);
wv.getSettings().setDatabaseEnabled(true);
wv.getSettings().setAppCacheEnabled(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
//Load Url
wv.loadUrl("https://str8red.com/");
Upvotes: 1
Views: 1044
Reputation: 961
Ok,
So, it turns out that for anything from KitKat upwards it is as simple as:
wv.evaluateJavascript("fromAndroid()", new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
textView.setText(value);
My gap in understanding was I was trying to access the javascript variables directly but this is not what evaluateJavascript is doing. It seems that it actually runs the chosen javascript function, fromAndroid()
in this example, and whatever is returned is stored on the native app as a variable.
Below is my javascript code incase it helps:
<script>
function fromAndroid(){
return "{% if user.is_authenticated %}true{% else %}false{% endif %} 1 0";
}
</script>
Happy to be created by an expert but I hope this may help someone in the future.
Upvotes: 1