Pass Variable from Android to JavaScript Launched in Webview

Pass variable from Android to JavaScript launched in WebView

First of all you need to load the script only once (your onClick is loading it every time), then call loadUrl("javascript:initialize(" + myNumber + ");")

Pass variables from Android Activity to JavaScript

You need to implement javascriptinteface in webview like this;

WebView webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());

Bundle extras = getIntent().getExtras();
double x = 0, y = 0;
if (extras != null) {
x = extras.getDouble("x");
y = extras.getDouble("y");
}
webView.addJavascriptInterface(new JavaScriptInterface(x, y), "JSInterface");
webView.loadUrl("file:///android_asset/index.html");

Create This Javainteface in your activity

public class JavaScriptInterface {

double x, y;

JavaScriptInterface(double x, double y) {
this.x = x;
this.y = y;
}

public double getXValue() {
return x;
}

public double getYValue() {
return y;

}
}

In you index.html

var x, y;
function init(){
x = JSInterface.getXValue();
y = JSInterface.getYValue();
}

Passing a string from Android to JS in a WebView via @JavascriptInterface

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

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

Pass JavaScript Value from Webview to Activity?Android

HTML JS CODE

<script type="text/javascript">
function Pa(value) {
//value is the param received from onClick
NewFUN.Print(value); //call the android method with value param
}
</script>

<center>
<h3>Sample HTML</h3>
<div id="content">Click on Button To thermal print</div>
<div>
<input type="button" onClick="Pa('26997')" /><br/>
</div>
</center>

& change your android code to be like this

@JavascriptInterface
public void Print(final String stringFromWebView) {
//use stringFromWebView
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure you want to leave to next screen?");
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent chnIntent = new Intent(Main_web.this, Print_activity.class);
chnIntent.putExtra("STRING_DATA", stringFromWebView);
startActivity(chnIntent);
}
});
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}

In next activity receive the web JS response by using

String data = getIntent().getStringExtra("STRING_DATA");

at oncreate

Passing String variable from Java to JavaScript via Webview (vice versa)

Calling Java/Kotlin code from JavaScript

There's a feature of Android WebView called Javascript Interface which is what you should look for.

It allows you to run your java/kotlin code from your javascript code.

You can define an interface by

val webView: WebView = findViewById(R.id.webview)
webView.addJavascriptInterface(WebAppInterface(this), "Android")

Here, WebAppInterface defines the methods which you want to be called from javascript.

/** Instantiate the interface and set the context  */
class WebAppInterface(private val mContext: Context) {
/** Show a toast from the web page */
@JavascriptInterface
fun showToast(toast: String) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show()
}
}

"Android" here is an interface added to your webview and can be used in your javascript code to call Android methods.

Once this is done, you can call the methods from your javascript,

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>

Keep in mind that the interface callbacks are not always called in main thread. So, if you want to perform any UI operations, make sure you use runOnUiThread.

Calling JavaScript function from Java/Kotlin code

There's a feature of Android WebView called Evaluate Javascript for API 19+ to call your javascript functions from java/kotlin code.

For example, for the following javascript:

<script type="text/javascript">
function printName(name) {
console.log(name);
}
</script>

You can write this code to call this JS function:

yourWebview.evaluateJavascript("printName(\'TEST\')")


Related Topics



Leave a reply



Submit