I have created an application in which i am using webview and loading a simple static html page. I am calling a java script function from activity but i am unable to call a function from java script. I have tried few of the link , but it didn't work .
Javascript Callback function pass to Android
I cannot call an android function from javascript
Here is my code. Thank you in advance.
acitivity_main.xml
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Call JavaScript Function"
android:onClick="callJavaScript" />
android:id="@+id/myWebView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
index.html
function displayMessage(){
document.getElementById('test1').innerHTML = 'This is from java script.';
Android.returnResult();
}
Hello World
Main activity has following two functions .
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = (WebView) this.findViewById(R.id.myWebView);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(new JavaScriptHandler(this), "Android");
myWebView.loadUrl("file:///android_asset/index.html");
}
public void callJavaScript(View view) {
Log.v(null, "Calling java Script");
myWebView.loadUrl("javascript:displayMessage()");
}
This is the JavaScriptHandler class
public class JavaScriptHandler {
Context mContext;
public JavaScriptHandler(Context context) {
mContext = context;
}
public void returnResult() {
Log.v(null, "result received");
}
}
解决方案
Make it
@JavascriptInterface
public void returnResult() {
Log.v(null, "result received");
}
This annotation allows exposing methods to JavaScript.