真的不知道为什么这不起作用。基本上,我正在尝试这样做。
public void testJS() {
final WebView webView = (WebView) findViewById(web);
// webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JSInterface(webView), "sample");
webView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
/* Do whatever you need here */
Log.e("chrome", "asdf");
return super.onJsAlert(view, url, message, result);
}
});
webView.loadUrl("javascript:window.sample.doEchoTest();void(0);");
}
这是 JSInterface
public class JSInterface {
WebView mAppView;
public JSInterface(WebView appView) {
this.mAppView = appView;
}
public void doEchoTest() {
Log.e("sample", "test details");
Toast toast = Toast.makeText(mAppView.getContext(), "sample test details", Toast.LENGTH_SHORT);
toast.show();
}
}
javascript 代码永远不会运行。
警报等基本功能:
webView.loadUrl("javascript:alert('sample')");
为什么 webView.loadUrl("javascript:window.sample.doEchoTest();void(0);");
不工作?
最佳答案
只是浏览不同的答案,对此的猜测是您没有公开它以从 JS 访问。您需要为每个方法明确地这样做:
@JavascriptInterface
public void doEchoTest() {
Log.e("sample", "test details");
Toast toast = Toast.makeText(mAppView.getContext(), "sample test details", Toast.LENGTH_SHORT);
toast.show();
}
关于Android webview javascript 界面无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40521418/