gpt4 book ai didi

java - WebView.addJavascriptInterface 不起作用

转载 作者:行者123 更新时间:2023-11-28 10:55:14 24 4
gpt4 key购买 nike

我需要从 Web 响应中调用我的 java 函数:

这是我的代码,请指出我哪里出错了

Activity :

    @InjectView(R.id.loadCardWebView)
android.webkit.WebView webView;

WebViewClient webViewClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
ButterKnife.inject(this);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setBuiltInZoomControls(false);
webView.addJavascriptInterface(new JSInterface(activity), "XYZ");
initWebViewClient();
webView.loadUrl("file:///android_asset/www/response.html");

}

private void initWebViewClient() {
webViewClient = new WebViewClient() {
private int webViewPreviousState;
private final int STARTED = 1;
private final int REDIRECTED = 4;

@Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view,
String urlNewString) {
webViewPreviousState = REDIRECTED;
webView.loadUrl(urlNewString);
return true;
}

@Override
public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
webViewPreviousState = STARTED;
}

@Override
public void onPageFinished(android.webkit.WebView view, String url) {

if (webViewPreviousState == STARTED) {
Log.e(TAG ,RESPONSE URL : " + url);
}

}
};
webView.setWebViewClient(webViewClient);
}

我的 JavaScript 类(class):

public class JSInterface {
private Activity activity;

public JSInterface(Activity activity) {
this.activity = activity;
}

@JavascriptInterface
public void showToast(String string){
Log.e("REACHED","HERE");
Timber.e("REACHED HERE");
}

}

这是一个示例 HTML 文件:

    <html>
<body>
<a href="test_2.html" target="_blank">goto test 2</a>
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

<script type="text/javascript">
function showAndroidToast(toast) {
XYZ.showToast(toast);
}
</script>
</body>
</html>

show 方法函数永远不会被调用。我从服务器收到响应,其中包含类似的代码以从我的 javascript 类调用一个函数。

请帮忙!

提前致谢!

最佳答案

我不确定 Timber.e() 是什么,但您的代码实际上是在尝试显示 toast 消息吗?也许它应该更像......

@JavascriptInterface
public void showToast(String string) {
Toast.makeText(...);
Log.e("REACHED","HERE");
Timber.e("REACHED HERE");
}

关于java - WebView.addJavascriptInterface 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24572774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com