javascript - 如何在 webview 的 java 代码中使用 javascript 值?
问题描述
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("alert('hi'); var elem =
document.querySelector('.price__container__discount__sales_price').firstChild.innerHTML;"
,null);
btn.setText(elem);
}
我想在setText方法中使用在js中声明的elem变量到java代码中
解决方案
如果您想从加载到 webview 中的 javascript 代码中获取值,我将公开一个带有 @JavascriptInterface 注释的方法,该方法将从您的 javascript 中收集该值。
如何做到这一点的一个例子如下:
本国的
//Make sure to enable these settings
webviewSettings.setJavaScriptEnabled(true);
addJavascriptInterface(YOUR_INTERFACE_CLASS, YOUR_INTERFACE_NAME);
@JavascriptInterface
public void getSalesPrice(String value) {
//Here you will get the value from your javascript
}
JAVASCRIPT
function sendDataToNative(data) {
YOUR_INTERFACE_NAME.getSalesPrice(data);
}
推荐阅读
- c# - 无法使用以下搜索条件找到 X.509 证书 仅在发布 API 时
- sql - 将字符串转换为数字,从“:”左侧拉到“:”右侧
- pyqt5 - QWebEngineView 和背景透明度
- ios - 如何使用 Siri 套件扩展启用钥匙串共享?
- r - 相同的 y 轴变量、散点图和长格式
- linkedin - 领英Campaing API
- postgresql - Hibernate:如何将 tsrange 映射到 Java 实体列/列?
- html - div 宽度加起来小于 100%
- javascript - 将鼠标悬停在图表上的选定路径上
- python - django 自定义 UserManager 中的 self.model()