我想访问一个webapp作为Android应用程序,因为我所做的只是通过使用webview调用该webapp的url。 Webapp包含一个js变量,我想将该变量访问到orroids MainActivity中,如何通过使用android MainActivity访问并为不同webapp中的js变量赋值。以下是我的MainActivity代码片段,
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.getSettings().setDatabaseEnabled(true);
mWebview.getSettings().setLoadWithOverviewMode(true);
mWebview.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
mWebview.setScrollbarFadingEnabled(false);
mWebview.loadUrl("http://www.mywebapp.com");
setContentView(mWebview);
}
我的主要问题是如何通过androids MainActivity访问并为js变量赋值,这是在不同的app / html中?
答案 0 :(得分:2)
// Call method in js or html
Android.getImageUrl("text");
// add this line in main activity.
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
// js value get in this method.(add this method in activity)
public class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void getImageUrl(String text) {
// js value get here.
}
}
}