Reputation:
I made HTML file with JavaScript functions in and Android UI to call these functions. I don't know how to call JS in web views on Android. Please help. Example:
//JavaScript
<script>
function doSomething(){
//do something
}
</script>
//Android Java
Button clickButton = (Button) findViewById(R.id.button);
clickButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
//call JS function doSomething()
}
});
Upvotes: 1
Views: 7235
Reputation: 105
First load the page containing JavaScript function(s) , then load the function you want. Example:
//JavaScript
<script type="text/javascript" >
function func(){
alert("Hello World!");
}
</script>
//Android
WebView webView = (WebView) findViewById(R.id.myWebview);
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl("file:///android_asset/HTML.html");
Button clickButton = (Button) findViewById(R.id.button);
clickButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
WebView webView = (WebView) findViewById(R.id.myWebview);
webView.loadUrl("javascript:func();");
}
});
Upvotes: 2
Reputation: 433
It is a duplicate from previous questions. But I will try and give you a starting point.
Before you load your webview(but after you had created an instance of the webview) you need to set a Javascript interface class.
Basically:
mWebView.addJavascriptInterface(WebInterface(this), "Android");
// more settings or whatever
mWebView.loadUrl("yourUrl.html.whatever");
the interface is a class that will live wherever you want, if it is a simple project you might as well keep it inside of the MainActivity class. It is up to you to know how to structure your application, but the basic gist of the class would look like this:
public class WebInterface {
Context mContext;
public WebInterface(Context c) { this.mContext = c;}
@JavascriptInterface
public void showAlert() {
Toast.makeText(mContext, "This is being called from the interface", Toast.LENGTH_SHORT).show();
}
}
Notice that the name of the class is the same name as the one you added to the webview. This is pretty obvious at this point, but you need for them to be the same.
Now, you are probably wondering about the "Android" part. Check this, in your JS code you would do something like this:
<script>
function doSomething(){
Android.showAlert();
}
</script>
Can you see the pattern here? Android is the identifier for the Java code you want to run inside your JS, since the method you defined inside the WebInterface
class is called showAlert()
you would call it inside the WebInterface
by using the Android
identifier. This can be named in any way you want, but for the sake of simplicity I have left it at Android
.
Try and see the other examples made in other SO questions to see if they match what you want to do. In this case, I would say that the one I provided above should be more than enough.
Upvotes: 0