我尝试了很多方法,但是无法在WebView.loadurl()中将JavaScript函数作为字符串调用
我已经尝试过使用自己的html文件,但是它可以正常工作,但是现在我想在JavaScriptInrteface的webView.loadurl(string)中以字符串形式调用JS函数,但是不起作用。
我无权访问html代码,也不需要从诸如html或html或javascript之类的网络文件中调用。
我也尝试过
Hide WebView until JavaScript is done
Android JS in WebView.loadUrl()
但是对我没有任何帮助。
这是我的代码。
MainActivity:
webView = (WebView) findViewById(R.id.webView);
webView.loadUrl(AppData.link);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
AppData.link = url;
view.loadUrl(url);
return false;
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("file:///android_assets/error.html");
}
public void onPageFinished(WebView view, String url) {
// do your stuff here
swipe.setRefreshing(false);
webView.loadUrl("javascript: window.Android.showToast("+url+");");
}
});
browserSettings();
private void browserSettings() {
webView.addJavascriptInterface(new JavaScriptInterface(ctx),"Android");
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
//String test = "javascript:(function(){ Android.showToast("+url+");})();";
//Log.e(TAG, test);
//webView.loadUrl(test);// this is also not working
//Here I need to get blob URL and pass it to javascriptInterface
//but this function is not wroking
webView.loadUrl("javascript:"
+ "var FunctionTwo = function () {"
+ " window.Android.showToast("+url+");"
+ "};"
+ "FunctionTwo();");
}
});
webView.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath());
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
}
JavaScriptInteface.java
public class JavaScriptInterface {
private Context context;
private NotificationManager nm;
public JavaScriptInterface(Context context) {
this.context = context;
}
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
}
}