在我的网站上,用户必须接受 cookie 才能继续。有一个用于检查同意的 API:
(window.consentApi?.consent("tidio-chat") || Promise.resolve()).then(() => {
console.log("Consent given, do something...!");
});
一旦用户接受了所有cookie,就会调用此回调。
如何通过 webview 从 Android 应用程序监听此回调?我尝试过使用
evaluateJavascript
但行不通。
我怀疑我必须使用
addJavascriptInterface
,但我不知道如何在||
条件下使用它。有人能给我提示吗?谢谢。
像这样处理 android 端:
public class MyActivity extends AppCompatActivity {
private WebView myWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = findViewById(R.id.myWebView);
myWebView.getSettings().setJavaScriptEnabled(true);
CookieManager.getInstance().setAcceptCookie(true);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
// Load your website URL
myWebView.loadUrl("https://your-website.com");
}
public class WebAppInterface {
Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void notifyConsent() {
// Do something when consent is given (e.g., Toast)
Toast.makeText(mContext, "Cookies Accepted!", Toast.LENGTH_SHORT).show();
}
}
}
在您的 Web api 中进行如下更改:
(window.consentApi?.consent("tidio-chat") || Promise.resolve()).then(() => {
console.log("Consent given, do something...!");
if (window.Android) {
window.Android.notifyConsent();
}
});
要通过 WebView 监听 Android 应用程序的回调,您确实可以使用
addJavascriptInterface
在 JavaScript 和 Java 代码之间进行通信。以下是实现这一目标的方法:
public class ConsentInterface {
@JavascriptInterface
public void onConsentGiven() {
// This method will be called when consent is given
Log.d("Consent", "Consent given, do something...!");
// Add your logic here
}
}
WebView webView = findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new ConsentInterface(), "Android");
(window.consentApi?.consent("tidio-chat") || Promise.resolve()).then(() => {
// Call the Java method when consent is given
Android.onConsentGiven();
});
通过此设置,当调用
consent
API 并且用户接受 cookie 时,将从 JavaScript 代码中调用 onConsentGiven
类中的 ConsentInterface
方法。然后,您可以在该 Java 方法中执行任何所需的操作。
如果尚未替换,请务必将
R.id.webView
替换为您的 WebView 的 ID。此外,请确保您通过根据需要将 JavaScript 接口限制为特定方法和类来处理使用 addJavascriptInterface
的潜在安全隐患。